xorm

package module
v0.0.0-...-f09dff6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 6, 2016 License: BSD-3-Clause Imports: 38 Imported by: 0

README

xorm

xorm是一个简单而强大的Go语言ORM库. 通过它可以使数据库操作非常简便。

说明

  • 本库是基于原版 xormhttps://github.com/go-xorm/xorm 的定制增强版本,由于本定制版有第三方库依赖(原版xorm无任何第三方库依赖),原版xorm要保持对第三方库零依赖特性,所以只好单独开了本Github库。
  • 本库的相关定制功能是为了解决更简单的进行复杂SQL调用和一些特殊业务需求场景而开发的。
  • 本定制版ORM相关核心功能和原版保持一致,会跟随原版xorm更新。
  • 定制功能采用针对原版弱侵入性代码实现。

特性

  • 支持Struct和数据库表之间的灵活映射,并支持自动同步
  • 事务支持
  • 同时支持原始SQL语句和ORM操作的混合执行
  • 支持类ibatis方式配置SQL语句(支持xml配置文件和pongo2模板2种方式)
  • 支持动态SQL功能
  • 支持一次批量混合执行多个CRUD操作,并返回多个结果集
  • 使用连写来简化调用
  • 支持使用Id, In, Where, Limit, Join, Having, Table, Sql, Cols等函数和结构体等方式作为条件
  • 支持级联加载Struct
  • 支持数据库查询结果直接返回Json字符串和xml字符串
  • 支持缓存
  • 支持根据数据库自动生成xorm的结构体
  • 支持记录版本(即乐观锁)

驱动支持

目前支持的Go数据库驱动和对应的数据库如下:

安装

推荐使用 gopm 进行安装:

gopm get github.com/xormplus/xorm

或者您也可以使用go工具进行安装:

go get -u github.com/xormplus/xorm

快速开始

  • 第一步创建引擎,driverName, dataSourceName和database/sql接口相同
//xorm原版标准方式创建引擎
engine, err := xorm.NewEngine(driverName, dataSourceName)

//您也可以针对特定数据库及数据库驱动使用类似下面的快捷方式创建引擎
engine, err = xorm.NewPostgreSQL(dataSourceName)
engine, err = xorm.NewSqlite3(dataSourceName)
  • 创建引擎,且需要使用类ibatis方式配置SQL语句,参考如下方式
var err error
engine, err = xorm.NewPostgreSQL("postgres://postgres:root@localhost:5432/testdb?sslmode=disable")

if err != nil {
	t.Fatal(err)
}

/*--------------------------------------------------------------------------------------------------
1、使用SetSqlMapRootDir()方法设置SqlMap配置文件总根目录,返回Engine实例本身,如采用sql/xormcfg.ini配置文件中的配置,可直接使用InitSqlMap()初始化
2、使用SetSqlTemplateRootDir()方法设置SqlTemplate模板配置文件总根目录,返回Engine实例本身,如采用sql/xormcfg.ini配置文件中的配置,可直接使用InitSqlTemplate()初始化
3、SqlMap配置文件总根目录和SqlTemplate模板配置文件总根目录,可代码指定,也可在配置文件中配置,代码指定优先级高于配置
--------------------------------------------------------------------------------------------------*/

//初始化SqlMap配置,可选功能,如应用中无需使用SqlMap,可无需初始化
err = engine.SetSqlMapRootDir("./sql/oracle").InitSqlMap()
if err != nil {
	t.Fatal(err)
}
//初始化动态SQL模板配置,可选功能,如应用中无需使用SqlTemplate,可无需初始化
err = engine.SetSqlTemplateRootDir("./sql/oracle").InitSqlTemplate(xorm.SqlTemplateOptions{Extension: ".xx"})
if err != nil {
	t.Fatal(err)
}

//开启SqlMap配置文件和SqlTemplate配置文件更新监控功能,将配置文件更新内容实时更新到内存,如无需要可以不调用该方法
err = engine.StartFSWatcher()
if err != nil {
	t.Fatal(err)
}

  • db.InitSqlMap()过程

    • 如使用SetSqlMapRootDir()方法指定SqlMap配置文件总根目录,则InitSqlMap()方法按指定目录遍历SqlMapRootDir所配置的目录及其子目录下的所有xml配置文件(配置文件样例
    • 如未使用SetSqlMapRootDir()方法指定SqlMap配置文件总根目录,则读取程序所在目下的sql/xormcfg.ini配置文件(样例)中的SqlMapRootDir配置项,遍历SqlMapRootDir所配置的目录及其子目录下的所有xml配置文件(配置文件样例
    • 解析所有配置SqlMap的xml配置文件
    • 配置文件中sql标签的id属性值作为SqlMap的key,如有重名id,则后加载的覆盖之前加载的配置sql条目
    • 配置文件中sql配置会读入内存并缓存
    • 由于SqlTemplate模板能完成更多复杂组装和特殊场景需求等强大功能,故SqlMap的xml只提供这种极简配置方式,非ibatis的OGNL的表达式实现方式
  • db.InitSqlTemplate()过程

    • 如使用SetSqlTemplateRootDir()方法指定SqlTemplate模板配置文件总根目录,则InitSqlTemplate()方法按指定目录遍历SqlTemplateRootDir所配置的目录及其子目录及其子目录下的所有stpl模板文件(模板文件样例
    • 如指使用SetSqlTemplateRootDir()方法指定SqlTemplate模板配置文件总根目录,则InitSqlTemplate()方法读取程序所在目下的sql/xormcfg.ini配置文件(样例)中的SqlTemplateRootDir配置项,遍历SqlTemplateRootDir所配置的目录及其子目录下的所有stpl模板文件(模板文件样例
    • 解析stpl模板文件
    • stpl模板文件名作为SqlTemplate存储的key(不包含目录路径),如有不同路径下出现同名文件,则后加载的覆盖之前加载的配置模板内容
    • stpl模板内容会读入内存并缓存
  • 支持最原始的SQL语句查询

/*-------------------------------------------------------------------------------------
 * 第1种方式:返回的结果类型为 []map[string][]byte
-------------------------------------------------------------------------------------*/
sql_1 := "select * from user"
results, err := engine.Query(sql_1)

/*-------------------------------------------------------------------------------------
 * 第2种方式:返回的结果类型为 []map[string]interface{}
-------------------------------------------------------------------------------------*/
sql_2_1 := "select * from user"
results, err := engine.Sql(sql_2_1).Query().List()
//当然也支持这种方法,将数据库中的时间字段格式化,时间字段对应的golang数据类型为time.Time
//当然你也可以在数据库中先使用函数将时间类型的字段格式化成字符串,这里只是提供另外一种方式
//该方式会将所有时间类型的字段都格式化,所以请依据您的实际需求按需使用
results, err := engine.Sql(sql_2_1).QueryWithDateFormat("20060102").List()

sql_2_2 := "select * from user where id = ? and age = ?"
results, err := engine.Sql(sql_2_2, 7, 17).Query().List()

//此Query()方法返回对象还支持ListPage()方法和Count()方法,这两个方法都是针对数据库查询出来后的结果集进行操作
//此Query()方法返回对象还支持Xml()方法、XmlIndent()方法和Json()方法,相关内容请阅读之后的章节
//ListPage()方法并非数据库分页方法,只是针对数据库查询出来后的结果集[]map[string]interface{}对象取部分切片
//例如以下例子,是取结果集的第1条到第50条记录
results, err := engine.Sql(sql_2_2, 7, 17).Query().ListPage(1,50)
//例如以下例子,是取结果集的第13条到第28条记录
results, err := engine.Sql(sql_2_2, 7, 17).Query().ListPage(13,28)
//此Count()方法也并非使用数据库count函数查询数据库某条件下的记录数,只是针对Sql语句对数据库查询出来后的结果集[]map[string]interface{}对象的数量
//此Count()方法也并非Engine对象和Session对象下的Count()方法,使用时请区分场景
count, err := engine.Sql(sql_2_2, 7, 17).Query().Count()

/*-------------------------------------------------------------------------------------
  第3种方式:执行SqlMap配置文件中的Sql语句,返回的结果类型为 []map[string]interface{}
-------------------------------------------------------------------------------------*/
sql_id_3_1 := "sql_3_1" //配置文件中sql标签的id属性,SqlMap的key
results, err := engine.SqlMapClient(sql_3_1).Query().List()

sql_id_3_2 := "sql_3_2"
results, err := engine.SqlMapClient(sql_id_3_2, 7, 17).Query().List()

sql_id_3_3 := "sql_3_3"
paramMap_3_3 := map[string]interface{}{"id": 7, "name": "xormplus"}
results1, err := engine.SqlMapClient(sql_id_3_3, &paramMap_3_3).Query().List()

/*-------------------------------------------------------------------------------------
 * 第4种方式:执行SqlTemplate配置文件中的Sql语句,返回的结果类型为 []map[string]interface{}
-------------------------------------------------------------------------------------*/
sql_key_4_1 := "select.example.stpl" //配置文件名,SqlTemplate的key

//执行的 sql:select * from user where id=7
//如部分参数未使用,请记得使用对应类型0值,如此处name参数值为空字符串,模板使用指南请详见pongo2
paramMap_4_1 := map[string]interface{}{"count": 1, "id": 7, "name": ""}
results, err := engine.SqlTemplateClient(sql_key_4_1, &paramMap_4_1).Query().List()

//执行的 sql:select * from user where name='xormplus'
//如部分参数未使用,请记得使用对应类型0值,如此处id参数值为0,模板使用指南请详见pongo2
paramMap_4_2 := map[string]interface{}{"id": 0, "count": 2, "name": "xormplus"}
results, err := engine.SqlTemplateClient(sql_key_4_1, &paramMap_4_2).Query().List()

/*-------------------------------------------------------------------------------------
 * 第5种方式:返回的结果类型为对应的[]interface{}
-------------------------------------------------------------------------------------*/
var categories []Category
err := engine.Sql("select * from category where id =?", 16).Find(&categories)

/*-------------------------------------------------------------------------------------
 * 第6种方式:返回的结果类型为对应的[]interface{}
-------------------------------------------------------------------------------------*/
sql_id_6_1 := "sql_6_1"
var categories []Category
err := engine.SqlMapClient(sql_id_6_1, 16).Find(&categories)

sql_id_6_2 := "sql_6_2"
var categories []Category
paramMap_6_2 := map[string]interface{}{"id": 25}
err := engine.SqlMapClient(sql_id_6_2, &paramMap_6_2).Find(&categories)

/*-------------------------------------------------------------------------------------
 * 第7种方式:返回的结果类型为对应的[]interface{}
-------------------------------------------------------------------------------------*/
//执行的 sql:select * from user where name='xormplus'
sql_key_7_1 := "select.example.stpl" //配置文件名,SqlTemplate的key
var users []User
paramMap_7_1 := map[string]interface{}{"id": 0, "count": 2, "name": "xormplus"}
err := engine.SqlTemplateClient(sql_key_7_1, &paramMap_7_1).Find(&users)
  • 注:

    • 除以上7种方式外,本库还支持另外3种方式,由于这3种方式支持一次性批量混合CRUD操作,返回多个结果集,且支持多种参数组合形式,内容较多,场景比较复杂,因此不在此处赘述。
    • 欲了解另外3种方式相关内容您可移步批量SQL操作章节,此3种方式将在此章节单独说明
  • 采用Sql(),SqlMapClient(),SqlTemplateClient()方法执行sql调用Find()方法,与ORM方式调用Find()方法不同(传送门:ORM方式操作数据库),此时Find()方法种的参数,即结构体的名字不需要与数据库表的名字映射,但字段名需要和数据库中的字段名字做映射。使用Find()方法需要自己定义查询返回结果集的结构体,如不想自己定义结构体可以使用Query()方法,返回[]map[string]interface{},两种方式请依据实际需要选用。

    举例:多表联合查询例子如下

//执行的SQL如下,查询的是article表与category表,查询的表字段是这两个表的部分字段
sql := `SELECT
	article.id,
	article.title,
	article.isdraft,
	article.lastupdatetime,
	category.name as categoryname
FROM
	article,
	category
WHERE
	article.categorysubid = category. ID
AND category. ID = 4`

//我们可以定义一个结构体,注意字段名和上面执行的SQL语句字段名映射
//当然你还可以给这个结构体加更多其他字段,但是如果执行上面的SQL语句时只会被赋值对应数据类型的零值
type CategoryInfo struct {
	Id             int       `xorm:"not null pk autoincr unique INTEGER"`
	Title          string    `xorm:"not null VARCHAR(255)"`
	Categoryname   string    `xorm:"not null VARCHAR(200)"`
	Isdraft        int       `xorm:"SMALLINT"`
	Lastupdatetime time.Time `xorm:"not null default 'now()' DATETIME"`
}

var categoryinfo []CategoryInfo

//执行sql,返回值为error对象,同时查询的结果集会被赋值给[]CategoryInfo
err = db.Sql(sql).Find(&categoryinfo)
if err != nil {
	t.Fatal(err)
}
t.Log(categoryinfo)
t.Log(categoryinfo[0].Categoryname)
t.Log(categoryinfo[0].Id)
t.Log(categoryinfo[0].Title)
t.Log(categoryinfo[0].Isdraft)
t.Log(categoryinfo[0].Lastupdatetime)

  • 第3种和第6种方式所使用的SqlMap配置文件内容如下
<sqlMap>
	<sql id="sql_3_1">
		select * from user
	</sql>
	<sql id="sql_3_2">
		select * from user where id=? and age=?
	</sql>
    <sql id="sql_3_3">
		select * from user where id=?id and name=?name
	</sql>
    <sql id="sql_id_6_1">
		select * from category where id =?
	</sql>
    <sql id="sql_id_6_2">
		select * from category where id =?id
	</sql>
</sqlMap>
  • 第4种和第7种方式所使用的SqlTemplate配置文件内容如下,文件名:select.example.stpl,路径为engine.SqlMap.SqlMapRootDir配置目录下的任意子目录中。使用模板方式配置Sql较为灵活,可以使用pongo2引擎的相关功能灵活组织Sql语句以及动态SQL拼装。
select * from user
where
{% if count>1%}
id=?id
{% else%}
name=?name
{% endif %}
  • 执行一个SQL语句
//第1种方式
affected, err := engine.Exec("update user set age = ? where name = ?", age, name)

//第2种方式
sql_2 := "INSERT INTO config(key,value) VALUES (?, ?)"
affected, err := engine.Sql(sql_4, "OSCHINA", "OSCHINA").Execute()

//第3种方式
sql_i_1 := "sql_i_1" //SqlMap中key为 "sql_i_1" 配置的Sql语句为:INSERT INTO config(key,value) VALUES (?, ?)
affected, err := engine.SqlMapClient(sql_i_1, "config_1", "1").Execute()

sql_i_2 := "sql_i_2" //SqlMap中key为 "sql_i_2" 配置的Sql语句为:INSERT INTO config(key,value) VALUES (?key, ?value)
paramMap_i := map[string]interface{}{"key": "config_2", "value": "2"}
affected, err := engine.SqlMapClient(sql_i_2, &paramMap_i).Execute()

//第4种方式
sql_i_3 := "insert.example.stpl"
paramMap_i_t := map[string]interface{}{"key": "config_3", "value": "3"}
affected, err := engine.SqlTemplateClient(sql_i_3, &paramMap_i_t).Execute()
  • 注:

    • 除以上4种方式外,本库还支持另外3种方式,由于这3种方式支持一次性批量混合CRUD操作,返回多个结果集,且支持多种参数组合形式,内容较多,场景比较复杂,因此不在此处赘述。
    • 欲了解另外3种方式相关内容您可移步批量SQL操作章节,此4种方式将在此章节单独说明
  • 支持链式读取数据操作查询返回json或xml字符串

//第1种方式
var users []User
results,err := engine.Where("id=?", 6).Search(&users).Xml() //返回查询结果的xml字符串
results,err := engine.Where("id=?", 6).Search(&users).Json() //返回查询结果的json字符串

//第2种方式
sql := "select * from user where id = ?"
results, err := engine.Sql(sql, 2).Query().Json() //返回查询结果的json字符串
results, err := engine.Sql(sql, 2).QueryWithDateFormat("20060102").Json() //返回查询结果的json字符串,并支持格式化日期
results, err := engine.Sql(sql, 2).QueryWithDateFormat("20060102").Xml() //返回查询结果的xml字符串,并支持格式化日期

sql := "select * from user where id = ?id and userid=?userid"
paramMap := map[string]interface{}{"id": 6, "userid": 1} //支持参数使用map存放
results, err := engine.Sql(sql, &paramMap).Query().XmlIndent("", "  ", "article") //返回查询结果格式化后的xml字符串

//第3种方式
sql_id_3_1 := "sql_3_1" //配置文件中sql标签的id属性,SqlMap的key
results, err := engine.SqlMapClient(sql_id_3_1, 7, 17).Query().Json() //返回查询结果的json字符串

sql_id_3_2 := "sql_3_2" //配置文件中sql标签的id属性,SqlMap的key
paramMap := map[string]interface{}{"id": 6, "userid": 1} //支持参数使用map存放
results, err := engine.SqlMapClient(sql_id_3_2, &paramMap).Query().Xml() //返回查询结果的xml字符串

//第4种方式
sql_key_4_1 := "select.example.stpl"
paramMap_4_1 := map[string]interface{}{"id": 6, "userid": 1}
results, err := engine.SqlTemplateClient(sql_key_4_1, &paramMap_4_1).Query().Json()
  • 支持链式读取数据操作查询返回某条记录的某个字段的值
//第1种方式
id := engine.Sql(sql, 2).Query().Results[0]["id"] //返回查询结果的第一条数据的id列的值

//第2种方式
id := engine.SqlMapClient(key, 2).Query().Results[0]["id"] //返回查询结果的第一条数据的id列的值
id := engine.SqlMapClient(key, &paramMap).Query().Results[0]["id"] //返回查询结果的第一条数据的id列的值

//第3种方式
id := engine.SqlTemplateClient(key, &paramMap).Query().Results[0]["id"] //返回查询结果的第一条数据的id列的值
  • 事务处理,当使用事务处理时,需要创建Session对象,另外当使用Sql()、SqlMapClient()、SqlTemplateClient()方法进行操作时也推荐手工创建Session对象方式管理Session。在进行事物处理时,可以混用ORM方法和RAW方法。注意如果您使用的是mysql,数据库引擎为innodb事务才有效,myisam引擎是不支持事务的。示例代码如下:
session := engine.NewSession()
defer session.Close()
// add Begin() before any action
err := session.Begin()
user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
_, err = session.Insert(&user1)
if err != nil {
    session.Rollback()
    return
}
user2 := Userinfo{Username: "yyy"}
_, err = session.Where("id = ?", 2).Update(&user2)
if err != nil {
    session.Rollback()
    return
}

_, err = session.Exec("delete from userinfo where username = ?", user2.Username)
if err != nil {
    session.Rollback()
    return
}

_, err = session.SqlMapClient("delete.userinfo", user2.Username).Execute()
if err != nil {
    session.Rollback()
    return
}

// add Commit() after all actions
err = session.Commit()
if err != nil {
    return
}
  • SqlMap及SqlTemplate相关功能API
//设置SqlMap文件总根目录,可代码指定,也可在配置文件中配置,如使用配置文件中的配置则无需调用该方法,代码指定优先级高于配置
engine.SetSqlMapRootDir()
//设置SqlTemplate模板配置文件总根目录,可代码指定,也可在配置文件中配置,如使用配置文件中的配置则无需调用该方法,代码指定优先级高于配置
engine.SetSqlTemplateRootDir()

err := engine.InitSqlMap()//初始化加载SqlMap配置文件,默认初始化后缀为".xml"
err := engine.InitSqlTemplate()//初始化加载SqlTemplate配置文件,默认初始化后缀为".stpl"

//SqlMap配置文件和SqlTemplate配置文件后缀不要相同
option := xorm.SqlMapOptions{Extension: ".xx"} //指定SqlMap配置文件后缀为".xx",但配置内容必须为样例的xml格式
err := engine.InitSqlMap(option) //按指定SqlMap配置文件后缀为".xx"初始化

option := xorm.SqlTemplateOptions{Extension: ".yy"} //指定SqlTemplate配置文件后缀为".yy"
err = engine.InitSqlTemplate(option) //按指定SqlMap配置文件后缀为".xx"初始化

//开启SqlMap配置文件和SqlTemplate配置文件更新监控功能,将配置文件更新内容实时更新到内存,如无需要可以不调用该方法
//该监控模式下,如删除配置文件,内存中不会删除相关配置
engine.StartFSWatcher()
//停止SqlMap配置文件和SqlTemplate配置文件更新监控功能
engine.StopFSWatcher()

/*------------------------------------------------------------------------------------
1、以下方法是在没有engine.InitSqlMap()和engine.InitSqlTemplate()初始化相关配置文件的情况下让您在代码中可以轻松的手动管理SqlMap配置及SqlTemplate模板。
2、engine.InitSqlMap()和engine.InitSqlTemplate()初始化相关配置文件之后也可以使用以下方法灵活的对SqlMap配置及SqlTemplate模板进行管理
3、方便支持您系统中其他初始化配置源,可不依赖于本库的初始化配置方式
4、可在代码中依据业务场景,动态的添加、更新、删除SqlMap配置及SqlTemplate模板
5、手工管理的SqlMap配置及SqlTemplate模板,与xorm初始化方法一样会将相关配置缓存,但不会生成相关配置文件
-----------------------------------------------------------------------------------*/
engine.LoadSqlMap(filepath) //加载指定文件的SqlMap配置
engine.ReloadSqlMap(filepath) //重新加载指定文件的SqlMap配置

engine.BatchLoadSqlMap([]filepath) //批量加载SqlMap配置
engine.BatchReloadSqlMap([]filepath) //批量加载SqlMap配置

engine.GetSql(key, sql) //获取一条SqlMap配置
engine.AddSql(key, sql) //新增一条SqlMap配置
engine.UpdateSql(key, sql) //更新一条SqlMap配置
engine.RemoveSql(key) //删除一条SqlMap配置

engine.BatchAddSql(map[key]sql) //批量新增SqlMap配置
engine.BatchUpdateSql(map[key]sql) //批量更新SqlMap配置
engine.BatchRemoveSql([]key) //批量删除SqlMap配置

engine.LoadSqlTemplate(filepath) //加载指定文件的SqlTemplate模板
engine.ReloadSqlTemplate(filepath) //重新加载指定文件的SqlTemplate模板

engine.BatchLoadSqlTemplate([]filepath) //批量加载SqlTemplate模板
engine.BatchReloadSqlTemplate([]filepath) //批量加载SqlTemplate模板

engine.AddSqlTemplate(key, sql) //新增一条SqlTemplate模板,sql为SqlTemplate模板内容字符串
engine.UpdateSqlTemplate(key, sql) //更新一条SqlTemplate模板,sql为SqlTemplate模板内容字符串
engine.RemoveSqlTemplate(key) //删除一条SqlTemplate模板

engine.BatchAddSqlTemplate(map[key]sql) //批量新增SqlTemplate配置,sql为SqlTemplate模板内容字符串
engine.BatchUpdateSqlTemplate(map[key]sql) //批量更新SqlTemplate配置,sql为SqlTemplate模板内容字符串
engine.batchUpdateSqlTemplate([]key) //批量删除SqlTemplate配置

/*
1、指定多个key,批量查询SqlMap配置,...key的数据类型为...interface{},返回类型为map[string]string
2、支持如下多种调用方式
	a)engine.GetSqlMap("Test_GetSqlMap_1"),返回key为Test_GetSqlMap_1的SqlMap配置
    b)engine.GetSqlMap("Test_GetSqlMap_1", "Test_GetSqlMap_3"),返回key为Test_GetSqlMap_1,Test_GetSqlMap_3的SqlMap配置
    c)engine.GetSqlMap("Test_GetSqlMap_1", "Test_GetSqlMap_3","Test_GetSqlMap_null"),返回key为Test_GetSqlMap_1,Test_GetSqlMap_3的SqlMap,Test_GetSqlMap_null配置,其中Test_GetSqlMap_null在内存中缓存的的key不存在,则在返回的map[string]string中,key Test_GetSqlMap_null配置返回的值为空字符串
    d)engine.GetSqlMap([]string{"Test_GetSqlMap_1", "Test_GetSqlMap_3"})支持字符串数组形式参数
    e)engine.GetSqlMap([]string{"Test_GetSqlMap_1", "Test_GetSqlMap_3"},"Test_GetSqlMap_2")支持字符串数组形式和字符串参数混用
    f)engine.GetSqlMap([]string{"Test_GetSqlMap_1", "Test_GetSqlMap_3"},"Test_GetSqlMap_2",3)支持字符串数组形式,字符串参数和其他类型参数混用,但查询时只会处理字符串类型参数和字符转数组类型参数(因为SqlMap的key是字符串类型),返回的map[string]string也无其他类型的key
3、如不传任何参数,调用engine.GetSqlMap(),则返回整个内存中当前缓存的所有SqlMap配置
*/
engine.GetSqlMap(...key)

/*
1、指定多个key,批量查询SqlTemplate配置,...key的数据类型为...interface{},返回类型为map[string]*pongo2.Template
2、支持如下多种调用方式
	a)engine.GetSqlTemplates("Test_GetSqlTemplates_1"),返回key为Test_GetSqlTemplates_1的SSqlTemplate配置
    b)engine.GetSqlTemplates("Test_GetSqlTemplates_1", "Test_GetSqlTemplates_3"),返回key为Test_GetSqlTemplates_1,Test_GetSqlTemplates_3的SqlTemplate配置
    c)engine.GetSqlTemplates("Test_GetSqlTemplates_1", "Test_GetSqlTemplates_3","Test_GetSqlTemplates_null"),返回key为Test_GetSqlTemplates_1,Test_GetSqlTemplates_3的SqlMap,Test_GetSqlMap_null配置,其中Test_GetSqlTemplates_null在内存中缓存的的key不存在,则在返回的map[string]*pongo2.Template中,key Test_GetSqlTemplates_null配置返回的值为nil
    d)engine.GetSqlTemplates([]string{"Test_GetSqlTemplates_1", "Test_GetSqlTemplates_3"})支持字符串数组形式参数
    e)engine.GetSqlTemplates([]string{"Test_GetSqlTemplates_1", "Test_GetSqlTemplates_3"},"Test_GetSqlTemplates_2")支持字符串数组形式和字符串参数混用
    f)engine.GetSqlTemplates([]string{"Test_GetSqlTemplates_1", "Test_GetSqlTemplates_3"},"Test_GetSqlTemplates_2",3)支持字符串数组形式,字符串参数和其他类型参数混用,但查询时只会处理字符串类型参数和字符转数组类型参数(因为SqlTemplate的key是字符串类型),返回的map[string]*pongo2.Template也无其他类型的key
3、如不传任何参数,调用engine.GetSqlTemplates(),则返回整个内存中当前缓存的所有SqlTemplate配置
4、engine.GetSqlTemplates()返回类型为map[string]*pongo2.Template,可以方便的实现链式调用pongo2的Execute(),ExecuteBytes(),ExecuteWriter()方法
*/
engine.GetSqlTemplates(...key)
# 批量SQL操作 * 批量SQL操作API
//第一种方式,可以从Engine对象轻松进行使用,该方式自动管理事务,注意如果您使用的是mysql,数据库引擎为innodb事务才有效,myisam引擎是不支持事务的。
engine.Sqls(sqls, parmas...).Execute()
engine.SqlMapsClient(sqlkeys, parmas...).Execute()
engine.SqlTemplatesClient(sqlkeys, parmas...).Execute()

//第2种方式,手动创建Session对象进行调用,该方式需要您手动管理事务
session := engine.NewSession()
defer session.Close()
// add Begin() before any action
err := session.Begin()


_, err = session.Exec("delete from userinfo where username = ?", user2.Username)
if err != nil {
    session.Rollback()
    return
}

//Execuet返回值有3个,分别为slice,map,error类型
results, _, err = session.Sqls(sqls, parmas...).Execute()
if err != nil {
    session.Rollback()
    return
}

_, results, err = session.SqlMapsClient(sqlkeys, parmas...).Execute()
if err != nil {
    session.Rollback()
    return
}

results, _, err = session.SqlTemplatesClient(sqlkeys, parmas...).Execute()
if err != nil {
    session.Rollback()
    return
}

// add Commit() after all actions
err = session.Commit()
if err != nil {
    return
}

//支持两种返回结果集
//Slice形式类似如下
/*
[
    [
        {
            "id": "6",
            "name": "xorm"
        },
        {
            "id": "7",
            "name": "xormplus"
        },
        {
            "id": "8",
            "name": "ibatis"
        }
    ],
    [
        {
            "LastInsertId": 0,
            "RowsAffected": 0
        }
    ],
    [
        {
            "LastInsertId": 0,
            "RowsAffected": 0
        }
    ],
    [
        {
            "LastInsertId": 13,
            "RowsAffected": 1
        }
    ]
]
 */

//Map形式类似如下
/*
{
    "deleteUser": [
        {
            "LastInsertId": 0,
            "RowsAffected": 0
        }
    ],
    "insertUser": [
        {
            "LastInsertId": 11,
            "RowsAffected": 1
        }
    ],
    "updateUser": [
        {
            "LastInsertId": 0,
            "RowsAffected": 0
        }
    ],
    "userList": [
        {
            "id": "3",
            "name": "xorm"
        },
        {
            "id": "4",
            "name": "xormplus"
        },
    ]
}
 */

  • Sqls(sqls, parmas...)方法说明:

    1. sqls参数
    • sqls参数数据类型为interface{}类型,但实际参数类型检查时,只支持string,[]string和map[string]string三中类型,使用其他类型均会返回参数类型错误。
    • 使用string类型则为执行单条Sql执行单元(传送门:Sql执行单元定义),Execute()方法返回的结果集数据类型为[][]map[string]interface{},只有1个元素。
    • 使用[]string则Execute()方法为有序执行多条Sql执行单元,Execute()方法返回的结果集数据类型为[][]map[string]interface{}类型,结果集元素个数与sqls参数的元素个数相同,每个元素索引与返回结果集的索引一一对应。
    • 使用map[string]string类型则Execute()方法为无序执行多条Sql执行单元,Execute()方法返回的结果集数据类型为map[string][]map[string]interface{},结果集map的key与返回结果集的key一一对应。
    1. parmas...参数
    • 可以接收0个参数或则1个参数,当所有执行单元都无需执行参数时候,可以不传此参数
    • parmas参数数据类型为interface{},但实际参数类型检查时,只支持map[string]interface{},[]map[string]interface{}和map[string]map[string]interface{}三种类型,使用其他类型均会返回参数类型错误。
    • 使用map[string]interface{}类型时候,sqls参数类型必须为string类型,即map[string]interface{}类型为单条Sql执行单元的参数。
    • 使用[]map[string]interface{}类型时候,sqls参数类型可以为string类型,此时只有第一个元素[0]map[string]interface{}会被提取,之后的元素将不起任何作用。同时,sqls参数类型也可以为[]string类型,这种参数组合是最常用的组合形式之一,sqls参数的索引和parmas参数的索引一一对应。当某个索引所对应的Sql执行单元是无参数的时候,请将此索引的值设为nil,即parmas[i] = nil
    • 使用map[string]map[string]interface{}类型时,sqls参数类型必须为map[string]string类型,这种参数组合是最常用的组合形式之一,sqls参数的key和parmas参数的key一一对应。当某个key所对应的Sql执行单元是无参数的时候,请将此key的值设为nil,即parmas[key] = nil
  • SqlMapsClient(sqlkeys, parmas...)方法说明:

    1. sqlkeys参数
    • sqlkeys参数数据类型为interface{}类型,但实际参数类型检查时,只支持string,[]string和map[string]string三中类型,使用其他类型均会返回参数类型错误。
    • 使用string类型则为执行单条Sql执行单元(Sql执行单元定义),即在xorm种缓存的SqlMap中的key所对应的配置项,Execute()方法返回的结果集数据类型为[][]map[string]interface{},只有1个元素。
    • 使用[]string则Execute()方法为有序执行多条Sql执行单元,Execute()方法返回的结果集数据类型为[][]map[string]interface{}类型,结果集元素个数与sqls参数的元素个数相同,sqlkeys的索引与返回结果集的索引一一对应,sqlkeys存储的是每个元素的值是xorm缓存的SqlMap的key
    • 使用map[string]string类型则Execute()方法为无序执行多条Sql执行单元,Execute()方法返回的结果集数据类型为map[string][]map[string]interface{},sqlkeys的key与返回结果集的key一一对应,sqlkeys存储的是每个键值对的值是xorm缓存的SqlMap的key
    1. parmas...参数
    • 可以接收0个参数或则1个参数,当所有执行单元都无需执行参数时候,可以不传此参数
    • parmas参数数据类型为interface{},但实际参数类型检查时,只支持map[string]interface{},[]map[string]interface{}和map[string]map[string]interface{}三种类型,使用其他类型均会返回参数类型错误。
    • 使用map[string]interface{}类型时候,sqlkeys参数类型必须为string类型,即map[string]interface{}类型为单条Sql执行单元的参数。效果等同SqlMapClient()方法(请注意本方法名为SqlMapsClient)。
    • 使用[]map[string]interface{}类型时候,sqlkeys参数类型支持两种:
      • 第1种为string类型,此时只有第一个元素[0]map[string]interface{}会被提取,之后的元素将不起任何作用。
      • 第2种为[]string类型,这种参数组合是最常用的组合形式之一,sqlkeys参数的索引和parmas参数的索引一一对应。当某个索引所对应的Sql执行单元是无参数的时候,请将此索引的值设为nil,即parmas[i] = nil
    • 使用map[string]map[string]interface{}类型时,sqlkeys参数类型必须为map[string]string类型,这种参数组合是最常用的组合形式之一,sqlkeys参数的key和parmas参数的key一一对应。当某个key所对应的Sql执行单元是无参数的时候,请将此key的值设为nil,即parmas[key] = nil
  • SqlTemplatesClient(sqlkeys, parmas...)方法说明:

    1. sqlkeys参数
    • sqlkeys参数数据类型为interface{}类型,但实际参数类型检查时,只支持string,[]string和map[string]string三中类型,使用其他类型均会返回参数类型错误。
    • 使用string类型则为执行单条Sql执行单元(Sql执行单元定义),即在xorm缓存的SqlTemplate中的key所对应的模板,Execute()方法返回的结果集数据类型为[][]map[string]interface{},只有1个元素。
    • 使用[]string则Execute()方法为有序执行多条Sql执行单元,Execute()方法返回的结果集数据类型为[][]map[string]interface{}类型,结果集元素个数与sqls参数的元素个数相同,sqlkeys的索引与返回结果集的索引一一对应,sqlkeys存储的是每个元素的值是xorm缓存的SqlTemplate的key
    • 使用map[string]string类型则Execute()方法为无序执行多条Sql执行单元,Execute()方法返回的结果集数据类型为map[string][]map[string]interface{},sqlkeys的key与返回结果集的key一一对应,sqlkeys存储的是每个键值对的值是xorm缓存的SqlTemplate的key
    1. parmas...参数
    • 可以接收0个参数或则1个参数,当所有执行单元都无需执行参数时候,可以不传此参数
    • parmas参数数据类型为interface{},但实际参数类型检查时,只支持map[string]interface{},[]map[string]interface{}和map[string]map[string]interface{}三种类型,使用其他类型均会返回参数类型错误。
    • 使用map[string]interface{}类型时候,sqlkeys参数类型必须为string类型,即map[string]interface{}类型为单条Sql执行单元的参数。效果等同SqlMapClient()方法(请注意本方法名为SqlMapsClient)。
    • 使用[]map[string]interface{}类型时候,sqlkeys参数类型支持两种:
      • 第1种为string类型,此时只有第一个元素[0]map[string]interface{}会被提取,之后的元素将不起任何作用;
      • 第2种为[]string类型,这种参数组合是最常用的组合形式之一,sqlkeys参数的索引和parmas参数的索引一一对应。当某个索引所对应的Sql执行单元是无参数的时候,请将此索引的值设为nil,即parmas[i] = nil
    • 使用map[string]map[string]interface{}类型时,sqlkeys参数类型必须为map[string]string类型,这种参数组合是最常用的组合形式之一,sqlkeys参数的key和parmas参数的key一一对应。当某个key所对应的Sql执行单元是无参数的时候,请将此key的值设为nil,即parmas[key] = nil
  • Execute()方法说明:

    • 一共3个返回值,([][]map[string]interface{}, map[string][]map[string]interface{}, error)
    • 当以上3个方法的sqls或sqlkeys参数为string或[]string时为有序执行Sql执行单元,故返回结果集为第一个返回值,Slice存储,第二返回值为nil
    • 当以上3个方法的sqls或sqlkeys参数为map[string]string时为无序执行Sql执行单元,返回结果集为第二个返回值,map存储,第一个返回值为nil
    • 当以上3个方法执行中出现错误,则第三个返回值有值,前2个返回值均为nil

  • Sql执行单元定义
    • 当sqls为string时候,则Sql执行单元为该字符串的内容
    • 当sqlkeys为string时,则Sql执行单元为所对应的SqlMap配置项或SqlTemplate模板
    • 当sqls为[]string或map[string]string时候,则Sql执行单元为相关元素的字符串内容
    • 当sqlkeys为[]string或map[string]string时候,则Sql执行单元为以相关元素为key所对应的SqlMap配置项或SqlTemplate模板
    • Sql执行单元的具体内容,必须以"select", "insert", "delete", "update", "create", "drop"为起始内容,但后续内容不会继续做检查,请合理定义Sql执行单元内容。当执行单元内容不是以上起始内容,则对应索引或key返回的结果集为nil,请注意对返回结果集的nil判断
    • Sql执行单元并非单条Sql语句,当执行insert,delete,update,create,drop操作时候,可以为多条Sql语句,这里需要对应的数据库的SQL语法支持。如在一个执行单元批量执行多条Sql,返回结果集作为一组所有执行单元的大结果集中的一个元素,这个结果集的数据类型为map[string]interface{},只有2个键值对,一个键值对的key为LastInsertId,一个键值对的key为RowsAffected,请控制好执行粒度。另外,目前不是所有数据库都支持返回LastInsertId,目前还在设计更通用的API来实现所有数据库都能支持此功能。
    • 当执行select操作时候,执行单元的Sql语句必须为一条,返回结果集作为一组所有执行单元的大结果集中的一个元素
    • insert,delete,update,create,drop操作不能和select操作混合定义在同一个执行单元中
    • 最后,Sql执行单元基于以上约定,请合理组织

ORM方式操作数据库

  • 定义一个和表同步的结构体,并且自动同步结构体到数据库
type User struct {
    Id int64
    Name string
    Salt string
    Age int
    Passwd string `xorm:"varchar(200)"`
    Created time.Time `xorm:"created"`
    Updated time.Time `xorm:"updated"`
}

err := engine.Sync2(new(User))
  • ORM方式插入一条或者多条记录
affected, err := engine.Insert(&user)
// INSERT INTO struct () values ()
affected, err := engine.Insert(&user1, &user2)
// INSERT INTO struct1 () values ()
// INSERT INTO struct2 () values ()
affected, err := engine.Insert(&users)
// INSERT INTO struct () values (),(),()
affected, err := engine.Insert(&user1, &users)
// INSERT INTO struct1 () values ()
// INSERT INTO struct2 () values (),(),()
  • ORM方式查询单条记录
has, err := engine.Get(&user)
// SELECT * FROM user LIMIT 1
has, err := engine.Where("name = ?", name).Desc("id").Get(&user)
// SELECT * FROM user WHERE name = ? ORDER BY id DESC LIMIT 1
  • ORM方式查询多条记录,当然可以使用Join和extends来组合使用
var users []User
err := engine.Where("name = ?", name).And("age > 10").Limit(10, 0).Find(&users)
// SELECT * FROM user WHERE name = ? AND age > 10 limit 0 offset 10

type Detail struct {
    Id int64
    UserId int64 `xorm:"index"`
}

type UserDetail struct {
    User `xorm:"extends"`
    Detail `xorm:"extends"`
}

var users []UserDetail
err := engine.Table("user").Select("user.*, detail.*")
    Join("INNER", "detail", "detail.user_id = user.id").
    Where("user.name = ?", name).Limit(10, 0).
    Find(&users)
// SELECT user.*, detail.* FROM user INNER JOIN detail WHERE user.name = ? limit 0 offset 10
  • 根据条件遍历数据库,可以有两种方式: Iterate and Rows
err := engine.Iterate(&User{Name:name}, func(idx int, bean interface{}) error {
    user := bean.(*User)
    return nil
})
// SELECT * FROM user

rows, err := engine.Rows(&User{Name:name})
// SELECT * FROM user
defer rows.Close()
bean := new(Struct)
for rows.Next() {
    err = rows.Scan(bean)
}
  • ORM方式更新数据,除非使用Cols,AllCols函数指明,默认只更新非空和非0的字段
affected, err := engine.Id(1).Update(&user)
// UPDATE user SET ... Where id = ?

affected, err := engine.Update(&user, &User{Name:name})
// UPDATE user SET ... Where name = ?

var ids = []int64{1, 2, 3}
affected, err := engine.In(ids).Update(&user)
// UPDATE user SET ... Where id IN (?, ?, ?)

// force update indicated columns by Cols
affected, err := engine.Id(1).Cols("age").Update(&User{Name:name, Age: 12})
// UPDATE user SET age = ?, updated=? Where id = ?

// force NOT update indicated columns by Omit
affected, err := engine.Id(1).Omit("name").Update(&User{Name:name, Age: 12})
// UPDATE user SET age = ?, updated=? Where id = ?

affected, err := engine.Id(1).AllCols().Update(&user)
// UPDATE user SET name=?,age=?,salt=?,passwd=?,updated=? Where id = ?
  • ORM方式删除记录,需要注意,删除必须至少有一个条件,否则会报错。要清空数据库可以用EmptyTable
affected, err := engine.Where(...).Delete(&user)
// DELETE FROM user Where ...
  • ORM方式获取记录条数
counts, err := engine.Count(&user)
// SELECT count(*) AS total FROM user
  • Dump数据库结构和数据 DumpAll方法接收一个io.Writer接口来保存Dump出的数据库结构和数据的SQL语句,这个方法导出的SQL语句并不能通用。只针对当前engine所对应的数据库支持的SQL。
//如果需要在程序中Dump数据库的结构和数据可以使用下面2个方法
engine.DumpAll(w io.Writer)

engine.DumpAllFile(fpath string)
  • Import 执行数据库SQL脚本 同样,这里需要对应的数据库的SQL语法支持。
//如果你需要将保存在文件或者其它存储设施中的SQL脚本执行,那么可以使用下面2个方法
engine.Import(r io.Reader)

engine.ImportFile(fpath string)

部分测试用例

测试用例测试结果

文档

讨论

请加入QQ群:280360085 进行讨论。API设计相关建议可联系本人QQ:50892683

Documentation

Index

Constants

View Source
const (
	DEFAULT_LOG_PREFIX = "[xorm]"
	DEFAULT_LOG_FLAG   = log.Ldate | log.Lmicroseconds
	DEFAULT_LOG_LEVEL  = core.LOG_DEBUG
)
View Source
const (
	MSSQL_DRIVER      string = "mssql"
	MSSQL_ODBC_DRIVER string = "odbc"
	MYSQL_DRIVER      string = "mysql"
	MYMYSQL_DRIVER    string = "mymysql"
	POSTGRESQL_DRIVER string = "postgres"
	OCI8_DRIVER       string = "oci8"
	GORACLE_DRIVER    string = "goracle"
	SQLITE3_DRIVER    string = "sqlite3"
)
View Source
const (
	// Version show the xorm's version
	Version string = "0.5.4.0513"
)

Variables

View Source
var (
	ErrParamsType      error = errors.New("Params type error")
	ErrParamsFormat    error = errors.New("Params format error")
	ErrTableNotFound   error = errors.New("Not found table")
	ErrUnSupportedType error = errors.New("Unsupported type error")
	ErrNotExist        error = errors.New("Not exist error")
	ErrCacheFailed     error = errors.New("Cache failed")
	ErrNeedDeletedCond error = errors.New("Delete need at least one condition")
	ErrNotImplemented  error = errors.New("Not implemented.")
)
View Source
var (
	// NIL is defined in RFC 4122 section 4.1.7.
	// The nil UUID is special form of UUID that is specified to have all 128 bits set to zero.
	NIL = &UUID{
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	}
	// NameSpaceDNS assume name to be a fully-qualified domain name.
	// Declared in RFC 4122 Appendix C.
	NameSpaceDNS = &UUID{
		0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1,
		0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8,
	}
	// NameSpaceURL assume name to be a URL.
	// Declared in RFC 4122 Appendix C.
	NameSpaceURL = &UUID{
		0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1,
		0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8,
	}
	// NameSpaceOID assume name to be an ISO OID.
	// Declared in RFC 4122 Appendix C.
	NameSpaceOID = &UUID{
		0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1,
		0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8,
	}
	// NameSpaceX500 assume name to be a X.500 DN (in DER or a text output format).
	// Declared in RFC 4122 Appendix C.
	NameSpaceX500 = &UUID{
		0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1,
		0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8,
	}
)
View Source
var (
	NULL_TIME time.Time
)

Functions

func JSONString

func JSONString(v interface{}, IndentJSON bool) (string, error)

Types

type AfterDeleteProcessor

type AfterDeleteProcessor interface {
	AfterDelete()
}

Executed after an object has been deleted

type AfterInsertProcessor

type AfterInsertProcessor interface {
	AfterInsert()
}

Executed after an object is persisted to the database

type AfterSetProcessor

type AfterSetProcessor interface {
	AfterSet(string, Cell)
}

type AfterUpdateProcessor

type AfterUpdateProcessor interface {
	AfterUpdate()
}

Executed after an object has been updated

type BeforeDeleteProcessor

type BeforeDeleteProcessor interface {
	BeforeDelete()
}

Executed before an object is deleted

type BeforeInsertProcessor

type BeforeInsertProcessor interface {
	BeforeInsert()
}

Executed before an object is initially persisted to the database

type BeforeSetProcessor

type BeforeSetProcessor interface {
	BeforeSet(string, Cell)
}

type BeforeUpdateProcessor

type BeforeUpdateProcessor interface {
	BeforeUpdate()
}

Executed before an object is updated

type Cell

type Cell *interface{}

type DiscardLogger

type DiscardLogger struct{}

func (DiscardLogger) Debug

func (DiscardLogger) Debug(v ...interface{})

func (DiscardLogger) Debugf

func (DiscardLogger) Debugf(format string, v ...interface{})

func (DiscardLogger) Error

func (DiscardLogger) Error(v ...interface{})

func (DiscardLogger) Errorf

func (DiscardLogger) Errorf(format string, v ...interface{})

func (DiscardLogger) Info

func (DiscardLogger) Info(v ...interface{})

func (DiscardLogger) Infof

func (DiscardLogger) Infof(format string, v ...interface{})

func (DiscardLogger) IsShowSQL

func (DiscardLogger) IsShowSQL() bool

func (DiscardLogger) Level

func (DiscardLogger) Level() core.LogLevel

func (DiscardLogger) SetLevel

func (DiscardLogger) SetLevel(l core.LogLevel)

func (DiscardLogger) ShowSQL

func (DiscardLogger) ShowSQL(show ...bool)

func (DiscardLogger) Warn

func (DiscardLogger) Warn(v ...interface{})

func (DiscardLogger) Warnf

func (DiscardLogger) Warnf(format string, v ...interface{})

type Engine

type Engine struct {
	ColumnMapper  core.IMapper
	TableMapper   core.IMapper
	TagIdentifier string
	Tables        map[reflect.Type]*core.Table

	Cacher core.Cacher

	TZLocation *time.Location
	// contains filtered or unexported fields
}

Engine is the major struct of xorm, it means a database manager. Commonly, an application only need one engine

func NewDB

func NewDB(driverName string, dataSourceName string) (*Engine, error)

func NewEngine

func NewEngine(driverName string, dataSourceName string) (*Engine, error)

NewEngine new a db manager according to the parameter. Currently support four drivers

func NewMSSQL

func NewMSSQL(driverName string, dataSourceName string) (*Engine, error)

func NewMySQL

func NewMySQL(driverName string, dataSourceName string) (*Engine, error)

func NewOracle

func NewOracle(driverName string, dataSourceName string) (*Engine, error)

func NewPostgreSQL

func NewPostgreSQL(dataSourceName string) (*Engine, error)

func NewSqlite3

func NewSqlite3(dataSourceName string) (*Engine, error)

func (*Engine) AddSql

func (engine *Engine) AddSql(key string, sql string)

func (*Engine) AddSqlTemplate

func (engine *Engine) AddSqlTemplate(key string, sqlTemplateStr string) error

func (*Engine) After

func (engine *Engine) After(closures func(interface{})) *Session

Apply after insert Processor, affected bean is passed to closure arg

func (*Engine) Alias

func (engine *Engine) Alias(alias string) *Session

set the table alias

func (*Engine) AllCols

func (engine *Engine) AllCols() *Session

func (*Engine) Asc

func (engine *Engine) Asc(colNames ...string) *Session

Method Asc will generate "ORDER BY column1,column2 Asc" This method can chainable use.

engine.Desc("name").Asc("age").Find(&users)
// SELECT * FROM user ORDER BY name DESC, age ASC

func (*Engine) AutoIncrStr

func (engine *Engine) AutoIncrStr() string

AutoIncrStr Database's autoincrement statement

func (*Engine) BatchAddSql

func (engine *Engine) BatchAddSql(sqlStrMap map[string]string)

func (*Engine) BatchAddSqlTemplate

func (engine *Engine) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error

func (*Engine) BatchLoadSqlMap

func (engine *Engine) BatchLoadSqlMap(filepathSlice []string) error

func (*Engine) BatchLoadSqlTemplate

func (engine *Engine) BatchLoadSqlTemplate(filepathSlice []string) error

func (*Engine) BatchReloadSqlMap

func (engine *Engine) BatchReloadSqlMap(filepathSlice []string) error

func (*Engine) BatchReloadSqlTemplate

func (engine *Engine) BatchReloadSqlTemplate(filepathSlice []string) error

func (*Engine) BatchRemoveSql

func (engine *Engine) BatchRemoveSql(key []string)

func (*Engine) BatchRemoveSqlTemplate

func (engine *Engine) BatchRemoveSqlTemplate(key []string)

func (*Engine) BatchUpdateSql

func (engine *Engine) BatchUpdateSql(sqlStrMap map[string]string)

func (*Engine) BatchUpdateSqlTemplate

func (engine *Engine) BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error

func (*Engine) Before

func (engine *Engine) Before(closures func(interface{})) *Session

Apply before Processor, affected bean is passed to closure arg

func (*Engine) Cascade

func (engine *Engine) Cascade(trueOrFalse ...bool) *Session

use cascade or not

func (*Engine) Charset

func (engine *Engine) Charset(charset string) *Session

set charset when create table, only support mysql now

func (*Engine) ClearCache

func (engine *Engine) ClearCache(beans ...interface{}) error

If enabled cache, clear some tables' cache

func (*Engine) ClearCacheBean

func (engine *Engine) ClearCacheBean(bean interface{}, id string) error

If enabled cache, clear the cache bean

func (*Engine) Clone

func (engine *Engine) Clone() (*Engine, error)

Clone clone an engine

func (*Engine) Close

func (engine *Engine) Close() error

Close the engine

func (*Engine) Cols

func (engine *Engine) Cols(columns ...string) *Session

only use the paramters as select or update columns

func (*Engine) Count

func (engine *Engine) Count(bean interface{}) (int64, error)

Count counts the records. bean's non-empty fields are conditions.

func (*Engine) CreateIndexes

func (engine *Engine) CreateIndexes(bean interface{}) error

create indexes

func (*Engine) CreateTables

func (engine *Engine) CreateTables(beans ...interface{}) error

CreateTables create tabls according bean

func (*Engine) CreateUniques

func (engine *Engine) CreateUniques(bean interface{}) error

create uniques

func (*Engine) DB

func (engine *Engine) DB() *core.DB

DB return the wrapper of sql.DB

func (*Engine) DBMetas

func (engine *Engine) DBMetas() ([]*core.Table, error)

DBMetas Retrieve all tables, columns, indexes' informations from database.

func (*Engine) DataSourceName

func (engine *Engine) DataSourceName() string

DataSourceName return the current connection string

func (*Engine) Decr

func (engine *Engine) Decr(column string, arg ...interface{}) *Session

Method Decr provides a update string like "column = column - ?"

func (*Engine) Delete

func (engine *Engine) Delete(bean interface{}) (int64, error)

Delete records, bean's non-empty fields are conditions

func (*Engine) Desc

func (engine *Engine) Desc(colNames ...string) *Session

Method Desc will generate "ORDER BY column1 DESC, column2 DESC" This will

func (*Engine) Dialect

func (engine *Engine) Dialect() core.Dialect

Dialect return database dialect

func (*Engine) Distinct

func (engine *Engine) Distinct(columns ...string) *Session

use for distinct columns. Caution: when you are using cache, distinct will not be cached because cache system need id, but distinct will not provide id

func (*Engine) DriverName

func (engine *Engine) DriverName() string

DriverName return the current sql driver's name

func (*Engine) DropTables

func (engine *Engine) DropTables(beans ...interface{}) error

func (*Engine) DumpAll

func (engine *Engine) DumpAll(w io.Writer) error

DumpAll dump database all table structs and data to w

func (*Engine) DumpAllToFile

func (engine *Engine) DumpAllToFile(fp string) error

DumpAllToFile dump database all table structs and data to a file

func (*Engine) DumpTables

func (engine *Engine) DumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error

DumpTables dump specify tables to io.Writer

func (*Engine) DumpTablesToFile

func (engine *Engine) DumpTablesToFile(tables []*core.Table, fp string, tp ...core.DbType) error

DumpTablesToFile dump specified tables to SQL file.

func (*Engine) Exec

func (engine *Engine) Exec(sql string, args ...interface{}) (sql.Result, error)

Exec raw sql

func (*Engine) Find

func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error

Find retrieve records from table, condiBeans's non-empty fields are conditions. beans could be []Struct, []*Struct, map[int64]Struct map[int64]*Struct

func (*Engine) FormatTime

func (engine *Engine) FormatTime(sqlTypeName string, t time.Time) (v interface{})

func (*Engine) Get

func (engine *Engine) Get(bean interface{}) (bool, error)

Get retrieve one record from table, bean's non-empty fields are conditions

func (*Engine) GetFirst

func (engine *Engine) GetFirst(bean interface{}) ResultBean

Get retrieve one record from table, bean's non-empty fields are conditions

func (*Engine) GetSql

func (engine *Engine) GetSql(key string) string

func (*Engine) GetSqlMap

func (engine *Engine) GetSqlMap(keys ...interface{}) map[string]string

func (*Engine) GetSqlTemplate

func (engine *Engine) GetSqlTemplate(key string) *pongo2.Template

func (*Engine) GetSqlTemplates

func (engine *Engine) GetSqlTemplates(keys ...interface{}) map[string]*pongo2.Template

func (*Engine) GobRegister

func (engine *Engine) GobRegister(v interface{}) *Engine

func (*Engine) GroupBy

func (engine *Engine) GroupBy(keys string) *Session

Generate Group By statement

func (*Engine) Having

func (engine *Engine) Having(conditions string) *Session

Generate Having statement

func (*Engine) Id

func (engine *Engine) Id(id interface{}) *Session

Id mehtod provoide a condition as (id) = ?

func (*Engine) IdOf

func (engine *Engine) IdOf(bean interface{}) core.PK

func (*Engine) IdOfV

func (engine *Engine) IdOfV(rv reflect.Value) core.PK

func (*Engine) Import

func (engine *Engine) Import(r io.Reader) ([]sql.Result, error)

Import SQL DDL file

func (*Engine) ImportFile

func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error)

Import SQL DDL file

func (*Engine) In

func (engine *Engine) In(column string, args ...interface{}) *Session

This method will generate "column IN (?, ?)"

func (*Engine) Incr

func (engine *Engine) Incr(column string, arg ...interface{}) *Session

Method Inc provides a update string like "column = column + ?"

func (*Engine) InitSqlMap

func (engine *Engine) InitSqlMap(options ...SqlMapOptions) error

func (*Engine) InitSqlTemplate

func (engine *Engine) InitSqlTemplate(options ...SqlTemplateOptions) error

func (*Engine) Insert

func (engine *Engine) Insert(beans ...interface{}) (int64, error)

Insert one or more records

func (*Engine) InsertOne

func (engine *Engine) InsertOne(bean interface{}) (int64, error)

Insert only one record

func (*Engine) IsTableEmpty

func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error)

If a table has any reocrd

func (*Engine) IsTableExist

func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error)

If a table is exist

func (*Engine) Iterate

func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error

Iterate record by record handle records from table, bean's non-empty fields are conditions.

func (*Engine) Join

func (engine *Engine) Join(join_operator string, tablename interface{}, condition string, args ...interface{}) *Session

The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN

func (*Engine) Limit

func (engine *Engine) Limit(limit int, start ...int) *Session

This method will generate "LIMIT start, limit"

func (*Engine) LoadSqlMap

func (engine *Engine) LoadSqlMap(filepath string) error

func (*Engine) LoadSqlTemplate

func (engine *Engine) LoadSqlTemplate(filepath string) error

func (*Engine) Logger

func (engine *Engine) Logger() core.ILogger

Logger return the logger interface

func (*Engine) MapCacher

func (engine *Engine) MapCacher(bean interface{}, cacher core.Cacher)

MapCacher Set a table use a special cacher

func (*Engine) MustCols

func (engine *Engine) MustCols(columns ...string) *Session

func (*Engine) NewDB

func (engine *Engine) NewDB() (*core.DB, error)

NewDB provides an interface to operate database directly

func (*Engine) NewSession

func (engine *Engine) NewSession() *Session

NewSession New a session

func (*Engine) NoAutoCondition

func (engine *Engine) NoAutoCondition(no ...bool) *Session

NoAutoCondition disable auto generate Where condition from bean or not

func (*Engine) NoAutoTime

func (engine *Engine) NoAutoTime() *Session

NoAutoTime Default if your struct has "created" or "updated" filed tag, the fields will automatically be filled with current time when Insert or Update invoked. Call NoAutoTime if you dont' want to fill automatically.

func (*Engine) NoCache

func (engine *Engine) NoCache() *Session

NoCache If you has set default cacher, and you want temporilly stop use cache, you can use NoCache()

func (*Engine) NoCascade

func (engine *Engine) NoCascade() *Session

NoCascade If you do not want to auto cascade load object

func (*Engine) NowTime

func (engine *Engine) NowTime(sqlTypeName string) interface{}

func (*Engine) NowTime2

func (engine *Engine) NowTime2(sqlTypeName string) (interface{}, time.Time)

func (*Engine) Nullable

func (engine *Engine) Nullable(columns ...string) *Session

Set null when column is zero-value and nullable for update

func (*Engine) Omit

func (engine *Engine) Omit(columns ...string) *Session

Only not use the paramters as select or update columns

func (*Engine) OrderBy

func (engine *Engine) OrderBy(order string) *Session

Method OrderBy will generate "ORDER BY order"

func (*Engine) Ping

func (engine *Engine) Ping() error

Ping tests if database is alive

func (*Engine) Query

func (engine *Engine) Query(sql string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error)

Exec a raw sql and return records as []map[string][]byte

func (*Engine) Query2

func (engine *Engine) Query2(sql string, paramStr ...interface{}) (resultsSlice []map[string]string, err error)

Exec a raw sql and return records as []map[string][]byte

func (*Engine) Quote

func (engine *Engine) Quote(sql string) string

Quote Use QuoteStr quote the string sql

func (*Engine) QuoteStr

func (engine *Engine) QuoteStr() string

QuoteStr Engine's database use which charactor as quote. mysql, sqlite use ` and postgres use "

func (*Engine) ReloadSqlMap

func (engine *Engine) ReloadSqlMap(filepath string) error

func (*Engine) ReloadSqlTemplate

func (engine *Engine) ReloadSqlTemplate(filepath string) error

func (*Engine) RemoveSql

func (engine *Engine) RemoveSql(key string)

func (*Engine) RemoveSqlTemplate

func (engine *Engine) RemoveSqlTemplate(key string)

func (*Engine) Rows

func (engine *Engine) Rows(bean interface{}) (*Rows, error)

Return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields are conditions.

func (*Engine) Search

func (engine *Engine) Search(beans interface{}, condiBeans ...interface{}) ResultStructs

func (*Engine) Select

func (engine *Engine) Select(str string) *Session

func (*Engine) SetColumnMapper

func (engine *Engine) SetColumnMapper(mapper core.IMapper)

SetColumnMapper set the column name mapping rule

func (*Engine) SetDefaultCacher

func (engine *Engine) SetDefaultCacher(cacher core.Cacher)

SetDefaultCacher set the default cacher. Xorm's default not enable cacher.

func (*Engine) SetDisableGlobalCache

func (engine *Engine) SetDisableGlobalCache(disable bool)

SetDisableGlobalCache disable global cache or not

func (*Engine) SetExpr

func (engine *Engine) SetExpr(column string, expression string) *Session

Method SetExpr provides a update string like "column = {expression}"

func (*Engine) SetLogger

func (engine *Engine) SetLogger(logger core.ILogger)

SetLogger set the new logger

func (*Engine) SetMapper

func (engine *Engine) SetMapper(mapper core.IMapper)

SetMapper set the name mapping rules

func (*Engine) SetMaxIdleConns

func (engine *Engine) SetMaxIdleConns(conns int)

SetMaxIdleConns set the max idle connections on pool, default is 2

func (*Engine) SetMaxOpenConns

func (engine *Engine) SetMaxOpenConns(conns int)

SetMaxOpenConns is only available for go 1.2+

func (*Engine) SetSqlMapRootDir

func (engine *Engine) SetSqlMapRootDir(sqlMapRootDir string) *Engine

func (*Engine) SetSqlTemplateRootDir

func (engine *Engine) SetSqlTemplateRootDir(sqlTemplateRootDir string) *Engine

func (*Engine) SetTableMapper

func (engine *Engine) SetTableMapper(mapper core.IMapper)

SetTableMapper set the table name mapping rule

func (*Engine) ShowExecTime

func (engine *Engine) ShowExecTime(show ...bool)

ShowExecTime show SQL statment and execute time or not on logger if log level is great than INFO

func (*Engine) ShowSQL

func (engine *Engine) ShowSQL(show ...bool)

ShowSQL show SQL statment or not on logger if log level is great than INFO

func (*Engine) Sql

func (engine *Engine) Sql(querystring string, args ...interface{}) *Session

Sql method let's you manualy write raw sql and operate For example:

engine.Sql("select * from user").Find(&users)

This code will execute "select * from user" and set the records to users

func (*Engine) SqlMapClient

func (engine *Engine) SqlMapClient(sqlTagName string, args ...interface{}) *Session

func (*Engine) SqlMapsClient

func (engine *Engine) SqlMapsClient(sqlkeys interface{}, parmas ...interface{}) *SqlMapsExecutor

func (*Engine) SqlTemplateClient

func (engine *Engine) SqlTemplateClient(sqlTagName string, args ...interface{}) *Session

func (*Engine) SqlTemplatesClient

func (engine *Engine) SqlTemplatesClient(sqlkeys interface{}, parmas ...interface{}) *SqlTemplatesExecutor

func (*Engine) SqlType

func (engine *Engine) SqlType(c *core.Column) string

SqlType A simple wrapper to dialect's core.SqlType method

func (*Engine) Sqls

func (engine *Engine) Sqls(sqls interface{}, parmas ...interface{}) *SqlsExecutor

func (*Engine) StartFSWatcher

func (engine *Engine) StartFSWatcher() error

start filesytem watcher

func (*Engine) StopFSWatcher

func (engine *Engine) StopFSWatcher() error

stop filesytem watcher

func (*Engine) StoreEngine

func (engine *Engine) StoreEngine(storeEngine string) *Session

set store engine when create table, only support mysql now

func (*Engine) SupportInsertMany

func (engine *Engine) SupportInsertMany() bool

SupportInsertMany If engine's database support batch insert records like "insert into user values (name, age), (name, age)". When the return is ture, then engine.Insert(&users) will generate batch sql and exeute.

func (*Engine) Sync

func (engine *Engine) Sync(beans ...interface{}) error

Sync the new struct changes to database, this method will automatically add table, column, index, unique. but will not delete or change anything. If you change some field, you should change the database manually.

func (*Engine) Sync2

func (engine *Engine) Sync2(beans ...interface{}) error

func (*Engine) TZTime

func (engine *Engine) TZTime(t time.Time) time.Time

func (*Engine) Table

func (engine *Engine) Table(tableNameOrBean interface{}) *Session

Temporarily change the Get, Find, Update's table

func (*Engine) TableInfo

func (engine *Engine) TableInfo(bean interface{}) *core.Table

func (*Engine) Unscoped

func (engine *Engine) Unscoped() *Session

Always disable struct tag "deleted"

func (*Engine) Update

func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error)

Update records, bean's non-empty fields are updated contents, condiBean' non-empty filds are conditions CAUTION:

1.bool will defaultly be updated content nor conditions
 You should call UseBool if you have bool to use.
2.float32 & float64 may be not inexact as conditions

func (*Engine) UpdateSql

func (engine *Engine) UpdateSql(key string, sql string)

func (*Engine) UpdateSqlTemplate

func (engine *Engine) UpdateSqlTemplate(key string, sqlTemplateStr string) error

func (*Engine) UseBool

func (engine *Engine) UseBool(columns ...string) *Session

Xorm automatically retrieve condition according struct, but if struct has bool field, it will ignore them. So use UseBool to tell system to do not ignore them. If no paramters, it will use all the bool field of struct, or it will use paramters's columns

func (*Engine) Where

func (engine *Engine) Where(querystring string, args ...interface{}) *Session

Where method provide a condition query

type IterFunc

type IterFunc func(idx int, bean interface{}) error

IterFunc only use by Iterate

type LRUCacher

type LRUCacher struct {

	// maxSize    int
	MaxElementSize int
	Expired        time.Duration
	GcInterval     time.Duration
	// contains filtered or unexported fields
}

func NewLRUCacher

func NewLRUCacher(store core.CacheStore, maxElementSize int) *LRUCacher

func NewLRUCacher2

func NewLRUCacher2(store core.CacheStore, expired time.Duration, maxElementSize int) *LRUCacher

func (*LRUCacher) ClearBeans

func (m *LRUCacher) ClearBeans(tableName string)

func (*LRUCacher) ClearIds

func (m *LRUCacher) ClearIds(tableName string)

func (*LRUCacher) DelBean

func (m *LRUCacher) DelBean(tableName string, id string)

func (*LRUCacher) DelIds

func (m *LRUCacher) DelIds(tableName, sql string)

func (*LRUCacher) GC

func (m *LRUCacher) GC()

GC check ids lit and sql list to remove all element expired

func (*LRUCacher) GetBean

func (m *LRUCacher) GetBean(tableName string, id string) interface{}

Get bean according tableName and id from cache

func (*LRUCacher) GetIds

func (m *LRUCacher) GetIds(tableName, sql string) interface{}

Get all bean's ids according to sql and parameter from cache

func (*LRUCacher) PutBean

func (m *LRUCacher) PutBean(tableName string, id string, obj interface{})

func (*LRUCacher) PutIds

func (m *LRUCacher) PutIds(tableName, sql string, ids interface{})

func (*LRUCacher) RunGC

func (m *LRUCacher) RunGC()

RunGC run once every m.GcInterval

type MemoryStore

type MemoryStore struct {
	// contains filtered or unexported fields
}

memory store

func NewMemoryStore

func NewMemoryStore() *MemoryStore

func (*MemoryStore) Del

func (s *MemoryStore) Del(key string) error

func (*MemoryStore) Get

func (s *MemoryStore) Get(key string) (interface{}, error)

func (*MemoryStore) Put

func (s *MemoryStore) Put(key string, value interface{}) error

type Result

type Result struct {
	Sql []Sql `xml:"sql"`
}

type ResultBean

type ResultBean struct {
	Has    bool
	Result interface{}
	Error  error
}

func (ResultBean) GetResult

func (resultBean ResultBean) GetResult() (bool, interface{}, error)

func (ResultBean) Json

func (resultBean ResultBean) Json() (bool, string, error)

func (ResultBean) Xml

func (resultBean ResultBean) Xml() (bool, string, error)

func (ResultBean) XmlIndent

func (resultBean ResultBean) XmlIndent(prefix string, indent string, recordTag string) (bool, string, error)

type ResultMap

type ResultMap struct {
	Results []map[string]interface{}
	Error   error
}

func (ResultMap) Count

func (resultMap ResultMap) Count() (int, error)

func (ResultMap) Json

func (resultMap ResultMap) Json() (string, error)

func (ResultMap) List

func (resultMap ResultMap) List() ([]map[string]interface{}, error)

func (ResultMap) ListPage

func (resultMap ResultMap) ListPage(firstResult int, maxResults int) ([]map[string]interface{}, error)

func (ResultMap) Xml

func (resultMap ResultMap) Xml() (string, error)

func (ResultMap) XmlIndent

func (resultMap ResultMap) XmlIndent(prefix string, indent string, recordTag string) (string, error)

type ResultStructs

type ResultStructs struct {
	Result interface{}
	Error  error
}

func (ResultStructs) Json

func (resultStructs ResultStructs) Json() (string, error)

func (ResultStructs) Xml

func (resultStructs ResultStructs) Xml() (string, error)

func (ResultStructs) XmlIndent

func (resultStructs ResultStructs) XmlIndent(prefix string, indent string, recordTag string) (string, error)

type Rows

type Rows struct {
	NoTypeCheck bool
	// contains filtered or unexported fields
}

func (*Rows) Close

func (rows *Rows) Close() error

close session if session.IsAutoClose is true, and claimed any opened resources

func (*Rows) Err

func (rows *Rows) Err() error

Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.

func (*Rows) Next

func (rows *Rows) Next() bool

move cursor to next record, return false if end has reached

func (*Rows) Scan

func (rows *Rows) Scan(bean interface{}) error

scan row record to bean properties

type Session

type Session struct {
	Engine                 *Engine
	Tx                     *core.Tx
	Statement              Statement
	IsAutoCommit           bool
	IsCommitedOrRollbacked bool
	IsSqlFuc               bool
	TransType              string
	IsAutoClose            bool

	// Automatically reset the statement after operations that execute a SQL
	// query such as Count(), Find(), Get(), ...
	AutoResetStatement bool
	// contains filtered or unexported fields
}

Struct Session keep a pointer to sql.DB and provides all execution of all kind of database operations.

func (*Session) After

func (session *Session) After(closures func(interface{})) *Session

After Apply after Processor, affected bean is passed to closure arg

func (*Session) Alias

func (session *Session) Alias(alias string) *Session

Alias set the table alias

func (*Session) AllCols

func (session *Session) AllCols() *Session

AllCols ask all columns

func (*Session) And

func (session *Session) And(querystring string, args ...interface{}) *Session

And provides custom query condition.

func (*Session) Asc

func (session *Session) Asc(colNames ...string) *Session

Method Asc provide asc order by query condition, the input parameters are columns.

func (*Session) Before

func (session *Session) Before(closures func(interface{})) *Session

Before Apply before Processor, affected bean is passed to closure arg

func (*Session) Begin

func (session *Session) Begin() error

Begin a transaction

func (*Session) Cascade

func (session *Session) Cascade(trueOrFalse ...bool) *Session

Method Cascade indicates if loading sub Struct

func (*Session) Charset

func (session *Session) Charset(charset string) *Session

Method Charset is only avialble mysql dialect currently

func (*Session) Clone

func (session *Session) Clone() *Session

Clone copy all the session's content and return a new session

func (*Session) Close

func (session *Session) Close()

Close release the connection from pool

func (*Session) Cols

func (session *Session) Cols(columns ...string) *Session

Cols provides some columns to special

func (*Session) Commit

func (session *Session) Commit() error

Commit When using transaction, Commit will commit all operations.

func (*Session) Count

func (session *Session) Count(bean interface{}) (int64, error)

Count counts the records. bean's non-empty fields are conditions.

func (*Session) CreateIndexes

func (session *Session) CreateIndexes(bean interface{}) error

CreateIndexes create indexes

func (*Session) CreateTable

func (session *Session) CreateTable(bean interface{}) error

CreateTable create a table according a bean

func (*Session) CreateUniques

func (session *Session) CreateUniques(bean interface{}) error

CreateUniques create uniques

func (*Session) DB

func (session *Session) DB() *core.DB

DB db return the wrapper of sql.DB

func (*Session) Decr

func (session *Session) Decr(column string, arg ...interface{}) *Session

Decr provides a query string like "count = count - 1"

func (*Session) Delete

func (session *Session) Delete(bean interface{}) (int64, error)

Delete records, bean's non-empty fields are conditions

func (*Session) Desc

func (session *Session) Desc(colNames ...string) *Session

Method Desc provide desc order by query condition, the input parameters are columns.

func (*Session) Distinct

func (session *Session) Distinct(columns ...string) *Session

Distinct use for distinct columns. Caution: when you are using cache, distinct will not be cached because cache system need id, but distinct will not provide id

func (*Session) DropIndexes

func (session *Session) DropIndexes(bean interface{}) error

drop indexes

func (*Session) DropTable

func (session *Session) DropTable(beanOrTableName interface{}) error

drop table will drop table if exist, if drop failed, it will return error

func (*Session) Exec

func (session *Session) Exec(sqlStr string, args ...interface{}) (sql.Result, error)

Exec raw sql

func (*Session) Execute

func (session *Session) Execute() (sql.Result, error)

Execute raw sql

func (*Session) Find

func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error

Find retrieve records from table, condiBeans's non-empty fields are conditions. beans could be []Struct, []*Struct, map[int64]Struct map[int64]*Struct

func (*Session) ForUpdate

func (session *Session) ForUpdate() *Session

ForUpdate Set Read/Write locking for UPDATE

func (*Session) Get

func (session *Session) Get(bean interface{}) (bool, error)

Get retrieve one record from database, bean's non-empty fields will be as conditions

func (*Session) GetFirst

func (session *Session) GetFirst(bean interface{}) ResultBean

func (*Session) GroupBy

func (session *Session) GroupBy(keys string) *Session

GroupBy Generate Group By statement

func (*Session) Having

func (session *Session) Having(conditions string) *Session

Having Generate Having statement

func (*Session) Id

func (session *Session) Id(id interface{}) *Session

Id provides converting id as a query condition

func (*Session) In

func (session *Session) In(column string, args ...interface{}) *Session

In provides a query string like "id in (1, 2, 3)"

func (*Session) Incr

func (session *Session) Incr(column string, arg ...interface{}) *Session

Incr provides a query string like "count = count + 1"

func (*Session) Init

func (session *Session) Init()

Init reset the session as the init status.

func (*Session) Insert

func (session *Session) Insert(beans ...interface{}) (int64, error)

Insert insert one or more beans

func (*Session) InsertMulti

func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error)

InsertMulti insert multiple records

func (*Session) InsertOne

func (session *Session) InsertOne(bean interface{}) (int64, error)

InsertOne insert only one struct into database as a record. The in parameter bean must a struct or a point to struct. The return parameter is inserted and error

func (*Session) IsTableEmpty

func (session *Session) IsTableEmpty(bean interface{}) (bool, error)

IsTableEmpty if table have any records

func (*Session) IsTableExist

func (session *Session) IsTableExist(beanOrTableName interface{}) (bool, error)

IsTableExist if a table is exist

func (*Session) Iterate

func (session *Session) Iterate(bean interface{}, fun IterFunc) error

Iterate record by record handle records from table, condiBeans's non-empty fields are conditions. beans could be []Struct, []*Struct, map[int64]Struct map[int64]*Struct

func (*Session) Join

func (session *Session) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session

Join join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN

func (*Session) LastSQL

func (session *Session) LastSQL() (string, []interface{})

LastSQL returns last query information

func (*Session) Limit

func (session *Session) Limit(limit int, start ...int) *Session

Method Limit provide limit and offset query condition

func (*Session) MustCols

func (session *Session) MustCols(columns ...string) *Session

MustCols

func (*Session) NoAutoCondition

func (session *Session) NoAutoCondition(no ...bool) *Session

NoAutoCondition disable generate SQL condition from beans

func (*Session) NoAutoTime

func (session *Session) NoAutoTime() *Session

NoAutoTime means do not automatically give created field and updated field the current time on the current session temporarily

func (*Session) NoCache

func (session *Session) NoCache() *Session

NoCache ask this session do not retrieve data from cache system and get data from database directly.

func (*Session) NoCascade

func (session *Session) NoCascade() *Session

NoCascade

func (*Session) Nullable

func (session *Session) Nullable(columns ...string) *Session

Nullable Set null when column is zero-value and nullable for update

func (*Session) Omit

func (session *Session) Omit(columns ...string) *Session

Omit Only not use the paramters as select or update columns

func (*Session) Or

func (session *Session) Or(querystring string, args ...interface{}) *Session

Or provides custom query condition.

func (*Session) OrderBy

func (session *Session) OrderBy(order string) *Session

Method OrderBy provide order by query condition, the input parameter is the content after order by on a sql statement.

func (*Session) Ping

func (session *Session) Ping() error

Ping test if database is ok

func (*Session) Prepare

func (session *Session) Prepare() *Session

Prepare

func (*Session) Query

func (session *Session) Query() ResultMap

Exec a raw sql and return records as ResultMap

func (*Session) QueryWithDateFormat

func (session *Session) QueryWithDateFormat(dateFormat string) ResultMap

Exec a raw sql and return records as ResultMap

func (*Session) Rollback

func (session *Session) Rollback() error

Rollback When using transaction, you can rollback if any error

func (*Session) Rows

func (session *Session) Rows(bean interface{}) (*Rows, error)

Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields are conditions.

func (*Session) Search

func (session *Session) Search(rowsSlicePtr interface{}, condiBean ...interface{}) ResultStructs

func (*Session) Select

func (session *Session) Select(str string) *Session

Select provides some columns to special

func (*Session) SetExpr

func (session *Session) SetExpr(column string, expression string) *Session

SetExpr provides a query string like "column = {expression}"

func (*Session) Sql

func (session *Session) Sql(querystring string, args ...interface{}) *Session

Sql provides raw sql input parameter. When you have a complex SQL statement and cannot use Where, Id, In and etc. Methods to describe, you can use Sql.

func (*Session) SqlMapClient

func (session *Session) SqlMapClient(sqlTagName string, args ...interface{}) *Session

func (*Session) SqlMapsClient

func (session *Session) SqlMapsClient(sqlkeys interface{}, parmas ...interface{}) *SqlMapsExecutor

func (*Session) SqlTemplateClient

func (session *Session) SqlTemplateClient(sqlTagName string, args ...interface{}) *Session

func (*Session) SqlTemplatesClient

func (session *Session) SqlTemplatesClient(sqlkeys interface{}, parmas ...interface{}) *SqlTemplatesExecutor

func (*Session) Sqls

func (session *Session) Sqls(sqls interface{}, parmas ...interface{}) *SqlsExecutor

func (*Session) StoreEngine

func (session *Session) StoreEngine(storeEngine string) *Session

Method StoreEngine is only avialble mysql dialect currently

func (*Session) Sync2

func (s *Session) Sync2(beans ...interface{}) error

Sync2 synchronize structs to database tables

func (*Session) Table

func (session *Session) Table(tableNameOrBean interface{}) *Session

Table can input a string or pointer to struct for special a table to operate.

func (*Session) Unscoped

func (session *Session) Unscoped() *Session

Unscoped always disable struct tag "deleted"

func (*Session) Update

func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error)

Update records, bean's non-empty fields are updated contents, condiBean' non-empty filds are conditions CAUTION:

1.bool will defaultly be updated content nor conditions
 You should call UseBool if you have bool to use.
2.float32 & float64 may be not inexact as conditions

func (*Session) UseBool

func (session *Session) UseBool(columns ...string) *Session

UseBool automatically retrieve condition according struct, but if struct has bool field, it will ignore them. So use UseBool to tell system to do not ignore them. If no paramters, it will use all the bool field of struct, or it will use paramters's columns

func (*Session) Where

func (session *Session) Where(querystring string, args ...interface{}) *Session

Where provides custom query condition.

type SimpleLogger

type SimpleLogger struct {
	DEBUG *log.Logger
	ERR   *log.Logger
	INFO  *log.Logger
	WARN  *log.Logger
	// contains filtered or unexported fields
}

SimpleLogger is the default implment of core.ILogger

func NewSimpleLogger

func NewSimpleLogger(out io.Writer) *SimpleLogger

NewSimpleLogger use a special io.Writer as logger output

func NewSimpleLogger2

func NewSimpleLogger2(out io.Writer, prefix string, flag int) *SimpleLogger

NewSimpleLogger2 let you customrize your logger prefix and flag

func NewSimpleLogger3

func NewSimpleLogger3(out io.Writer, prefix string, flag int, l core.LogLevel) *SimpleLogger

NewSimpleLogger3 let you customrize your logger prefix and flag and logLevel

func (*SimpleLogger) Debug

func (s *SimpleLogger) Debug(v ...interface{})

Debug implement core.ILogger

func (*SimpleLogger) Debugf

func (s *SimpleLogger) Debugf(format string, v ...interface{})

Debugf implement core.ILogger

func (*SimpleLogger) Error

func (s *SimpleLogger) Error(v ...interface{})

Error implement core.ILogger

func (*SimpleLogger) Errorf

func (s *SimpleLogger) Errorf(format string, v ...interface{})

Errorf implement core.ILogger

func (*SimpleLogger) Info

func (s *SimpleLogger) Info(v ...interface{})

Info implement core.ILogger

func (*SimpleLogger) Infof

func (s *SimpleLogger) Infof(format string, v ...interface{})

Infof implement core.ILogger

func (*SimpleLogger) IsShowSQL

func (s *SimpleLogger) IsShowSQL() bool

IsShowSQL implement core.ILogger

func (*SimpleLogger) Level

func (s *SimpleLogger) Level() core.LogLevel

Level implement core.ILogger

func (*SimpleLogger) SetLevel

func (s *SimpleLogger) SetLevel(l core.LogLevel)

SetLevel implement core.ILogger

func (*SimpleLogger) ShowSQL

func (s *SimpleLogger) ShowSQL(show ...bool)

ShowSQL implement core.ILogger

func (*SimpleLogger) Warn

func (s *SimpleLogger) Warn(v ...interface{})

Warn implement core.ILogger

func (*SimpleLogger) Warnf

func (s *SimpleLogger) Warnf(format string, v ...interface{})

Warnf implement core.ILogger

type Sql

type Sql struct {
	Value string `xml:",chardata"`
	Id    string `xml:"id,attr"`
}

type SqlMap

type SqlMap struct {
	SqlMapRootDir string
	Sql           map[string]string
	Extension     string
}

type SqlMapOptions

type SqlMapOptions struct {
	Extension string
}

type SqlMapsExecutor

type SqlMapsExecutor struct {
	// contains filtered or unexported fields
}

func (*SqlMapsExecutor) Execute

func (sqlMapsExecutor *SqlMapsExecutor) Execute() ([][]map[string]interface{}, map[string][]map[string]interface{}, error)

type SqlTemplate

type SqlTemplate struct {
	SqlTemplateRootDir string
	Template           map[string]*pongo2.Template
	Extension          string
}

type SqlTemplateOptions

type SqlTemplateOptions struct {
	Extension string
}

type SqlTemplatesExecutor

type SqlTemplatesExecutor struct {
	// contains filtered or unexported fields
}

func (*SqlTemplatesExecutor) Execute

func (sqlTemplatesExecutor *SqlTemplatesExecutor) Execute() ([][]map[string]interface{}, map[string][]map[string]interface{}, error)

type SqlsExecutor

type SqlsExecutor struct {
	// contains filtered or unexported fields
}

func (*SqlsExecutor) Execute

func (sqlsExecutor *SqlsExecutor) Execute() ([][]map[string]interface{}, map[string][]map[string]interface{}, error)

type Statement

type Statement struct {
	RefTable *core.Table
	OutTable *core.Table
	Engine   *Engine
	Start    int
	LimitN   int
	WhereStr string
	IdParam  *core.PK
	Params   []interface{}
	OrderStr string
	JoinStr  string

	GroupByStr string
	HavingStr  string
	ColumnStr  string

	OmitStr      string
	ConditionStr string
	AltTableName string
	RawSQL       string
	RawParams    []interface{}
	UseCascade   bool
	UseAutoJoin  bool
	StoreEngine  string
	Charset      string
	BeanArgs     []interface{}
	UseCache     bool
	UseAutoTime  bool

	IsDistinct  bool
	IsForUpdate bool
	TableAlias  string
	// contains filtered or unexported fields
}

Statement save all the sql info for executing SQL

func (*Statement) Alias

func (statement *Statement) Alias(alias string) *Statement

Alias set the table alias

func (*Statement) AllCols

func (statement *Statement) AllCols() *Statement

AllCols update use only: update all columns

func (*Statement) And

func (statement *Statement) And(querystring string, args ...interface{}) *Statement

And add Where & and statment

func (*Statement) Asc

func (statement *Statement) Asc(colNames ...string) *Statement

Asc provide asc order by query condition, the input parameters are columns.

func (*Statement) Cols

func (statement *Statement) Cols(columns ...string) *Statement

Cols generate "col1, col2" statement

func (*Statement) Decr

func (statement *Statement) Decr(column string, arg ...interface{}) *Statement

Decr Generate "Update ... Set column = column - arg" statment

func (*Statement) Desc

func (statement *Statement) Desc(colNames ...string) *Statement

Desc generate `ORDER BY xx DESC`

func (*Statement) Distinct

func (statement *Statement) Distinct(columns ...string) *Statement

Generate "Distince col1, col2 " statment

func (*Statement) ForUpdate

func (statement *Statement) ForUpdate() *Statement

Generate "SELECT ... FOR UPDATE" statment

func (*Statement) GroupBy

func (statement *Statement) GroupBy(keys string) *Statement

GroupBy generate "Group By keys" statement

func (*Statement) Having

func (statement *Statement) Having(conditions string) *Statement

Having generate "Having conditions" statement

func (*Statement) Id

func (statement *Statement) Id(id interface{}) *Statement

Id generate "where id = ? " statment or for composite key "where key1 = ? and key2 = ?"

func (*Statement) In

func (statement *Statement) In(column string, args ...interface{}) *Statement

In generate "Where column IN (?) " statment

func (*Statement) Incr

func (statement *Statement) Incr(column string, arg ...interface{}) *Statement

Incr Generate "Update ... Set column = column + arg" statment

func (*Statement) Init

func (statement *Statement) Init()

Init reset all the statment's fields

func (*Statement) Join

func (statement *Statement) Join(joinOP string, tablename interface{}, condition string, args ...interface{}) *Statement

Join The joinOP should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN

func (*Statement) JoinColumns

func (statement *Statement) JoinColumns(cols []*core.Column, includeTableName bool) string

func (*Statement) Limit

func (statement *Statement) Limit(limit int, start ...int) *Statement

Limit generate LIMIT start, limit statement

func (*Statement) MustCols

func (statement *Statement) MustCols(columns ...string) *Statement

MustCols update use only: must update columns

func (*Statement) NoAutoCondition

func (statement *Statement) NoAutoCondition(no ...bool) *Statement

NoAutoCondition if you do not want convert bean's field as query condition, then use this function

func (*Statement) Nullable

func (statement *Statement) Nullable(columns ...string)

Nullable Update use only: update columns to null when value is nullable and zero-value

func (*Statement) Omit

func (statement *Statement) Omit(columns ...string)

Omit do not use the columns

func (*Statement) Or

func (statement *Statement) Or(querystring string, args ...interface{}) *Statement

Or add Where & Or statment

func (*Statement) OrderBy

func (statement *Statement) OrderBy(order string) *Statement

OrderBy generate "Order By order" statement

func (*Statement) Select

func (s *Statement) Select(str string) *Statement

Select replace select

func (*Statement) SetExpr

func (statement *Statement) SetExpr(column string, expression string) *Statement

SetExpr Generate "Update ... Set column = {expression}" statment

func (*Statement) Sql

func (statement *Statement) Sql(querystring string, args ...interface{}) *Statement

Sql add the raw sql statement

func (*Statement) Table

func (statement *Statement) Table(tableNameOrBean interface{}) *Statement

Table tempororily set table name, the parameter could be a string or a pointer of struct

func (*Statement) TableName

func (statement *Statement) TableName() string

TableName return current tableName

func (*Statement) Top

func (statement *Statement) Top(limit int) *Statement

Top generate LIMIT limit statement

func (*Statement) Unscoped

func (statement *Statement) Unscoped() *Statement

Unscoped always disable struct tag "deleted"

func (*Statement) UseBool

func (statement *Statement) UseBool(columns ...string) *Statement

UseBool indicates that use bool fields as update contents and query contiditions

func (*Statement) Where

func (statement *Statement) Where(querystring string, args ...interface{}) *Statement

Where add Where statment

type SyslogLogger

type SyslogLogger struct {
	// contains filtered or unexported fields
}

SyslogLogger will be depricated

func NewSyslogLogger

func NewSyslogLogger(w *syslog.Writer) *SyslogLogger

func (*SyslogLogger) Debug

func (s *SyslogLogger) Debug(v ...interface{})

func (*SyslogLogger) Debugf

func (s *SyslogLogger) Debugf(format string, v ...interface{})

func (*SyslogLogger) Error

func (s *SyslogLogger) Error(v ...interface{})

func (*SyslogLogger) Errorf

func (s *SyslogLogger) Errorf(format string, v ...interface{})

func (*SyslogLogger) Info

func (s *SyslogLogger) Info(v ...interface{})

func (*SyslogLogger) Infof

func (s *SyslogLogger) Infof(format string, v ...interface{})

func (*SyslogLogger) IsShowSQL

func (s *SyslogLogger) IsShowSQL() bool

func (*SyslogLogger) Level

func (s *SyslogLogger) Level() core.LogLevel

func (*SyslogLogger) SetLevel

func (s *SyslogLogger) SetLevel(l core.LogLevel)

SetLevel always return error, as current log/syslog package doesn't allow to set priority level after syslog.Writer created

func (*SyslogLogger) ShowSQL

func (s *SyslogLogger) ShowSQL(show ...bool)

func (*SyslogLogger) Warn

func (s *SyslogLogger) Warn(v ...interface{})

func (*SyslogLogger) Warnf

func (s *SyslogLogger) Warnf(format string, v ...interface{})

type TableName

type TableName interface {
	TableName() string
}

type UUID

type UUID [16]byte

The UUID represents Universally Unique IDentifier (which is 128 bit long).

func NewNamespaceUUID

func NewNamespaceUUID(namespace string) *UUID

NewNamespaceUUID creates a namespace UUID by using the namespace name in the NIL name space. This is a different approach as the 4 "standard" namespace UUIDs which are timebased UUIDs (V1).

func NewV1

func NewV1() *UUID

NewV1 creates a new UUID with variant 1 as described in RFC 4122. Variant 1 is based on hosts MAC address and actual timestamp (as count of 100-nanosecond intervals since 00:00:00.00, 15 October 1582 (the date of Gregorian reform to the Christian calendar).

func NewV3

func NewV3(namespace *UUID, name []byte) *UUID

NewV3 creates a new UUID with variant 3 as described in RFC 4122. Variant 3 based namespace-uuid and name and MD-5 hash calculation.

func NewV4

func NewV4() *UUID

NewV4 creates a new UUID with variant 4 as described in RFC 4122. Variant 4 based on pure random bytes.

func NewV5

func NewV5(namespaceUUID *UUID, name []byte) *UUID

NewV5 creates a new UUID with variant 5 as described in RFC 4122. Variant 5 based namespace-uuid and name and SHA-1 hash calculation.

func (*UUID) String

func (u *UUID) String() string

String returns the human readable form of the UUID.

func (*UUID) Version

func (u *UUID) Version() int

Version of the UUID represents a kind of subtype specifier.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL