README
xorm
xorm是一个简单而强大的Go语言ORM库. 通过它可以使数据库操作非常简便。
说明
- 本库是基于原版 xorm:https://github.com/go-xorm/xorm 的定制增强版本,由于本定制版有第三方库依赖(原版xorm无任何第三方库依赖),原版xorm要保持对第三方库零依赖特性,所以只好单独开了本Github库。
- 本库的相关定制功能是为了解决更简单的进行复杂SQL调用和一些特殊业务需求场景而开发的。
- 本定制版ORM相关核心功能和原版保持一致,会跟随原版xorm更新。
- 定制功能采用针对原版弱侵入性代码实现。
特性
- 支持Struct和数据库表之间的灵活映射,并支持自动同步
- 事务支持,支持嵌套事务(支持类JAVA Spring的事务传播机制)
- 同时支持原始SQL语句和ORM操作的混合执行
- 使用连写来简化调用
- 支持使用Id, In, Where, Limit, Join, Having, Table, Sql, Cols等函数和结构体等方式作为条件
- 支持级联加载Struct
- 支持类ibatis方式配置SQL语句(支持xml配置文件、json配置文件、xsql配置文件,支持pongo2、jet、html/template模板和自定义实现配置多种方式)
- 支持动态SQL功能
- 支持一次批量混合执行多个CRUD操作,并返回多个结果集
- 支持数据库查询结果直接返回Json字符串和xml字符串
- 支持SqlMap配置文件和SqlTemplate模板密文存储和解析
- 支持缓存
- 支持主从数据库(Main/Subordinate)数据库读写分离
- 支持根据数据库自动生成xorm的结构体
- 支持记录版本(即乐观锁)
- 支持查询结果集导出csv、tsv、xml、json、xlsx、yaml、html功能
- 支持SQL Builder github.com/go-xorm/builder
- 上下文缓存支持
驱动支持
目前支持的Go数据库驱动和对应的数据库如下:
- Mysql: github.com/go-sql-driver/mysql
- MyMysql: github.com/ziutek/mymysql
- Postgres: github.com/lib/pq
- Tidb: github.com/pingcap/tidb
- SQLite: github.com/mattn/go-sqlite3
- MsSql: github.com/denisenkom/go-mssqldb
- Oracle: github.com/mattn/go-oci8 (试验性支持)
安装
使用go工具进行安装:
go get -u github.com/xormplus/xorm
文档
传送门:本定制版《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、使用RegisterSqlMap()注册SqlMap配置
2、RegisterSqlTemplate()方法注册SSqlTemplate模板配置
3、SqlMap配置文件总根目录和SqlTemplate模板配置文件总根目录可为同一目录
--------------------------------------------------------------------------------------------------*/
//注册SqlMap配置,可选功能,如应用中无需使用SqlMap,可无需初始化
//此处使用xml格式的配置,配置文件根目录为"./sql/oracle",配置文件后缀为".xml"
err = x.RegisterSqlMap(xorm.Xml("./sql/oracle", ".xml"))
if err != nil {
t.Fatal(err)
}
//注册动态SQL模板配置,可选功能,如应用中无需使用SqlTemplate,可无需初始化
//此处注册动态SQL模板配置,使用Pongo2模板引擎,配置文件根目录为"./sql/oracle",配置文件后缀为".stpl"
err = x.RegisterSqlTemplate(xorm.Pongo2("./sql/oracle", ".stpl"))
if err != nil {
t.Fatal(err)
}
//开启SqlMap配置文件和SqlTemplate配置文件更新监控功能,将配置文件更新内容实时更新到内存,如无需要可以不调用该方法
err = engine.StartFSWatcher()
if err != nil {
t.Fatal(err)
}
-
db.RegisterSqlMap()过程
- 使用RegisterSqlMap()方法指定SqlMap配置文件文件格式,配置文件总根目录,配置文件后缀名,RegisterSqlMap()方法按指定目录遍历所配置的目录及其子目录下的所有xml配置文件(配置文件样例)或json配置文件(配置文件样例)
- 解析所有配置SqlMap的xml配置文件或json配置文件
- xml配置文件中sql标签的id属性值作为SqlMap的key,如有重名id,则后加载的覆盖之前加载的配置sql条目
- json配置文件中key值作为SqlMap的key,如有重名key,则后加载的覆盖之前加载的配置sql条目
- json配置文件中key和xml配置文件中sql标签的id属性值有相互重名的,则后加载的覆盖之前加载的配置sql条目
- 配置文件中sql配置会读入内存并缓存
- 由于SqlTemplate模板能完成更多复杂组装和特殊场景需求等强大功能,故SqlMap的xml或json只提供这种极简配置方式,非ibatis的OGNL的表达式实现方式
-
db.RegisterSqlTemplate()过程
- 使用RegisterSqlTemplate()方法指定SqlTemplate模板的模板引擎(支持pongo2、jet、html/template3种模板引擎,但只能选用一种,不能同时混用),配置文件总根目录,配置文件后缀名,RegisterSqlTemplate()方法按指定目录遍历所配置的目录及其子目录及其子目录下的所有stpl模板文件(模板文件样例)
- 使用指定模板引擎解析stpl模板文件
- stpl模板文件名作为SqlTemplate存储的key(不包含目录路径),如有不同路径下出现同名文件,则后加载的覆盖之前加载的配置模板内容
- stpl模板内容会读入内存并缓存
-
支持最原始的SQL语句查询
/*-------------------------------------------------------------------------------------
* 第1种方式:返回的结果类型为 []map[string][]byte
-------------------------------------------------------------------------------------*/
sql_1_1 := "select * from user"
results, err := engine.QueryBytes(sql_1_1)
//SqlMapClient和SqlTemplateClient传参方式类同如下2种,具体参见第6种方式和第7种方式
sql_1_2 := "select id,userid,title,createdatetime,content from Article where id=?"
results, err := db.SQL(sql_1_2, 2).QueryBytes()
sql_1_3 := "select id,userid,title,createdatetime,content from Article where id=?id"
paramMap_1_3 := map[string]interface{}{"id": 2}
results, err := db.SQL(sql_1_3, ¶mMap_1_3).QueryBytes()
/*-------------------------------------------------------------------------------------
* 第2种方式:返回的结果类型为 []map[string]string
-------------------------------------------------------------------------------------*/
sql_2_1 := "select * from user"
results, err := engine.QueryString(sql_2_1)
//SqlMapClient和SqlTemplateClient传参方式类同如下2种,具体参见第6种方式和第7种方式
sql_2_2 := "select id,userid,title,createdatetime,content from Article where id=?"
results, err := db.SQL(sql_2_2, 2).QueryString()
sql_2_3 := "select id,userid,title,createdatetime,content from Article where id=?id"
paramMap_2_3 := map[string]interface{}{"id": 2}
results, err := db.SQL(sql_2_3, ¶mMap_2_3).QueryString()
/*-------------------------------------------------------------------------------------
* 第3种方式:返回的结果类型为 []map[string]xorm.Value
-------------------------------------------------------------------------------------*/
//xorm.Value类型本质是[]byte,具有一系列类型转换函数
sql_2_1 := "select * from user"
results, err := engine.QueryValue(sql_2_1)
//SqlMapClient和SqlTemplateClient传参方式类同如下2种,具体参见第6种方式和第7种方式
sql_2_2 := "select id,userid,title,createdatetime,content from Article where id=?"
results, err := db.SQL(sql_2_2, 2).QueryValue()
title := results[0]["title"].String()
sql_2_3 := "select id,userid,title,createdatetime,content from Article where id=?id"
paramMap_2_3 := map[string]interface{}{"id": 2}
results, err := db.SQL(sql_2_3, ¶mMap_2_3).QueryValue()
/*-------------------------------------------------------------------------------------
* 第4种方式:返回的结果类型为 xorm.Result
-------------------------------------------------------------------------------------*/
//xorm.Value类型本质是[]byte,具有一系列类型转换函数
sql_2_1 := "select * from user"
results, err := engine.QueryResult(sql_2_1).List()
//SqlMapClient和SqlTemplateClient传参方式类同如下2种,具体参见第6种方式和第7种方式
sql_2_2 := "select id,userid,title,createdatetime,content from Article where id=?"
result, err := db.SQL(sql_2_2, 2).QueryResult().List()
title := result[0]["createdatetime"].Time("2006-01-02T15:04:05.999Z")
content := result[0]["content"].NullString()
sql_2_3 := "select id,userid,title,createdatetime,content from Article where id=?id"
paramMap_2_3 := map[string]interface{}{"id": 2}
results, err := db.SQL(sql_2_3, ¶mMap_2_3).QueryResult().List()
/*-------------------------------------------------------------------------------------
* 第5种方式:返回的结果类型为 []map[string]interface{}
-------------------------------------------------------------------------------------*/
sql_3_1 := "select * from user"
results, err := engine.QueryInterface(sql_3_1)
//SqlMapClient和SqlTemplateClient传参方式类同如下2种,具体参见第6种方式和第7种方式
sql_3_2 := "select id,userid,title,createdatetime,content from Article where id=?"
results, err := db.SQL(sql_3_2, 2).QueryInterface()
sql_3_3 := "select id,userid,title,createdatetime,content from Article where id=?id"
paramMap_3_3 := map[string]interface{}{"id": 2}
results, err := db.SQL(sql_3_3, ¶mMap_3_3).QueryInterface()
//Query方法返回的是一个ResultMap对象,它有List(),Count(),ListPage(),Json(),Xml()
//Xml(),XmlIndent(),SaveAsCSV(),SaveAsTSV(),SaveAsHTML(),SaveAsXML(),SaveAsXMLWithTagNamePrefixIndent(),
//SaveAsYAML(),SaveAsJSON(),SaveAsXLSX()系列实用函数
sql_3_4 := "select * from user"
//List()方法返回查询的全部结果集,类型为[]map[string]interface{}
results, err := engine.Sql(sql_3_4).Query().List()
//当然也支持这种方法,将数据库中的时间字段格式化,时间字段对应的golang数据类型为time.Time
//当然你也可以在数据库中先使用函数将时间类型的字段格式化成字符串,这里只是提供另外一种方式
//该方式会将所有时间类型的字段都格式化,所以请依据您的实际需求按需使用
results, err := engine.Sql(sql_3_4).QueryWithDateFormat("20060102").List()
sql_3_5 := "select * from user where id = ? and age = ?"
results, err := engine.Sql(sql_3_5, 7, 17).Query().List()
sql_3_6 := "select * from user where id = ?id and age = ?age"
paramMap_3_6 := map[string]interface{}{"id": 7, "age": 17}
results, err := engine.Sql(sql_3_6, ¶mMap_3_6).Query().List()
//此Query()方法返回对象还支持ListPage()方法和Count()方法,这两个方法都是针对数据库查询出来后的结果集进行操作
//此Query()方法返回对象还支持Xml()方法、XmlIndent()方法和Json()方法,相关内容请阅读之后的章节
//ListPage()方法并非数据库分页方法,只是针对数据库查询出来后的结果集[]map[string]interface{}对象取部分切片
//例如以下例子,是取结果集的第1条到第50条记录
results, err := engine.Sql(sql_3_5, 7, 17).Query().ListPage(1,50)
//例如以下例子,是取结果集的第13条到第28条记录
results, err := engine.Sql(sql_3_5, 7, 17).Query().ListPage(13,28)
//此Count()方法也并非使用数据库count函数查询数据库某条件下的记录数,只是针对Sql语句对数据库查询出来后的结果集[]map[string]interface{}对象的数量
//此Count()方法也并非Engine对象和Session对象下的Count()方法,使用时请区分场景
count, err := engine.Sql(sql_3_5, 7, 17).Query().Count()
/*-------------------------------------------------------------------------------------
第6种方式:执行SqlMap配置文件中的Sql语句,返回的结果类型为 []map[string]interface{}
-------------------------------------------------------------------------------------*/
sql_id_4_1 := "sql_4_1" //配置文件中sql标签的id属性,SqlMap的key
results, err := engine.SqlMapClient(sql_id_4_1).Query().List()
sql_id_4_2 := "sql_4_2"
results, err := engine.SqlMapClient(sql_id_4_2, 7, 17).Query().List()
sql_id_4_3 := "sql_4_3"
paramMap_4_3 := map[string]interface{}{"id": 7, "name": "xormplus"}
results1, err := engine.SqlMapClient(sql_id_4_3, ¶mMap_4_3).Query().List()
/*-------------------------------------------------------------------------------------
* 第7种方式:执行SqlTemplate配置文件中的Sql语句,返回的结果类型为 []map[string]interface{}
-------------------------------------------------------------------------------------*/
sql_key_5_1 := "select.example.stpl" //配置文件名,SqlTemplate的key
//执行的 sql:select * from user where id=7
//如部分参数未使用,请记得使用对应类型0值,如此处name参数值为空字符串,模板使用指南请详见pongo2
paramMap_5_1 := map[string]interface{}{"count": 2, "id": 7, "name": ""}
results, err := engine.SqlTemplateClient(sql_key_5_1, ¶mMap_5_1).Query().List()
//执行的 sql:select * from user where name='xormplus'
//如部分参数未使用,请记得使用对应类型0值,如此处id参数值为0,模板使用指南请详见pongo2
paramMap_5_2 := map[string]interface{}{"id": 0, "count": 2, "name": "xormplus"}
results, err := engine.SqlTemplateClient(sql_key_5_1, ¶mMap_5_2).Query().List()
/*-------------------------------------------------------------------------------------
* 第8种方式:返回的结果类型为对应的[]interface{}
-------------------------------------------------------------------------------------*/
var categories []Category
err := engine.Sql("select * from category where id =?", 16).Find(&categories)
paramMap_6 := map[string]interface{}{"id": 2}
err := engine.Sql("select * from category where id =?id", ¶mMap_6).Find(&categories)
/*-------------------------------------------------------------------------------------
* 第9种方式:返回的结果类型为对应的[]interface{}
-------------------------------------------------------------------------------------*/
sql_id_7_1 := "sql_7_1"
var categories []Category
err := engine.SqlMapClient(sql_id_7_1, 16).Find(&categories)
sql_id_7_2 := "sql_7_2"
var categories []Category
paramMap_7_2 := map[string]interface{}{"id": 25}
err := engine.SqlMapClient(sql_id_7_2, ¶mMap_7_2).Find(&categories)
/*-------------------------------------------------------------------------------------
* 第10种方式:返回的结果类型为对应的[]interface{}
-------------------------------------------------------------------------------------*/
//执行的 sql:select * from user where name='xormplus'
sql_key_8_1 := "select.example.stpl" //配置文件名,SqlTemplate的key
var users []User
paramMap_8_1 := map[string]interface{}{"id": 0, "count": 2, "name": "xormplus"}
err := engine.SqlTemplateClient(sql_key_8_1, ¶mMap_8_1).Find(&users)
/*-------------------------------------------------------------------------------------
* 第11种方式:查询单条数据
* 使用Sql,SqlMapClient,SqlTemplateClient函数与Get函数组合可以查询单条数据,以Sql与Get函数组合为例:
-------------------------------------------------------------------------------------*/
//获得单条数据的值,并存为结构体
var article Article
has, err := db.Sql("select * from article where id=?", 2).Get(&article)
//获得单条数据的值并存为map
var valuesMap1 = make(map[string]string)
has, err := db.Sql("select * from article where id=?", 2).Get(&valuesMap1)
var valuesMap2 = make(map[string]interface{})
has, err := db.Sql("select * from article where id=?", 2).Get(&valuesMap2)
var valuesMap3 = make(map[string]xorm.Value)
has, err := db.Sql("select * from article where id=?", 2).Get(&valuesMap3)
//获得单条数据的值并存为xorm.Record
record := make(xorm.Record)
has, err = session.SQL("select * from article where id=?", 2).Get(&record)
id := record["id"].Int64()
content := record["content"].NullString()
//获得单条数据某个字段的值
var title string
has, err := db.Sql("select title from article where id=?", 2).Get(&title)
var id int
has, err := db.Sql("select id from article where id=?", 2).Get(&id)
-
注:
- 除以上9种方式外,本库还支持另外3种方式,由于这3种方式支持一次性批量混合CRUD操作,返回多个结果集,且支持多种参数组合形式,内容较多,场景比较复杂,因此不在此处赘述。
- 欲了解另外3种方式相关内容您可移步批量SQL操作章节,此3种方式将在此章节单独说明
-
采用Sql(),SqlMapClient(),SqlTemplateClient()方法执行sql调用Find()方法,与ORM方式调用Find()方法不同(传送门:ORM方式操作数据库),此时Find()方法中的参数,即结构体的名字不需要与数据库表的名字映射(因为前面的Sql()方法已经确定了SQL语句),但字段名需要和数据库中的字段名字做映射。使用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
Title string
Categoryname string
Isdraft int
Lastupdatetime time.Time
}
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)
- 第4种和第7种方式所使用的SqlMap配置文件内容如下
<sqlMap>
<sql id="sql_4_1">
select * from user
</sql>
<sql id="sql_4_2">
select * from user where id=? and age=?
</sql>
<sql id="sql_4_3">
select * from user where id=?id and name=?name
</sql>
<sql id="sql_id_7_1">
select * from category where id =?
</sql>
<sql id="sql_id_7_2">
select * from category where id =?id
</sql>
</sqlMap>
- 第5种和第8种方式所使用的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, ¶mMap_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, ¶mMap_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, ¶mMap).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, ¶mMap).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, ¶mMap_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, ¶mMap).Query().Results[0]["id"] //返回查询结果的第一条数据的id列的值
//第3种方式
id := engine.SqlTemplateClient(key, ¶mMap).Query().Results[0]["id"] //返回查询结果的第一条数据的id列的值
- 在sqltemplate中使用自定义函数(目前暂支持默认的HTMLTemplate,其他两种TODO,但也有变通方法使用)
//定义的自定义函数
func ShowTimestamp(now time.Time) string {
return fmt.Sprintf("%d", now.Unix())
}
func main() {
engine, err := xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", "root", "", "127.0.0.1", "3306", "mysql"))
if err != nil {
panic(err)
}
engine.ShowExecTime(true)
engine.ShowSQL(true)
tpl := xorm.Default("./templates", ".tpl")
tpl.SetFuncs("test.tpl", xorm.FuncMap{"ShowTimestamp": ShowTimestamp})
err = engine.RegisterSqlTemplate(tpl)
if err != nil {
panic(err)
}
result := engine.SqlTemplateClient("test.tpl",&map[string]interface{}{"now":time.Now()}).Query()
}
//模板中编写的sql内容如下
select * from user{{ShowTimestamp .now}}
事务模型
-
本xorm版本同时支持简单事务模型和嵌套事务模型进行事务处理,当使用简单事务模型进行事务处理时,需要创建Session对象,另外当使用Sql()、SqlMapClient()、SqlTemplateClient()方法进行操作时也推荐手工创建Session对象方式管理Session。在进行事务处理时,可以混用ORM方法和RAW方法。注意如果您使用的是mysql,数据库引擎为innodb事务才有效,myisam引擎是不支持事务的。示例代码如下:
-
事务的简写方法
res, err := engine.Transaction(func(session *xorm.Session) (interface{}, error) {
user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
if _, err := session.Insert(&user1); err != nil {
return nil, err
}
user2 := Userinfo{Username: "yyy"}
if _, err := session.Where("id = ?", 2).Update(&user2); err != nil {
return nil, err
}
if _, err := session.Exec("delete from userinfo where username = ?", user2.Username); err != nil {
return nil, err
}
return nil, nil
})
- Context Cache, if enabled, current query result will be cached on session and be used by next same statement on the same session.
sess := engine.NewSession()
defer sess.Close()
var context = xorm.NewMemoryContextCache()
var c2 ContextGetStruct
has, err := sess.ID(1).ContextCache(context).Get(&c2)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, 1, c2.Id)
assert.EqualValues(t, "1", c2.Name)
sql, args := sess.LastSQL()
assert.True(t, len(sql) > 0)
assert.True(t, len(args) > 0)
var c3 ContextGetStruct
has, err = sess.ID(1).ContextCache(context).Get(&c3)
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, 1, c3.Id)
assert.EqualValues(t, "1", c3.Name)
sql, args = sess.LastSQL()
assert.True(t, len(sql) == 0)
assert.True(t, len(args) == 0)
- 简单事务模型的一般用法
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
}
// add Commit() after all actions
err = session.Commit()
if err != nil {
return
}
- 嵌套事务模型
在实际业务开发过程中我们会发现依然还有一些特殊场景,我们需要借助嵌套事务来进行事务处理。本xorm版本也提供了嵌套事务的支持。当使用嵌套事务模型进行事务处理时,同样也需要创建Session对象,与使用简单事务模型进行事务处理不同在于,使用session.Begin()创建简单事务时,直接在同一个session下操作,而使用嵌套事务模型进行事务处理时候,使用session.BeginTrans()创建嵌套事务时,将返回Transaction实例,后续操作则在同一个Transaction实例下操作。在进行具体数据库操作时候,则使用tx.Session() API可以获得当前事务所持有的session会话,从而进行Get(),Find(),Execute()等具体数据库操作。
session := engine.NewSession()
defer session.Close()
// add BeginTrans() before any action
tx, err := session.BeginTrans()
if err != nil {
return
}
user1 := Userinfo{Username: "xiaoxiao", Departname: "dev", Alias: "lunny", Created: time.Now()}
_, err = tx.Session().Insert(&user1)
if err != nil {
tx.Rollback()
return
}
user2 := Userinfo{Username: "yyy"}
_, err = tx.Session().Where("id = ?", 2).Update(&user2)
if err != nil {
tx.RollbackTrans()
return
}
_, err = tx.Session().Exec("delete from userinfo where username = ?", user2.Username)
if err != nil {
tx.RollbackTrans()
return
}
_, err = tx.Session().SqlMapClient("delete.userinfo", user2.Username).Execute()
if err != nil {
tx.RollbackTrans()
return
}
// add CommitTrans() after all actions
err = tx.CommitTrans()
if err != nil {
...
return
}
本定制版xorm支持嵌套事务(类JAVA Spring的事务传播机制),这部分内容较多,详细了解请您移步本定制版《xorm操作指南》
SqlMap及SqlTemplate
- SqlMap及SqlTemplate相关功能API
//注册SqlMap配置,xml格式
err := engine.RegisterSqlMap(xorm.Xml("./sql/oracle", ".xml"))
//注册SqlMap配置,json格式
err := engine.RegisterSqlMap(xorm.Json("./sql/oracle", ".json"))
//注册SqlTemplate配置,使用Pongo2模板引擎
err := engine.RegisterSqlTemplate(xorm.Pongo2("./sql/oracle", ".stpl"))
//注册SqlTemplate配置,使用Jet模板引擎
err := engine.RegisterSqlTemplate(xorm.Jet("./sql/oracle", ".jet"))
//注册SqlTemplate配置,使用html/template模板引擎
err := engine.RegisterSqlTemplate(xorm.Default("./sql/oracle", ".tpl"))
//开启SqlMap配置文件和SqlTemplate配置文件更新监控功能,将配置文件更新内容实时更新到内存,如无需要可以不调用该方法
//该监控模式下,如删除配置文件,内存中不会删除相关配置
engine.StartFSWatcher()
//停止SqlMap配置文件和SqlTemplate配置文件更新监控功能
engine.StopFSWatcher()
/*------------------------------------------------------------------------------------
1、以下方法是在没有engine.RegisterSqlMap()和engine.RegisterSqlTemplate()初始化相关配置文件的情况下让您在代码中可以轻松的手动管理SqlMap配置及SqlTemplate模板。
2、engine.RegisterSqlMap()和engine.RegisterSqlTemplate()初始化相关配置文件之后也可以使用以下方法灵活的对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.SqlTemplate.LoadSqlTemplate(filepath) //加载指定文件的SqlTemplate模板
engine.SqlTemplate.ReloadSqlTemplate(filepath) //重新加载指定文件的SqlTemplate模板
engine.SqlTemplate.BatchLoadSqlTemplate([]filepath) //批量加载SqlTemplate模板
engine.SqlTemplate.BatchReloadSqlTemplate([]filepath) //批量加载SqlTemplate模板
engine.SqlTemplate.AddSqlTemplate(key, sql) //新增一条SqlTemplate模板,sql为SqlTemplate模板内容字符串
engine.SqlTemplate.UpdateSqlTemplate(key, sql) //更新一条SqlTemplate模板,sql为SqlTemplate模板内容字符串
engine.SqlTemplate.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.SqlTemplate.GetSqlTemplates(...key)
- SqlMap配置文件及SqlTemplate模板加密存储及解析
- 出于系统信息安全的原因,一些大公司有自己的信息安全规范。其中就有类似这样的配置文件不允许明文存储的需求,本xorm定制版本也内置了一些API对SqlMap配置文件及SqlTemplate模板密文存储解析的需求进行支持。
- 本库内置提供了AES,DES,3DES,RSA四种加密算法支持SqlMap配置文件及SqlTemplate模板加解密存储解析功能。其中,AES,DES,3DES和标准实现略有不同,如不提供key,本库会提供了一个内置key,当然您也可以设置自己的key。RSA支持公钥加密私钥解密和私钥加密公钥解密两种模式。
- 本库还提供一个批量配置文件加密工具,采用sciter的Golang绑定库实现。工具传送门:xorm tools。
- 除以上4种内置加解密算法外,本库也支持自定义加解密算法功能,您也可以使用自己实现的加密解密算法,只需要实现Cipher接口即可。
- 内存中缓存的是经指定解密算法解密之后的配置文件内容或模板内容。
- SqlMap配置文件及SqlTemplate模板加密存储及解析具体示例如下:
//如需使用自定义的加密解密算法,只需实现Cipher接口即可
type Cipher interface {
Encrypt(strMsg string) ([]byte, error)
Decrypt(src []byte) (decrypted []byte, err error)
}
//SqlMapOptions中的Cipher实现了加密和解密方法
type SqlMapOptions struct {
Capacity uint
Extension string
Cipher Cipher
}
//SqlTemplateOptions中的Cipher实现了加密和解密方法
type SqlTemplateOptions struct {
Capacity uint
Extension string
Cipher Cipher
}
//如现在我们已经使用3DES加密了SqlMap配置文件和SqlTemplate模板,则xorm初始化方式如下
var err error
engine, err = xorm.NewPostgreSQL("postgres://postgres:root@localhost:5432/mblog?sslmode=disable")
if err != nil {
t.Fatal(err)
}
enc := &xorm.AesEncrypt{
PubKey: "122334",
}
//如自定义加解密算法,则此处传入的enc为自己实现的加解密算法,后续代码与本示例一致
err = x.RegisterSqlMap(xorm.Xml("./sql/aes", ".xml"), enc)
if err != nil {
t.Fatal(err)
}
//这里也可以new其他加密解密算法,SqlMap配置文件和SqlTemplate模板的加密结算算法可不相同
err = x.RegisterSqlTemplate(xorm.Pongo2("./sql/aes", ".stpl"), enc)
if err != nil {
t.Fatal(err)
}
//内置4种加密算法如下
type AesEncrypt struct {
PubKey string
}
type DesEncrypt struct {
PubKey string
}
type TripleDesEncrypt struct {
PubKey string
}
//RSA加密解密算法支持公钥加密私钥解密和私钥加密公钥解密两种模式,请合理设置DecryptMode
type RsaEncrypt struct {
PubKey string
PriKey string
pubkey *rsa.PublicKey
prikey *rsa.PrivateKey
EncryptMode int
DecryptMode int
}
const (
RSA_PUBKEY_ENCRYPT_MODE = iota //RSA公钥加密
RSA_PUBKEY_DECRYPT_MODE //RSA公钥解密
RSA_PRIKEY_ENCRYPT_MODE //RSA私钥加密
RSA_PRIKEY_DECRYPT_MODE //RSA私钥解密
)
//RSA使用示例
pukeyStr := `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyqyVCWQBeIgY4FyLnrA1
viOq9m++OyUwXIvpEH7zN7MjeJp7nSK5PBkvv81zIbQrMQXQzTuE52QjYfMfHVoq
FyK+Qxw+B/1qY3TACj8b4TlDS0IrII9u1QBRhGHmtmqJ5c6As/rIqYLQCdbmycC0
3iKBM8990Pff8uq+jqzsoQCFDexZClprR6Vbz3S1ejoFLuDUAXUfNrsudQ/7it3s
Vn540kh4a9MKeSOg68TSmKKQe1huTF03uDAdPuDveFpVU/l7nETH8mFoW06QvvJR
6Dh6FC9LzJA6EOK4fNGeDzJg9e2jByng/ubJM6WeU29uri2zwnMGQ3qsCuGMXBS/
yQIDAQAB
-----END PUBLIC KEY-----`
var err error
engine, err = xorm.NewPostgreSQL("postgres://postgres:root@localhost:5432/mblog?sslmode=disable")
if err != nil {
t.Fatal(err)
}
//公钥解密
enc := new(xorm.RsaEncrypt)
enc.PubKey = pukeyStr
enc.DecryptMode = xorm.RSA_PUBKEY_DECRYPT_MODE
err = engine.RegisterSqlMap(xorm.Xml("./sql/rsa", ".xml"), enc)
if err != nil {
t.Fatal(err)
}
err = engine.RegisterSqlTemplate(xorm.Pongo2("./sql/rsa", ".stpl"), enc)
if err != nil {
t.Fatal(err)
}
/*----------------------------------------------------------------------------------------------------
其他相关API
1.ClearSqlMapCipher()可清除SqlMap中设置的Cipher,这样可以使用engine.LoadSqlMap(filepath)手工加载一些没有加密的配置文件
2.如果您之后又想加载一些其他加密算法存储的配置文件,也可以先清除,再重新SetSqlMapCipher()之后加载
3.当然,配置文件也可以不加密存储,遇到需要部分加密存储的配置文件可以手工调用SetSqlMapCipher()之后加载
4.注意InitSqlMap()是对整个SqlMapRootDir做统一操作,如您有区别对待的配置文件,请自行设置隔离目录,使用ClearSqlMapCipher()或SetSqlMapCipher()后调用LoadSqlMap()方法进行指定处理。
----------------------------------------------------------------------------------------------------*/
engine.ClearSqlMapCipher()
engine.SetSqlMapCipher(cipher)
/*----------------------------------------------------------------------------------------------------
1.ClearSqlTemplateCipher()可清除SqlTemplate中设置的Cipher,这样可以使用engine.LoadSqlTemplate(filepath)手工加载一些没有加密的模板文件
2.如果您之后又想加载一些其他加密算法存储的模板文件,也可以先清除,再重新SetSqlTemplateCipher()之后加载
3.当然,配置文件也可以不加密存储,遇到需要部分加密存储的配置文件可以手工调用SetSqlTemplateCipher()之后加载
4.注意InitSqlMap()是对整个SqlTemplateRootDir做统一操作,如您有区别对待的配置文件,请自行设置隔离目录,使用ClearSqlTemplateCipher()或SetSqlTemplateCipher()后调用LoadSqlTemplate()方法进行指定处理。
----------------------------------------------------------------------------------------------------*/
engine.ClearSqlTemplateCipher()
engine.SetSqlTemplateCipher(cipher)
# 批量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
tx,err := session.Begin()
_, err = tx.Session().Exec("delete from userinfo where username = ?", user2.Username)
if err != nil {
tx.Rollback()
return
}
//Execuet返回值有3个,分别为slice,map,error类型
results, _, err = tx.Session().Sqls(sqls, parmas...).Execute()
if err != nil {
tx.Rollback()
return
}
_, results, err = tx.Session().SqlMapsClient(sqlkeys, parmas...).Execute()
if err != nil {
tx.Rollback()
return
}
results, _, err = tx.Session().SqlTemplatesClient(sqlkeys, parmas...).Execute()
if err != nil {
tx.Rollback()
return
}
// add Commit() after all actions
err = tx.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...)方法说明:
- 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一一对应。
- 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...)方法说明:
- 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
- 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...)方法说明:
- 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
- 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
var name string
has, err := engine.Table(&user).Where("id = ?", id).Cols("name").Get(&name)
// SELECT name FROM user WHERE id = ?
var id int64
has, err := engine.Table(&user).Where("name = ?", name).Cols("id").Get(&id)
// SELECT id FROM user WHERE name = ?
var valuesMap = make(map[string]string)
has, err := engine.Table(&user).Where("id = ?", id).Get(&valuesMap)
// SELECT * FROM user WHERE id = ?
var valuesSlice = make([]interface{}, len(cols))
has, err := engine.Table(&user).Where("id = ?", id).Cols(cols...).Get(&valuesSlice)
// SELECT col1, col2, col3 FROM user WHERE id = ?
- 检测记录是否存在
has, err := testEngine.Exist(new(RecordExist))
// SELECT * FROM record_exist LIMIT 1
has, err = testEngine.Exist(&RecordExist{
Name: "test1",
})
// SELECT * FROM record_exist WHERE name = ? LIMIT 1
has, err = testEngine.Where("name = ?", "test1").Exist(&RecordExist{})
// SELECT * FROM record_exist WHERE name = ? LIMIT 1
has, err = testEngine.SQL("select * from record_exist where name = ?", "test1").Exist()
// select * from record_exist where name = ?
has, err = testEngine.Table("record_exist").Exist()
// SELECT * FROM record_exist LIMIT 1
has, err = testEngine.Table("record_exist").Where("name = ?", "test1").Exist()
// SELECT * FROM record_exist WHERE name = ? 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
- 子查询
var student []Student
err = db.Table("student").Select("id ,name").Where("id in (?)", db.Table("studentinfo").Select("id").Where("status = ?", 2).QueryExpr()).Find(&student)
//SELECT id ,name FROM `student` WHERE (id in (SELECT id FROM `studentinfo` WHERE (status = 2)))
- 根据条件遍历数据库,可以有两种方式: 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
FindAndCount
combines functionFind
withCount
which is usually used in query by page
var users []User
counts, err := engine.FindAndCount(&users)
- 条件编辑器
err := engine.Where(builder.NotIn("a", 1, 2).And(builder.In("b", "c", "d", "e"))).Find(&users)
// SELECT id, name ... FROM user WHERE a NOT IN (?, ?) AND b IN (?, ?, ?)
- 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)
部分测试用例
讨论
请加入原版xorm QQ群一:280360085(已满)QQ群二:795010183 进行讨论。本定制版API设计相关建议可联系本人QQ:50892683
Documentation
Overview ¶
Copyright 2018 The Xorm Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Index ¶
- Constants
- Variables
- func Bool(i interface{}) bool
- func Bytes(i interface{}) []byte
- func ConvertToBoundSQL(sql string, args []interface{}) (string, error)
- func DecodeToString(b []byte) string
- func Encode(vs ...interface{}) []byte
- func EncodeBool(b bool) []byte
- func EncodeFloat32(f float32) []byte
- func EncodeFloat64(f float64) []byte
- func EncodeInt(i int) []byte
- func EncodeInt16(i int16) []byte
- func EncodeInt32(i int32) []byte
- func EncodeInt64(i int64) []byte
- func EncodeInt8(i int8) []byte
- func EncodeString(s string) []byte
- func EncodeUint(i uint) []byte
- func EncodeUint16(i uint16) []byte
- func EncodeUint32(i uint32) []byte
- func EncodeUint64(i uint64) []byte
- func EncodeUint8(i uint8) []byte
- func Float32(i interface{}) float32
- func Float64(i interface{}) float64
- func Int(i interface{}) int
- func Int16(i interface{}) int16
- func Int32(i interface{}) int32
- func Int64(i interface{}) int64
- func Int8(i interface{}) int8
- func IsNumeric(s string) bool
- func JSONString(v interface{}, IndentJSON bool) (string, error)
- func NewDataset(headers []string) *tablib.Dataset
- func NewDatasetWithData(headers []string, data interface{}, mustMatch bool) (*tablib.Dataset, error)
- func NewMemoryContextCache() memoryContextCache
- func PKCS5Padding(ciphertext []byte, blockSize int) []byte
- func PKCS5UnPadding(origData []byte) []byte
- func StrToTime(str string, format string, TZLocation ...*time.Location) (time.Time, error)
- func String(i interface{}) string
- func Strings(i interface{}) []string
- func Time(i interface{}, format string, TZLocation ...*time.Location) time.Time
- func TimeDuration(i interface{}) time.Duration
- func Uint(i interface{}) uint
- func Uint16(i interface{}) uint16
- func Uint32(i interface{}) uint32
- func Uint64(i interface{}) uint64
- func Uint8(i interface{}) uint8
- func ZeroPadding(ciphertext []byte, blockSize int) []byte
- func ZeroUnPadding(origData []byte) []byte
- type AesEncrypt
- type AfterDeleteProcessor
- type AfterInsertProcessor
- type AfterLoadProcessor
- type AfterLoadSessionProcessor
- type AfterSetProcessor
- type AfterUpdateProcessor
- type BeforeDeleteProcessor
- type BeforeInsertProcessor
- type BeforeSetProcessor
- type BeforeUpdateProcessor
- type Cell
- type Cipher
- type ContextCache
- type Databook
- func (databook *Databook) AddSheet(title string, data interface{}, mustMatch bool, headers ...[]string) error
- func (databook *Databook) HTML() *tablib.Exportable
- func (databook *Databook) JSON() (*tablib.Exportable, error)
- func (databook *Databook) SaveAsHTML(filename string, perm os.FileMode) error
- func (databook *Databook) SaveAsJSON(filename string, perm os.FileMode) error
- func (databook *Databook) SaveAsXLSX(filename string, perm os.FileMode) error
- func (databook *Databook) SaveAsXML(filename string, perm os.FileMode) error
- func (databook *Databook) SaveAsYAML(filename string, perm os.FileMode) error
- func (databook *Databook) Sheet(title string) tablib.Sheet
- func (databook *Databook) Sheets() map[string]tablib.Sheet
- func (databook *Databook) Size() int
- func (databook *Databook) Wipe()
- func (databook *Databook) XLSX() (*tablib.Exportable, error)
- func (databook *Databook) XML() (*tablib.Exportable, error)
- func (databook *Databook) YAML() (*tablib.Exportable, error)
- type DesEncrypt
- type Engine
- func NewDB(driverName string, dataSourceName string) (*Engine, error)
- func NewEngine(driverName string, dataSourceName string) (*Engine, error)
- func NewEngineWithDialectAndDB(driverName, dataSourceName string, dialect dialects.Dialect, db *core.DB) (*Engine, error)
- func NewEngineWithParams(driverName string, dataSourceName string, params map[string]string) (*Engine, error)
- func NewKB(driverName string, dataSourceName string) (*Engine, error)
- func NewMSSQL(driverName string, dataSourceName string) (*Engine, error)
- func NewMySQL(driverName string, dataSourceName string) (*Engine, error)
- func NewOracle(driverName string, dataSourceName string) (*Engine, error)
- func NewPostgreSQL(dataSourceName string) (*Engine, error)
- func NewSqlite3(dataSourceName string) (*Engine, error)
- func (engine *Engine) AddHook(hook contexts.Hook)
- func (engine *Engine) AddSql(key string, sql string)
- func (engine *Engine) AddSqlTemplate(key string, sqlTemplateStr string) error
- func (engine *Engine) After(closures func(interface{})) *Session
- func (engine *Engine) Alias(alias string) *Session
- func (engine *Engine) AllCols() *Session
- func (engine *Engine) Asc(colNames ...string) *Session
- func (engine *Engine) AutoIncrStr() string
- func (engine *Engine) BatchAddSql(sqlStrMap map[string]string)
- func (engine *Engine) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
- func (engine *Engine) BatchLoadSqlMap(filepathSlice []string) error
- func (engine *Engine) BatchLoadSqlTemplate(filepathSlice []string) error
- func (engine *Engine) BatchReloadSqlMap(filepathSlice []string) error
- func (engine *Engine) BatchReloadSqlTemplate(filepathSlice []string) error
- func (engine *Engine) BatchRemoveSql(key []string)
- func (engine *Engine) BatchRemoveSqlTemplate(key []string)
- func (engine *Engine) BatchUpdateSql(sqlStrMap map[string]string)
- func (engine *Engine) BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
- func (engine *Engine) Before(closures func(interface{})) *Session
- func (engine *Engine) BufferSize(size int) *Session
- func (engine *Engine) Cascade(trueOrFalse ...bool) *Session
- func (engine *Engine) Charset(charset string) *Session
- func (engine *Engine) ClearCache(beans ...interface{}) error
- func (engine *Engine) ClearCacheBean(bean interface{}, id string) error
- func (engine *Engine) ClearSqlMapCipher()
- func (engine *Engine) Clone() (*Engine, error)
- func (engine *Engine) Close() error
- func (engine *Engine) Cols(columns ...string) *Session
- func (engine *Engine) Context(ctx context.Context) *Session
- func (engine *Engine) Count(bean ...interface{}) (int64, error)
- func (engine *Engine) CreateIndexes(bean interface{}) error
- func (engine *Engine) CreateTables(beans ...interface{}) error
- func (engine *Engine) CreateUniques(bean interface{}) error
- func (engine *Engine) DB() *core.DB
- func (engine *Engine) DBMetas() ([]*schemas.Table, error)
- func (engine *Engine) DataSourceName() string
- func (engine *Engine) Decr(column string, args ...interface{}) *Session
- func (engine *Engine) Delete(bean interface{}) (int64, error)
- func (engine *Engine) Desc(colNames ...string) *Session
- func (engine *Engine) Dialect() dialects.Dialect
- func (engine *Engine) Distinct(columns ...string) *Session
- func (engine *Engine) DriverName() string
- func (engine *Engine) DropIndexes(bean interface{}) error
- func (engine *Engine) DropTables(beans ...interface{}) error
- func (engine *Engine) DumpAll(w io.Writer, tp ...schemas.DBType) error
- func (engine *Engine) DumpAllToFile(fp string, tp ...schemas.DBType) error
- func (engine *Engine) DumpTables(tables []*schemas.Table, w io.Writer, tp ...schemas.DBType) error
- func (engine *Engine) DumpTablesToFile(tables []*schemas.Table, fp string, tp ...schemas.DBType) error
- func (engine *Engine) EnableSessionID(enable bool)
- func (engine *Engine) Exec(sqlOrArgs ...interface{}) (sql.Result, error)
- func (engine *Engine) Exist(bean ...interface{}) (bool, error)
- func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error
- func (engine *Engine) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error)
- func (engine *Engine) Get(bean interface{}) (bool, error)
- func (engine *Engine) GetCacher(tableName string) caches.Cacher
- func (engine *Engine) GetColumnMapper() names.Mapper
- func (engine *Engine) GetDefaultCacher() caches.Cacher
- func (engine *Engine) GetFirst(bean interface{}) *ResultBean
- func (engine *Engine) GetSql(key string) string
- func (engine *Engine) GetSqlMap(keys ...interface{}) map[string]string
- func (engine *Engine) GetTZDatabase() *time.Location
- func (engine *Engine) GetTZLocation() *time.Location
- func (engine *Engine) GetTableMapper() names.Mapper
- func (engine *Engine) GroupBy(keys string) *Session
- func (engine *Engine) Having(conditions string) *Session
- func (engine *Engine) ID(id interface{}) *Session
- func (engine *Engine) Import(r io.Reader) ([]sql.Result, error)
- func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error)
- func (engine *Engine) In(column string, args ...interface{}) *Session
- func (engine *Engine) Incr(column string, args ...interface{}) *Session
- func (engine *Engine) Insert(beans ...interface{}) (int64, error)
- func (engine *Engine) InsertOne(bean interface{}) (int64, error)
- func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error)
- func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error)
- func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error
- func (engine *Engine) Join(joinOperator string, tablename interface{}, condition string, ...) *Session
- func (engine *Engine) Limit(limit int, start ...int) *Session
- func (engine *Engine) LoadSqlMap(filepath string) error
- func (engine *Engine) LoadSqlTemplate(filepath string) error
- func (engine *Engine) Logger() log.ContextLogger
- func (engine *Engine) MapCacher(bean interface{}, cacher caches.Cacher) error
- func (engine *Engine) MustCols(columns ...string) *Session
- func (engine *Engine) NewDB() (*core.DB, error)
- func (engine *Engine) NewSession() *Session
- func (engine *Engine) NoAutoCondition(no ...bool) *Session
- func (engine *Engine) NoAutoTime() *Session
- func (engine *Engine) NoCache() *Session
- func (engine *Engine) NoCascade() *Session
- func (engine *Engine) NotIn(column string, args ...interface{}) *Session
- func (engine *Engine) Nullable(columns ...string) *Session
- func (engine *Engine) Omit(columns ...string) *Session
- func (engine *Engine) OrderBy(order string) *Session
- func (engine *Engine) Ping() error
- func (engine *Engine) PingContext(ctx context.Context) error
- func (engine *Engine) Prepare() *Session
- func (engine *Engine) QueryBytes(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error)
- func (engine *Engine) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error)
- func (engine *Engine) QueryResult(sqlOrArgs ...interface{}) (result *ResultValue)
- func (engine *Engine) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error)
- func (engine *Engine) QueryValue(sqlOrArgs ...interface{}) (resultsSlice []map[string]Value, err error)
- func (engine *Engine) Quote(value string) string
- func (engine *Engine) QuoteTo(buf *strings.Builder, value string)
- func (engine *Engine) RegisterSqlMap(sqlm SqlM, Cipher ...Cipher) error
- func (engine *Engine) RegisterSqlTemplate(sqlt SqlTemplate, Cipher ...Cipher) error
- func (engine *Engine) ReloadSqlMap(filepath string) error
- func (engine *Engine) ReloadSqlTemplate(filepath string) error
- func (engine *Engine) RemoveSql(key string)
- func (engine *Engine) RemoveSqlTemplate(key string)
- func (engine *Engine) Rows(bean interface{}) (*Rows, error)
- func (engine *Engine) SQL(query interface{}, args ...interface{}) *Session
- func (engine *Engine) SQLType(c *schemas.Column) string
- func (engine *Engine) Search(beans interface{}, condiBeans ...interface{}) *ResultStructs
- func (engine *Engine) Select(str string) *Session
- func (engine *Engine) SetCacher(tableName string, cacher caches.Cacher)
- func (engine *Engine) SetColumnMapper(mapper names.Mapper)
- func (engine *Engine) SetConnMaxLifetime(d time.Duration)
- func (engine *Engine) SetDefaultCacher(cacher caches.Cacher)
- func (engine *Engine) SetDefaultContext(ctx context.Context)
- func (engine *Engine) SetDisableGlobalCache(disable bool)
- func (engine *Engine) SetExpr(column string, expression interface{}) *Session
- func (engine *Engine) SetLogLevel(level log.LogLevel)
- func (engine *Engine) SetLogger(logger interface{})
- func (engine *Engine) SetMapper(mapper names.Mapper)
- func (engine *Engine) SetMaxIdleConns(conns int)
- func (engine *Engine) SetMaxOpenConns(conns int)
- func (engine *Engine) SetQuotePolicy(quotePolicy dialects.QuotePolicy)
- func (engine *Engine) SetSchema(schema string)
- func (engine *Engine) SetSqlMapCipher(cipher Cipher)
- func (engine *Engine) SetSqlMapRootDir(sqlMapRootDir string) *Engine
- func (engine *Engine) SetTZDatabase(tz *time.Location)
- func (engine *Engine) SetTZLocation(tz *time.Location)
- func (engine *Engine) SetTableMapper(mapper names.Mapper)
- func (engine *Engine) ShowSQL(show ...bool)
- func (engine *Engine) SqlMapClient(sqlTagName string, args ...interface{}) *Session
- func (engine *Engine) SqlMapsClient(sqlkeys interface{}, parmas ...interface{}) *SqlMapsExecutor
- func (engine *Engine) SqlTemplateClient(sqlTagName string, args ...interface{}) *Session
- func (engine *Engine) SqlTemplatesClient(sqlkeys interface{}, parmas ...interface{}) *SqlTemplatesExecutor
- func (engine *Engine) Sqls(sqls interface{}, parmas ...interface{}) *SqlsExecutor
- func (engine *Engine) StartFSWatcher() error
- func (engine *Engine) StopFSWatcher() error
- func (engine *Engine) StoreEngine(storeEngine string) *Session
- func (engine *Engine) Sum(bean interface{}, colName string) (float64, error)
- func (engine *Engine) SumInt(bean interface{}, colName string) (int64, error)
- func (engine *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error)
- func (engine *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error)
- func (engine *Engine) Sync(beans ...interface{}) error
- func (engine *Engine) Sync2(beans ...interface{}) error
- func (engine *Engine) Table(tableNameOrBean interface{}) *Session
- func (engine *Engine) TableInfo(bean interface{}) (*schemas.Table, error)
- func (engine *Engine) TableName(bean interface{}, includeSchema ...bool) string
- func (engine *Engine) Transaction(f func(*Session) (interface{}, error)) (interface{}, error)
- func (engine *Engine) UnMapType(t reflect.Type)
- func (engine *Engine) Unscoped() *Session
- func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error)
- func (engine *Engine) UpdateSql(key string, sql string)
- func (engine *Engine) UpdateSqlTemplate(key string, sqlTemplateStr string) error
- func (engine *Engine) UseBool(columns ...string) *Session
- func (engine *Engine) Where(query interface{}, args ...interface{}) *Session
- type EngineGroup
- func (eg *EngineGroup) AddHook(hook contexts.Hook)
- func (eg *EngineGroup) Close() error
- func (eg *EngineGroup) Context(ctx context.Context) *Session
- func (eg *EngineGroup) Main() *Engine
- func (eg *EngineGroup) NewSession() *Session
- func (eg *EngineGroup) Ping() error
- func (eg *EngineGroup) RegisterSqlMap(sqlm SqlM, Cipher ...Cipher) error
- func (eg *EngineGroup) RegisterSqlTemplate(sqlt SqlTemplate, Cipher ...Cipher) error
- func (eg *EngineGroup) SetColumnMapper(mapper names.Mapper)
- func (eg *EngineGroup) SetConnMaxLifetime(d time.Duration)
- func (eg *EngineGroup) SetDefaultCacher(cacher caches.Cacher)
- func (eg *EngineGroup) SetLogLevel(level log.LogLevel)
- func (eg *EngineGroup) SetLogger(logger interface{})
- func (eg *EngineGroup) SetMapper(mapper names.Mapper)
- func (eg *EngineGroup) SetMaxIdleConns(conns int)
- func (eg *EngineGroup) SetMaxOpenConns(conns int)
- func (eg *EngineGroup) SetPolicy(policy GroupPolicy) *EngineGroup
- func (eg *EngineGroup) SetQuotePolicy(quotePolicy dialects.QuotePolicy)
- func (eg *EngineGroup) SetTableMapper(mapper names.Mapper)
- func (eg *EngineGroup) ShowSQL(show ...bool)
- func (eg *EngineGroup) Subordinate() *Engine
- func (eg *EngineGroup) Subordinates() []*Engine
- type EngineInterface
- type ErrFieldIsNotExist
- type ErrFieldIsNotValid
- type FuncMap
- type GroupPolicy
- type GroupPolicyHandler
- type HTMLTemplate
- func (sqlTemplate *HTMLTemplate) AddSqlTemplate(key string, sqlTemplateStr string) error
- func (sqlTemplate *HTMLTemplate) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
- func (sqlTemplate *HTMLTemplate) BatchLoadSqlTemplate(filepathSlice []string) error
- func (sqlTemplate *HTMLTemplate) BatchReloadSqlTemplate(filepathSlice []string) error
- func (sqlTemplate *HTMLTemplate) BatchRemoveSqlTemplate(key []string)
- func (sqlTemplate *HTMLTemplate) BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
- func (sqlTemplate *HTMLTemplate) Execute(key string, args ...interface{}) (string, error)
- func (sqlTemplate *HTMLTemplate) Extension() string
- func (sqlTemplate *HTMLTemplate) GetSqlTemplate(key string) *template.Template
- func (sqlTemplate *HTMLTemplate) GetSqlTemplates(keys ...interface{}) map[string]*template.Template
- func (sqlTemplate *HTMLTemplate) LoadSqlTemplate(filepath string) error
- func (sqlTemplate *HTMLTemplate) ReadTemplate(filepath string) ([]byte, error)
- func (sqlTemplate *HTMLTemplate) ReloadSqlTemplate(filepath string) error
- func (sqlTemplate *HTMLTemplate) RemoveSqlTemplate(key string)
- func (sqlTemplate *HTMLTemplate) RootDir() string
- func (sqlTemplate *HTMLTemplate) SetFuncs(key string, funcMap FuncMap)
- func (sqlTemplate *HTMLTemplate) SetSqlTemplateCipher(cipher Cipher)
- func (sqlTemplate *HTMLTemplate) UpdateSqlTemplate(key string, sqlTemplateStr string) error
- func (sqlTemplate *HTMLTemplate) WalkFunc(path string, info os.FileInfo, err error) error
- type Interface
- type IterFunc
- type JSONInterface
- type JetTemplate
- func (sqlTemplate *JetTemplate) AddSqlTemplate(key string, sqlTemplateStr string) error
- func (sqlTemplate *JetTemplate) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
- func (sqlTemplate *JetTemplate) BatchLoadSqlTemplate(filepathSlice []string) error
- func (sqlTemplate *JetTemplate) BatchReloadSqlTemplate(filepathSlice []string) error
- func (sqlTemplate *JetTemplate) BatchRemoveSqlTemplate(key []string)
- func (sqlTemplate *JetTemplate) BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
- func (sqlTemplate *JetTemplate) Execute(key string, args ...interface{}) (string, error)
- func (sqlTemplate *JetTemplate) Extension() string
- func (sqlTemplate *JetTemplate) GetSqlTemplate(key string) *jet.Template
- func (sqlTemplate *JetTemplate) GetSqlTemplates(keys ...interface{}) map[string]*jet.Template
- func (sqlTemplate *JetTemplate) LoadSqlTemplate(filepath string) error
- func (sqlTemplate *JetTemplate) ReadTemplate(filepath string) ([]byte, error)
- func (sqlTemplate *JetTemplate) ReloadSqlTemplate(filepath string) error
- func (sqlTemplate *JetTemplate) RemoveSqlTemplate(key string)
- func (sqlTemplate *JetTemplate) RootDir() string
- func (sqlTemplate *JetTemplate) SetFuncs(key string, funcMap FuncMap)
- func (sqlTemplate *JetTemplate) SetSqlTemplateCipher(cipher Cipher)
- func (sqlTemplate *JetTemplate) UpdateSqlTemplate(key string, sqlTemplateStr string) error
- func (sqlTemplate *JetTemplate) WalkFunc(path string, info os.FileInfo, err error) error
- type JsonSqlMap
- type NullBool
- func (nb NullBool) IsNil() bool
- func (nb NullBool) MarshalJSON() ([]byte, error)
- func (nb NullBool) MarshalText() ([]byte, error)
- func (nb NullBool) Ptr() *bool
- func (nb *NullBool) UnmarshalJSON(data []byte) error
- func (nb *NullBool) UnmarshalText(text []byte) error
- func (nb NullBool) ValueOrZero() bool
- type NullFloat32
- func (nf NullFloat32) IsNil() bool
- func (nf NullFloat32) MarshalJSON() ([]byte, error)
- func (nf NullFloat32) MarshalText() ([]byte, error)
- func (nf NullFloat32) Ptr() *float32
- func (nf *NullFloat32) UnmarshalJSON(data []byte) error
- func (nf *NullFloat32) UnmarshalText(text []byte) error
- func (nf NullFloat32) ValueOrZero() float32
- type NullFloat64
- func (nf NullFloat64) IsNil() bool
- func (nf NullFloat64) MarshalJSON() ([]byte, error)
- func (nf NullFloat64) MarshalText() ([]byte, error)
- func (nf NullFloat64) Ptr() *float64
- func (nf *NullFloat64) UnmarshalJSON(data []byte) error
- func (nf *NullFloat64) UnmarshalText(text []byte) error
- func (nf NullFloat64) ValueOrZero() float64
- type NullInt
- type NullInt16
- func (ni NullInt16) IsNil() bool
- func (ni NullInt16) MarshalJSON() ([]byte, error)
- func (ni NullInt16) MarshalText() ([]byte, error)
- func (ni NullInt16) Ptr() *int16
- func (ni *NullInt16) UnmarshalJSON(data []byte) error
- func (ni *NullInt16) UnmarshalText(text []byte) error
- func (ni NullInt16) ValueOrZero() int16
- type NullInt32
- func (ni NullInt32) IsNil() bool
- func (ni NullInt32) MarshalJSON() ([]byte, error)
- func (ni NullInt32) MarshalText() ([]byte, error)
- func (ni NullInt32) Ptr() *int32
- func (ni *NullInt32) UnmarshalJSON(data []byte) error
- func (ni *NullInt32) UnmarshalText(text []byte) error
- func (ni NullInt32) ValueOrZero() int32
- type NullInt64
- func (ni NullInt64) IsNil() bool
- func (ni NullInt64) MarshalJSON() ([]byte, error)
- func (ni NullInt64) MarshalText() ([]byte, error)
- func (ni NullInt64) Ptr() *int64
- func (ni *NullInt64) UnmarshalJSON(data []byte) error
- func (ni *NullInt64) UnmarshalText(text []byte) error
- func (ni NullInt64) ValueOrZero() int64
- type NullInt8
- func (ni NullInt8) IsNil() bool
- func (ni NullInt8) MarshalJSON() ([]byte, error)
- func (ni NullInt8) MarshalText() ([]byte, error)
- func (ni NullInt8) Ptr() *int8
- func (ni *NullInt8) UnmarshalJSON(data []byte) error
- func (ni *NullInt8) UnmarshalText(text []byte) error
- func (ni NullInt8) ValueOrZero() int8
- type NullString
- func (ns NullString) IsNil() bool
- func (ns NullString) MarshalJSON() ([]byte, error)
- func (ns NullString) MarshalText() ([]byte, error)
- func (ns NullString) Ptr() *string
- func (ns *NullString) UnmarshalJSON(data []byte) error
- func (ns *NullString) UnmarshalText(text []byte) error
- func (ns NullString) ValueOrZero() string
- type NullTime
- type NullType
- type NullUint
- func (nu NullUint) IsNil() bool
- func (ni NullUint) MarshalJSON() ([]byte, error)
- func (ni NullUint) MarshalText() ([]byte, error)
- func (nu NullUint) Ptr() *uint
- func (nu *NullUint) UnmarshalJSON(data []byte) error
- func (nu *NullUint) UnmarshalText(text []byte) error
- func (nu NullUint) ValueOrZero() uint
- type NullUint16
- func (nu NullUint16) IsNil() bool
- func (nu NullUint16) MarshalJSON() ([]byte, error)
- func (nu NullUint16) MarshalText() ([]byte, error)
- func (nu NullUint16) Ptr() *uint16
- func (nu *NullUint16) UnmarshalJSON(data []byte) error
- func (nu *NullUint16) UnmarshalText(text []byte) error
- func (nu NullUint16) ValueOrZero() uint16
- type NullUint32
- func (nu NullUint32) IsNil() bool
- func (nu NullUint32) MarshalJSON() ([]byte, error)
- func (nu NullUint32) MarshalText() ([]byte, error)
- func (nu NullUint32) Ptr() *uint32
- func (nu *NullUint32) UnmarshalJSON(data []byte) error
- func (nu *NullUint32) UnmarshalText(text []byte) error
- func (nu NullUint32) ValueOrZero() uint32
- type NullUint64
- func (nu NullUint64) IsNil() bool
- func (nu NullUint64) MarshalJSON() ([]byte, error)
- func (nu NullUint64) MarshalText() ([]byte, error)
- func (nu NullUint64) Ptr() *uint64
- func (nu *NullUint64) UnmarshalJSON(data []byte) error
- func (nu *NullUint64) UnmarshalText(text []byte) error
- func (nu NullUint64) ValueOrZero() uint64
- type NullUint8
- func (nu NullUint8) IsNil() bool
- func (nu NullUint8) MarshalJSON() ([]byte, error)
- func (nu NullUint8) MarshalText() ([]byte, error)
- func (nu NullUint8) Ptr() *uint8
- func (nu *NullUint8) UnmarshalJSON(data []byte) error
- func (nu *NullUint8) UnmarshalText(text []byte) error
- func (nu NullUint8) ValueOrZero() uint8
- type Pongo2Template
- func (sqlTemplate *Pongo2Template) AddSqlTemplate(key string, sqlTemplateStr string) error
- func (sqlTemplate *Pongo2Template) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
- func (sqlTemplate *Pongo2Template) BatchLoadSqlTemplate(filepathSlice []string) error
- func (sqlTemplate *Pongo2Template) BatchReloadSqlTemplate(filepathSlice []string) error
- func (sqlTemplate *Pongo2Template) BatchRemoveSqlTemplate(key []string)
- func (sqlTemplate *Pongo2Template) BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
- func (sqlTemplate *Pongo2Template) Execute(key string, args ...interface{}) (string, error)
- func (sqlTemplate *Pongo2Template) Extension() string
- func (sqlTemplate *Pongo2Template) GetSqlTemplate(key string) *pongo2.Template
- func (sqlTemplate *Pongo2Template) GetSqlTemplates(keys ...interface{}) map[string]*pongo2.Template
- func (sqlTemplate *Pongo2Template) LoadSqlTemplate(filepath string) error
- func (sqlTemplate *Pongo2Template) ReadTemplate(filepath string) ([]byte, error)
- func (sqlTemplate *Pongo2Template) ReloadSqlTemplate(filepath string) error
- func (sqlTemplate *Pongo2Template) RemoveSqlTemplate(key string)
- func (sqlTemplate *Pongo2Template) RootDir() string
- func (sqlTemplate *Pongo2Template) SetFuncs(key string, funcMap FuncMap)
- func (sqlTemplate *Pongo2Template) SetSqlTemplateCipher(cipher Cipher)
- func (sqlTemplate *Pongo2Template) UpdateSqlTemplate(key string, sqlTemplateStr string) error
- func (sqlTemplate *Pongo2Template) WalkFunc(path string, info os.FileInfo, err error) error
- type Record
- type Result
- type ResultBean
- type ResultMap
- func (resultMap *ResultMap) Count() (int, error)
- func (resultMap *ResultMap) Json() (string, error)
- func (resultMap *ResultMap) List() ([]map[string]interface{}, error)
- func (resultMap *ResultMap) ListPage(firstResult int, maxResults int) ([]map[string]interface{}, error)
- func (resultMap *ResultMap) SaveAsCSV(filename string, headers []string, perm os.FileMode) error
- func (resultMap *ResultMap) SaveAsHTML(filename string, headers []string, perm os.FileMode) error
- func (resultMap *ResultMap) SaveAsJSON(filename string, headers []string, perm os.FileMode) error
- func (resultMap *ResultMap) SaveAsTSV(filename string, headers []string, perm os.FileMode) error
- func (resultMap *ResultMap) SaveAsXLSX(filename string, headers []string, perm os.FileMode) error
- func (resultMap *ResultMap) SaveAsXML(filename string, headers []string, perm os.FileMode) error
- func (resultMap *ResultMap) SaveAsXMLWithTagNamePrefixIndent(tagName string, prifix string, indent string, filename string, ...) error
- func (resultMap *ResultMap) SaveAsYAML(filename string, headers []string, perm os.FileMode) error
- func (resultMap *ResultMap) Xml() (string, error)
- func (resultMap *ResultMap) XmlIndent(prefix string, indent string, recordTag string) (string, error)
- type ResultStructs
- type ResultValue
- type Rows
- type RsaEncrypt
- type Scanner
- type Session
- func (session *Session) After(closures func(interface{})) *Session
- func (session *Session) Alias(alias string) *Session
- func (session *Session) AllCols() *Session
- func (session *Session) And(query interface{}, args ...interface{}) *Session
- func (session *Session) Asc(colNames ...string) *Session
- func (session *Session) Before(closures func(interface{})) *Session
- func (session *Session) Begin() error
- func (session *Session) BeginTrans(transactionDefinition ...int) (*Transaction, error)
- func (session *Session) BufferSize(size int) *Session
- func (session *Session) Cascade(trueOrFalse ...bool) *Session
- func (session *Session) Charset(charset string) *Session
- func (session *Session) Close() error
- func (session *Session) Cols(columns ...string) *Session
- func (session *Session) Commit() error
- func (session *Session) Conds() builder.Cond
- func (session *Session) Context(ctx context.Context) *Session
- func (session *Session) ContextCache(context contexts.ContextCache) *Session
- func (session *Session) Count(bean ...interface{}) (int64, error)
- func (session *Session) CreateIndexes(bean interface{}) error
- func (session *Session) CreateTable(bean interface{}) error
- func (session *Session) CreateUniques(bean interface{}) error
- func (session *Session) DB() *core.DB
- func (session *Session) Decr(column string, arg ...interface{}) *Session
- func (session *Session) Delete(bean interface{}) (int64, error)
- func (session *Session) Desc(colNames ...string) *Session
- func (session *Session) Distinct(columns ...string) *Session
- func (session *Session) DropIndexes(bean interface{}) error
- func (session *Session) DropTable(beanOrTableName interface{}) error
- func (session *Session) Engine() *Engine
- func (session *Session) Exec(sqlOrArgs ...interface{}) (sql.Result, error)
- func (session *Session) Execute() (sql.Result, error)
- func (session *Session) Exist(bean ...interface{}) (bool, error)
- func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error
- func (session *Session) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error)
- func (session *Session) ForUpdate() *Session
- func (session *Session) Get(bean interface{}) (bool, error)
- func (session *Session) GetFirst(bean interface{}) *ResultBean
- func (session *Session) GroupBy(keys string) *Session
- func (session *Session) Having(conditions string) *Session
- func (session *Session) ID(id interface{}) *Session
- func (session *Session) Import(r io.Reader) ([]sql.Result, error)
- func (session *Session) ImportFile(ddlPath string) ([]sql.Result, error)
- func (session *Session) In(column string, args ...interface{}) *Session
- func (session *Session) Incr(column string, arg ...interface{}) *Session
- func (session *Session) Insert(beans ...interface{}) (int64, error)
- func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error)
- func (session *Session) InsertOne(bean interface{}) (int64, error)
- func (session *Session) IsClosed() bool
- func (session *Session) IsTableEmpty(bean interface{}) (bool, error)
- func (session *Session) IsTableExist(beanOrTableName interface{}) (bool, error)
- func (session *Session) Iterate(bean interface{}, fun IterFunc) error
- func (session *Session) Join(joinOperator string, tablename interface{}, condition string, ...) *Session
- func (session *Session) LastSQL() (string, []interface{})
- func (session *Session) Limit(limit int, start ...int) *Session
- func (session *Session) MustCols(columns ...string) *Session
- func (session *Session) MustLogSQL(logs ...bool) *Session
- func (session *Session) NoAutoCondition(no ...bool) *Session
- func (session *Session) NoAutoTime() *Session
- func (session *Session) NoCache() *Session
- func (session *Session) NoCascade() *Session
- func (session *Session) NotIn(column string, args ...interface{}) *Session
- func (session *Session) Nullable(columns ...string) *Session
- func (session *Session) Omit(columns ...string) *Session
- func (session *Session) Or(query interface{}, args ...interface{}) *Session
- func (session *Session) OrderBy(order string) *Session
- func (session *Session) Ping() error
- func (session *Session) PingContext(ctx context.Context) error
- func (session *Session) Prepare() *Session
- func (session *Session) Query() *ResultMap
- func (session *Session) QueryBytes(sqlOrArgs ...interface{}) ([]map[string][]byte, error)
- func (session *Session) QueryExpr(sqlOrArgs ...interface{}) sqlExpr
- func (session *Session) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error)
- func (session *Session) QueryResult(sqlOrArgs ...interface{}) *ResultValue
- func (session *Session) QueryRows(sqlOrArgs ...interface{}) (*core.Rows, error)
- func (session *Session) QuerySliceString(sqlOrArgs ...interface{}) ([][]string, error)
- func (session *Session) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error)
- func (session *Session) QueryValue(sqlOrArgs ...interface{}) ([]map[string]Value, error)
- func (session *Session) QueryWithDateFormat(dateFormat string) *ResultMap
- func (session *Session) Rollback() error
- func (session *Session) Rows(bean interface{}) (*Rows, error)
- func (session *Session) SQL(query interface{}, args ...interface{}) *Session
- func (session *Session) Search(rowsSlicePtr interface{}, condiBean ...interface{}) *ResultStructs
- func (session *Session) Select(str string) *Session
- func (session *Session) SetExpr(column string, expression interface{}) *Session
- func (session *Session) SqlMapClient(sqlTagName string, args ...interface{}) *Session
- func (session *Session) SqlMapsClient(sqlkeys interface{}, parmas ...interface{}) *SqlMapsExecutor
- func (session *Session) SqlTemplateClient(sqlTagName string, args ...interface{}) *Session
- func (session *Session) SqlTemplatesClient(sqlkeys interface{}, parmas ...interface{}) *SqlTemplatesExecutor
- func (session *Session) Sqls(sqls interface{}, parmas ...interface{}) *SqlsExecutor
- func (session *Session) StoreEngine(storeEngine string) *Session
- func (session *Session) Sum(bean interface{}, columnName string) (res float64, err error)
- func (session *Session) SumInt(bean interface{}, columnName string) (res int64, err error)
- func (session *Session) Sums(bean interface{}, columnNames ...string) ([]float64, error)
- func (session *Session) SumsInt(bean interface{}, columnNames ...string) ([]int64, error)
- func (session *Session) Sync2(beans ...interface{}) error
- func (session *Session) Table(tableNameOrBean interface{}) *Session
- func (session *Session) Unscoped() *Session
- func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error)
- func (session *Session) UseBool(columns ...string) *Session
- func (session *Session) Where(query interface{}, args ...interface{}) *Session
- type Sql
- type SqlM
- type SqlMap
- type SqlMapsExecutor
- type SqlTemplate
- type SqlTemplatesExecutor
- type SqlsExecutor
- type StdJSON
- type StringBuilder
- func (b *StringBuilder) Grow(n int)
- func (b *StringBuilder) Len() int
- func (b *StringBuilder) Reset()
- func (b *StringBuilder) String() string
- func (b *StringBuilder) Write(p []byte) (int, error)
- func (b *StringBuilder) WriteByte(c byte) error
- func (b *StringBuilder) WriteRune(r rune) (int, error)
- func (b *StringBuilder) WriteString(s string) (int, error)
- type Table
- type Transaction
- func (transaction *Transaction) BeginTrans() error
- func (transaction *Transaction) CommitTrans() error
- func (transaction *Transaction) Do(doFunc func(params ...interface{}), params ...interface{})
- func (transaction *Transaction) GetSavePointID() string
- func (transaction *Transaction) IsExistingTransaction() bool
- func (transaction *Transaction) RollbackToSavePoint(savePointID string) error
- func (transaction *Transaction) RollbackTrans() error
- func (transaction *Transaction) SavePoint(savePointID string) error
- func (transaction *Transaction) Session() *Session
- func (transaction *Transaction) TransactionDefinition() int
- func (transaction *Transaction) WaitForDo(doFunc func(params ...interface{}), params ...interface{})
- type TripleDesEncrypt
- type Value
- func (v Value) Bool() bool
- func (v Value) Bytes() []byte
- func (v Value) Float32() float32
- func (v Value) Float64() float64
- func (v Value) Int() int
- func (v Value) Int16() int16
- func (v Value) Int32() int32
- func (v Value) Int64() int64
- func (v Value) Int8() int8
- func (v Value) NullBool() NullBool
- func (v Value) NullFloat32() NullFloat32
- func (v Value) NullFloat64() NullFloat64
- func (v Value) NullInt() NullInt
- func (v Value) NullInt16() NullInt16
- func (v Value) NullInt32() NullInt32
- func (v Value) NullInt64() NullInt64
- func (v Value) NullInt8() NullInt8
- func (v Value) NullString() NullString
- func (v Value) NullTime(format string, TZLocation ...*time.Location) NullTime
- func (v Value) NullUint() NullUint
- func (v Value) NullUint16() NullUint16
- func (v Value) NullUint32() NullUint32
- func (v Value) NullUint64() NullUint64
- func (v Value) NullUint8() NullUint8
- func (v Value) String() string
- func (v Value) Time(format string, TZLocation ...*time.Location) time.Time
- func (v Value) TimeDuration() time.Duration
- func (v Value) Uint() uint
- func (v Value) Uint16() uint16
- func (v Value) Uint32() uint32
- func (v Value) Uint64() uint64
- func (v Value) Uint8() uint8
- type XSqlMap
- type XmlSql
- type XmlSqlMap
Constants ¶
const ( RSA_PUBKEY_ENCRYPT_MODE = iota //公钥加密 RSA_PUBKEY_DECRYPT_MODE //公钥解密 RSA_PRIKEY_ENCRYPT_MODE //私钥加密 RSA_PRIKEY_DECRYPT_MODE //私钥解密 )
const ( PROPAGATION_REQUIRED = 0 //Support a current transaction; create a new one if none exists. PROPAGATION_SUPPORTS = 1 //Support a current transaction; execute non-transactionally if none exists. PROPAGATION_MANDATORY = 2 //Support a current transaction; return an error if no current transaction exists. PROPAGATION_REQUIRES_NEW = 3 //Create a new transaction, suspending the current transaction if one exists. PROPAGATION_NOT_SUPPORTED = 4 //Do not support a current transaction; rather always execute non-transactionally. PROPAGATION_NEVER = 5 //Do not support a current transaction; return an error if a current transaction exists. PROPAGATION_NESTED = 6 //Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else. PROPAGATION_NOT_REQUIRED = 7 )
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 = "godror" SQLITE3_DRIVER string = "sqlite3" KINGBASE string = "kingbase" )
const ( // Version show the xorm's version Version string = "1.0.5.0912" )
Variables ¶
var ( ErrDataToLarge = errors.New("message too long for RSA public key size") ErrDataLen = errors.New("data length error") ErrDataBroken = errors.New("data broken, first byte is not zero") ErrKeyPairDismatch = errors.New("data is not encrypted by the private key") ErrDecryption = errors.New("decryption error") ErrPublicKey = errors.New("get public key error") ErrPrivateKey = errors.New("get private key error") )
var ( // ErrPtrSliceType represents a type error ErrPtrSliceType = errors.New("A point to a slice is needed") // ErrParamsType params error ErrParamsType = errors.New("Params type error") ErrParamsFormat = errors.New("Params format error") // ErrTableNotFound table not found error ErrTableNotFound = errors.New("Table not found") // ErrUnSupportedType unsupported error ErrUnSupportedType = errors.New("Unsupported type error") // ErrNotExist record does not exist error ErrNotExist = errors.New("Record does not exist") ErrNotInTransaction = errors.New("Not in transaction.") ErrNestedTransaction = errors.New("Nested transaction error.") ErrTransactionDefinition = errors.New("Transaction definition error.") // ErrCacheFailed cache failed error ErrCacheFailed = errors.New("Cache failed") // ErrNeedDeletedCond delete needs less one condition error ErrNeedDeletedCond = errors.New("Delete action needs at least one condition") // ErrNotImplemented not implemented ErrNotImplemented = errors.New("Not implemented") // ErrConditionType condition type unsupported ErrConditionType = errors.New("Unsupported condition type") // ErrNeedMoreArguments need more arguments ErrNeedMoreArguments = errors.New("Need more sql arguments") // ErrUnSupportedSQLType parameter of SQL is not supported ErrUnSupportedSQLType = errors.New("Unsupported sql type") )
var ErrNoElementsOnSlice = errors.New("No element on slice when insert")
ErrNoElementsOnSlice represents an error there is no element when insert
Functions ¶
func ConvertToBoundSQL ¶
ConvertToBoundSQL will convert SQL and args to a bound SQL
func DecodeToString ¶
func EncodeBool ¶
func EncodeFloat32 ¶
func EncodeFloat64 ¶
func EncodeInt16 ¶
func EncodeInt32 ¶
func EncodeInt64 ¶
func EncodeInt8 ¶
func EncodeString ¶
func EncodeUint ¶
func EncodeUint16 ¶
func EncodeUint32 ¶
func EncodeUint64 ¶
func EncodeUint8 ¶
func JSONString ¶
func NewDataset ¶
NewDataset creates a new Dataset.
func NewDatasetWithData ¶
func NewDatasetWithData(headers []string, data interface{}, mustMatch bool) (*tablib.Dataset, error)
NewDatasetWithData creates a new Dataset.
func NewMemoryContextCache ¶
func NewMemoryContextCache() memoryContextCache
NewMemoryContextCache return memoryContextCache
func PKCS5Padding ¶
func PKCS5UnPadding ¶
func TimeDuration ¶
func ZeroPadding ¶
func ZeroUnPadding ¶
Types ¶
type AesEncrypt ¶
type AesEncrypt struct {
PubKey string
}
type AfterDeleteProcessor ¶
type AfterDeleteProcessor interface {
AfterDelete()
}
AfterDeleteProcessor executed after an object has been deleted
type AfterInsertProcessor ¶
type AfterInsertProcessor interface {
AfterInsert()
}
AfterInsertProcessor executed after an object is persisted to the database
type AfterLoadProcessor ¶
type AfterLoadProcessor interface {
AfterLoad()
}
AfterLoadProcessor executed after an ojbect has been loaded from database
type AfterLoadSessionProcessor ¶
type AfterLoadSessionProcessor interface {
AfterLoad(*Session)
}
AfterLoadSessionProcessor executed after an ojbect has been loaded from database with session parameter
type AfterSetProcessor ¶
AfterSetProcessor executed after data set to the struct fields
type AfterUpdateProcessor ¶
type AfterUpdateProcessor interface {
AfterUpdate()
}
AfterUpdateProcessor executed after an object has been updated
type BeforeDeleteProcessor ¶
type BeforeDeleteProcessor interface {
BeforeDelete()
}
BeforeDeleteProcessor executed before an object is deleted
type BeforeInsertProcessor ¶
type BeforeInsertProcessor interface {
BeforeInsert()
}
BeforeInsertProcessor executed before an object is initially persisted to the database
type BeforeSetProcessor ¶
BeforeSetProcessor executed before data set to the struct fields
type BeforeUpdateProcessor ¶
type BeforeUpdateProcessor interface {
BeforeUpdate()
}
BeforeUpdateProcessor executed before an object is updated
type ContextCache ¶
type ContextCache interface { // Put puts value into cache with key. Put(key string, val interface{}) // Get gets cached value by given key. Get(key string) interface{} }
ContextCache is the interface that operates the cache data.
type Databook ¶
func NewDatabook ¶
func NewDatabook() *Databook
func NewDatabookWithData ¶
func (*Databook) HTML ¶
func (databook *Databook) HTML() *tablib.Exportable
func (*Databook) SaveAsHTML ¶
func (*Databook) SaveAsJSON ¶
func (*Databook) SaveAsXLSX ¶
func (*Databook) SaveAsYAML ¶
type DesEncrypt ¶
type DesEncrypt struct {
PubKey string
}
type Engine ¶
type Engine struct { SqlMap SqlMap SqlTemplate SqlTemplate TZLocation *time.Location // The timezone of the application DatabaseTZ *time.Location // The timezone of the database // 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 NewEngine ¶
NewEngine new a db manager according to the parameter. Currently support four drivers
func NewEngineWithDialectAndDB ¶
func NewEngineWithDialectAndDB(driverName, dataSourceName string, dialect dialects.Dialect, db *core.DB) (*Engine, error)
NewEngineWithDialectAndDB new a db manager according to the parameter. If you do not want to use your own dialect or db, please use NewEngine. For creating dialect, you can call dialects.OpenDialect. And, for creating db, you can call core.Open or core.FromDB.
func NewEngineWithParams ¶
func NewEngineWithParams(driverName string, dataSourceName string, params map[string]string) (*Engine, error)
NewEngineWithParams new a db manager with params. The params will be passed to dialects.
func NewPostgreSQL ¶
func NewSqlite3 ¶
func (*Engine) AddSqlTemplate ¶
func (*Engine) Asc ¶
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 ¶
AutoIncrStr Database's autoincrement statement
func (*Engine) BatchAddSql ¶
func (*Engine) BatchAddSqlTemplate ¶
func (*Engine) BatchLoadSqlMap ¶
func (*Engine) BatchLoadSqlTemplate ¶
func (*Engine) BatchReloadSqlMap ¶
func (*Engine) BatchReloadSqlTemplate ¶
func (*Engine) BatchRemoveSql ¶
func (*Engine) BatchRemoveSqlTemplate ¶
func (*Engine) BatchUpdateSql ¶
func (*Engine) BatchUpdateSqlTemplate ¶
func (*Engine) BufferSize ¶
BufferSize sets buffer size for iterate
func (*Engine) ClearCache ¶
ClearCache if enabled cache, clear some tables' cache
func (*Engine) ClearCacheBean ¶
ClearCacheBean if enabled cache, clear the cache bean
func (*Engine) ClearSqlMapCipher ¶
func (engine *Engine) ClearSqlMapCipher()
func (*Engine) CreateIndexes ¶
CreateIndexes create indexes
func (*Engine) CreateTables ¶
CreateTables create tabls according bean
func (*Engine) CreateUniques ¶
CreateUniques create uniques
func (*Engine) DataSourceName ¶
DataSourceName return the current connection string
func (*Engine) Distinct ¶
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 (*Engine) DriverName ¶
DriverName return the current sql driver's name
func (*Engine) DropIndexes ¶
DropIndexes drop indexes of a table
func (*Engine) DropTables ¶
DropTables drop specify tables
func (*Engine) DumpAllToFile ¶
DumpAllToFile dump database all table structs and data to a file
func (*Engine) DumpTables ¶
DumpTables dump specify tables to io.Writer
func (*Engine) DumpTablesToFile ¶
func (engine *Engine) DumpTablesToFile(tables []*schemas.Table, fp string, tp ...schemas.DBType) error
DumpTablesToFile dump specified tables to SQL file.
func (*Engine) EnableSessionID ¶
EnableSessionID if enable session id
func (*Engine) Find ¶
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) FindAndCount ¶
func (engine *Engine) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error)
FindAndCount find the results and also return the counts
func (*Engine) GetColumnMapper ¶
GetColumnMapper returns the column name mapper
func (*Engine) GetDefaultCacher ¶
GetDefaultCacher returns the default cacher
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) GetTZDatabase ¶
GetTZDatabase returns time zone of the database
func (*Engine) GetTZLocation ¶
GetTZLocation returns time zone of the application
func (*Engine) GetTableMapper ¶
GetTableMapper returns the table name mapper
func (*Engine) ImportFile ¶
ImportFile SQL DDL file
func (*Engine) IsTableEmpty ¶
IsTableEmpty if a table has any reocrd
func (*Engine) IsTableExist ¶
IsTableExist if a table is exist
func (*Engine) Iterate ¶
Iterate record by record handle records from table, bean's non-empty fields are conditions.
func (*Engine) Join ¶
func (engine *Engine) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session
Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
func (*Engine) LoadSqlMap ¶
func (*Engine) LoadSqlTemplate ¶
func (*Engine) Logger ¶
func (engine *Engine) Logger() log.ContextLogger
Logger return the logger interface
func (*Engine) NoAutoCondition ¶
NoAutoCondition disable auto generate Where condition from bean or not
func (*Engine) NoAutoTime ¶
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 ¶
NoCache If you has set default cacher, and you want temporilly stop use cache, you can use NoCache()
func (*Engine) PingContext ¶
PingContext tests if database is alive
func (*Engine) QueryBytes ¶
func (engine *Engine) QueryBytes(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error)
Query a raw sql and return records as []map[string][]byte
func (*Engine) QueryInterface ¶
QueryInterface runs a raw sql and return records as []map[string]interface{}
func (*Engine) QueryResult ¶
func (engine *Engine) QueryResult(sqlOrArgs ...interface{}) (result *ResultValue)
Query a raw sql and return records as Result
func (*Engine) QueryString ¶
QueryString runs a raw sql and return records as []map[string]string
func (*Engine) QueryValue ¶
func (engine *Engine) QueryValue(sqlOrArgs ...interface{}) (resultsSlice []map[string]Value, err error)
Query a raw sql and return records as []map[string]Value
func (*Engine) RegisterSqlMap ¶
func (*Engine) RegisterSqlTemplate ¶
func (engine *Engine) RegisterSqlTemplate(sqlt SqlTemplate, Cipher ...Cipher) error
func (*Engine) ReloadSqlMap ¶
func (*Engine) ReloadSqlTemplate ¶
func (*Engine) RemoveSqlTemplate ¶
func (*Engine) Rows ¶
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 (*Engine) SQL ¶
SQL method let's you manually 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) Search ¶
func (engine *Engine) Search(beans interface{}, condiBeans ...interface{}) *ResultStructs
func (*Engine) SetColumnMapper ¶
SetColumnMapper set the column name mapping rule
func (*Engine) SetConnMaxLifetime ¶
SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
func (*Engine) SetDefaultCacher ¶
SetDefaultCacher set the default cacher. Xorm's default not enable cacher.
func (*Engine) SetDefaultContext ¶
SetDefaultContext set the default context
func (*Engine) SetDisableGlobalCache ¶
SetDisableGlobalCache disable global cache or not
func (*Engine) SetLogLevel ¶
SetLogLevel sets the logger level
func (*Engine) SetLogger ¶
func (engine *Engine) SetLogger(logger interface{})
SetLogger set the new logger
func (*Engine) SetMaxIdleConns ¶
SetMaxIdleConns set the max idle connections on pool, default is 2
func (*Engine) SetMaxOpenConns ¶
SetMaxOpenConns is only available for go 1.2+
func (*Engine) SetQuotePolicy ¶
func (engine *Engine) SetQuotePolicy(quotePolicy dialects.QuotePolicy)
SetQuotePolicy sets the special quote policy
func (*Engine) SetSqlMapCipher ¶
func (*Engine) SetSqlMapRootDir ¶
func (*Engine) SetTZDatabase ¶
SetTZDatabase sets time zone of the database
func (*Engine) SetTZLocation ¶
SetTZLocation sets time zone of the application
func (*Engine) SetTableMapper ¶
SetTableMapper set the table name mapping rule
func (*Engine) ShowSQL ¶
ShowSQL show SQL statement or not on logger if log level is great than INFO
func (*Engine) SqlMapClient ¶
func (*Engine) SqlMapsClient ¶
func (engine *Engine) SqlMapsClient(sqlkeys interface{}, parmas ...interface{}) *SqlMapsExecutor
func (*Engine) SqlTemplateClient ¶
func (*Engine) SqlTemplatesClient ¶
func (engine *Engine) SqlTemplatesClient(sqlkeys interface{}, parmas ...interface{}) *SqlTemplatesExecutor
func (*Engine) Sqls ¶
func (engine *Engine) Sqls(sqls interface{}, parmas ...interface{}) *SqlsExecutor
func (*Engine) StartFSWatcher ¶
start filesystem watcher
func (*Engine) StoreEngine ¶
StoreEngine set store engine when create table, only support mysql now
func (*Engine) SumInt ¶
SumInt sum the records by some column. bean's non-empty fields are conditions.
func (*Engine) Sync ¶
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) Transaction ¶
Transaction Execute sql wrapped in a transaction(abbr as tx), tx will automatic commit if no errors occurred
func (*Engine) Update ¶
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) UpdateSqlTemplate ¶
type EngineGroup ¶
type EngineGroup struct { *Engine // contains filtered or unexported fields }
EngineGroup defines an engine group
func NewEngineGroup ¶
func NewEngineGroup(args1 interface{}, args2 interface{}, policies ...GroupPolicy) (*EngineGroup, error)
NewEngineGroup creates a new engine group
func (*EngineGroup) AddHook ¶
func (eg *EngineGroup) AddHook(hook contexts.Hook)
func (*EngineGroup) Context ¶
func (eg *EngineGroup) Context(ctx context.Context) *Session
ContextHook returned a group session
func (*EngineGroup) NewSession ¶
func (eg *EngineGroup) NewSession() *Session
NewSession returned a group session
func (*EngineGroup) RegisterSqlMap ¶
func (eg *EngineGroup) RegisterSqlMap(sqlm SqlM, Cipher ...Cipher) error
func (*EngineGroup) RegisterSqlTemplate ¶
func (eg *EngineGroup) RegisterSqlTemplate(sqlt SqlTemplate, Cipher ...Cipher) error
func (*EngineGroup) SetColumnMapper ¶
func (eg *EngineGroup) SetColumnMapper(mapper names.Mapper)
SetColumnMapper set the column name mapping rule
func (*EngineGroup) SetConnMaxLifetime ¶
func (eg *EngineGroup) SetConnMaxLifetime(d time.Duration)
SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
func (*EngineGroup) SetDefaultCacher ¶
func (eg *EngineGroup) SetDefaultCacher(cacher caches.Cacher)
SetDefaultCacher set the default cacher
func (*EngineGroup) SetLogLevel ¶
func (eg *EngineGroup) SetLogLevel(level log.LogLevel)
SetLogLevel sets the logger level
func (*EngineGroup) SetLogger ¶
func (eg *EngineGroup) SetLogger(logger interface{})
SetLogger set the new logger
func (*EngineGroup) SetMapper ¶
func (eg *EngineGroup) SetMapper(mapper names.Mapper)
SetMapper set the name mapping rules
func (*EngineGroup) SetMaxIdleConns ¶
func (eg *EngineGroup) SetMaxIdleConns(conns int)
SetMaxIdleConns set the max idle connections on pool, default is 2
func (*EngineGroup) SetMaxOpenConns ¶
func (eg *EngineGroup) SetMaxOpenConns(conns int)
SetMaxOpenConns is only available for go 1.2+
func (*EngineGroup) SetPolicy ¶
func (eg *EngineGroup) SetPolicy(policy GroupPolicy) *EngineGroup
SetPolicy set the group policy
func (*EngineGroup) SetQuotePolicy ¶
func (eg *EngineGroup) SetQuotePolicy(quotePolicy dialects.QuotePolicy)
SetQuotePolicy sets the special quote policy
func (*EngineGroup) SetTableMapper ¶
func (eg *EngineGroup) SetTableMapper(mapper names.Mapper)
SetTableMapper set the table name mapping rule
func (*EngineGroup) ShowSQL ¶
func (eg *EngineGroup) ShowSQL(show ...bool)
ShowSQL show SQL statement or not on logger if log level is great than INFO
func (*EngineGroup) Subordinate ¶
func (eg *EngineGroup) Subordinate() *Engine
Subordinate returns one of the physical databases which is a subordinate according the policy
func (*EngineGroup) Subordinates ¶
func (eg *EngineGroup) Subordinates() []*Engine
Subordinates returns all the subordinates
type EngineInterface ¶
type EngineInterface interface { Interface Before(func(interface{})) *Session Charset(charset string) *Session ClearCache(...interface{}) error Context(context.Context) *Session CreateTables(...interface{}) error DBMetas() ([]*schemas.Table, error) Dialect() dialects.Dialect DriverName() string DropTables(...interface{}) error DumpAllToFile(fp string, tp ...schemas.DBType) error GetCacher(string) caches.Cacher GetColumnMapper() names.Mapper GetDefaultCacher() caches.Cacher GetTableMapper() names.Mapper GetTZDatabase() *time.Location GetTZLocation() *time.Location ImportFile(fp string) ([]sql.Result, error) MapCacher(interface{}, caches.Cacher) error NewSession() *Session NoAutoTime() *Session Quote(string) string SetCacher(string, caches.Cacher) SetConnMaxLifetime(time.Duration) SetColumnMapper(names.Mapper) SetDefaultCacher(caches.Cacher) SetLogger(logger interface{}) SetLogLevel(log.LogLevel) SetMapper(names.Mapper) SetMaxOpenConns(int) SetMaxIdleConns(int) SetQuotePolicy(dialects.QuotePolicy) SetSchema(string) SetTableMapper(names.Mapper) SetTZDatabase(tz *time.Location) SetTZLocation(tz *time.Location) AddHook(hook contexts.Hook) ShowSQL(show ...bool) Sync(...interface{}) error Sync2(...interface{}) error StoreEngine(storeEngine string) *Session TableInfo(bean interface{}) (*schemas.Table, error) TableName(interface{}, ...bool) string UnMapType(reflect.Type) EnableSessionID(bool) }
EngineInterface defines the interface which Engine, EngineGroup will implementate.
type ErrFieldIsNotExist ¶
ErrFieldIsNotExist columns does not exist
func (ErrFieldIsNotExist) Error ¶
func (e ErrFieldIsNotExist) Error() string
type ErrFieldIsNotValid ¶
ErrFieldIsNotValid is not valid
func (ErrFieldIsNotValid) Error ¶
func (e ErrFieldIsNotValid) Error() string
type GroupPolicy ¶
type GroupPolicy interface {
Subordinate(*EngineGroup) *Engine
}
GroupPolicy is be used by chosing the current subordinate from subordinates
type GroupPolicyHandler ¶
type GroupPolicyHandler func(*EngineGroup) *Engine
GroupPolicyHandler should be used when a function is a GroupPolicy
func LeastConnPolicy ¶
func LeastConnPolicy() GroupPolicyHandler
LeastConnPolicy implements GroupPolicy, every time will get the least connections subordinate
func RandomPolicy ¶
func RandomPolicy() GroupPolicyHandler
RandomPolicy implmentes randomly chose the subordinate of subordinates
func RoundRobinPolicy ¶
func RoundRobinPolicy() GroupPolicyHandler
RoundRobinPolicy returns a group policy handler
func WeightRandomPolicy ¶
func WeightRandomPolicy(weights []int) GroupPolicyHandler
WeightRandomPolicy implmentes randomly chose the subordinate of subordinates
func WeightRoundRobinPolicy ¶
func WeightRoundRobinPolicy(weights []int) GroupPolicyHandler
WeightRoundRobinPolicy returns a group policy handler
func (GroupPolicyHandler) Subordinate ¶
func (h GroupPolicyHandler) Subordinate(eg *EngineGroup) *Engine
Subordinate implements the chosen of subordinates
type HTMLTemplate ¶
type HTMLTemplate struct { SqlTemplateRootDir string Template map[string]*template.Template Capacity uint Cipher Cipher Type int Funcs map[string]FuncMap // contains filtered or unexported fields }
func Default ¶
func Default(directory, extension string) *HTMLTemplate
func (*HTMLTemplate) AddSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) AddSqlTemplate(key string, sqlTemplateStr string) error
func (*HTMLTemplate) BatchAddSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
func (*HTMLTemplate) BatchLoadSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) BatchLoadSqlTemplate(filepathSlice []string) error
func (*HTMLTemplate) BatchReloadSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) BatchReloadSqlTemplate(filepathSlice []string) error
func (*HTMLTemplate) BatchRemoveSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) BatchRemoveSqlTemplate(key []string)
func (*HTMLTemplate) BatchUpdateSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
func (*HTMLTemplate) Execute ¶
func (sqlTemplate *HTMLTemplate) Execute(key string, args ...interface{}) (string, error)
func (*HTMLTemplate) Extension ¶
func (sqlTemplate *HTMLTemplate) Extension() string
func (*HTMLTemplate) GetSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) GetSqlTemplate(key string) *template.Template
func (*HTMLTemplate) GetSqlTemplates ¶
func (sqlTemplate *HTMLTemplate) GetSqlTemplates(keys ...interface{}) map[string]*template.Template
func (*HTMLTemplate) LoadSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) LoadSqlTemplate(filepath string) error
-------------------------------------------------------------------------------------------------------------
func (*HTMLTemplate) ReadTemplate ¶
func (sqlTemplate *HTMLTemplate) ReadTemplate(filepath string) ([]byte, error)
func (*HTMLTemplate) ReloadSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) ReloadSqlTemplate(filepath string) error
func (*HTMLTemplate) RemoveSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) RemoveSqlTemplate(key string)
func (*HTMLTemplate) RootDir ¶
func (sqlTemplate *HTMLTemplate) RootDir() string
func (*HTMLTemplate) SetFuncs ¶
func (sqlTemplate *HTMLTemplate) SetFuncs(key string, funcMap FuncMap)
func (*HTMLTemplate) SetSqlTemplateCipher ¶
func (sqlTemplate *HTMLTemplate) SetSqlTemplateCipher(cipher Cipher)
func (*HTMLTemplate) UpdateSqlTemplate ¶
func (sqlTemplate *HTMLTemplate) UpdateSqlTemplate(key string, sqlTemplateStr string) error
type Interface ¶
type Interface interface { AllCols() *Session Alias(alias string) *Session Asc(colNames ...string) *Session BufferSize(size int) *Session Cols(columns ...string) *Session Count(...interface{}) (int64, error) CreateIndexes(bean interface{}) error CreateUniques(bean interface{}) error Decr(column string, arg ...interface{}) *Session Desc(...string) *Session Delete(interface{}) (int64, error) Distinct(columns ...string) *Session DropIndexes(bean interface{}) error Exec(sqlOrArgs ...interface{}) (sql.Result, error) Exist(bean ...interface{}) (bool, error) Find(interface{}, ...interface{}) error FindAndCount(interface{}, ...interface{}) (int64, error) Get(interface{}) (bool, error) GroupBy(keys string) *Session ID(interface{}) *Session In(string, ...interface{}) *Session Incr(column string, arg ...interface{}) *Session Insert(...interface{}) (int64, error) InsertOne(interface{}) (int64, error) IsTableEmpty(bean interface{}) (bool, error) IsTableExist(beanOrTableName interface{}) (bool, error) Iterate(interface{}, IterFunc) error Limit(int, ...int) *Session MustCols(columns ...string) *Session NoAutoCondition(...bool) *Session NotIn(string, ...interface{}) *Session Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session Omit(columns ...string) *Session OrderBy(order string) *Session Ping() error QueryBytes(sqlOrArgs ...interface{}) (resultsSlice []map[string][]byte, err error) QueryInterface(sqlOrArgs ...interface{}) ([]map[string]interface{}, error) QueryString(sqlOrArgs ...interface{}) ([]map[string]string, error) QueryValue(sqlOrArgs ...interface{}) ([]map[string]Value, error) QueryResult(sqlOrArgs ...interface{}) (result *ResultValue) Rows(bean interface{}) (*Rows, error) SetExpr(string, interface{}) *Session Select(string) *Session SQL(interface{}, ...interface{}) *Session Sum(bean interface{}, colName string) (float64, error) SumInt(bean interface{}, colName string) (int64, error) Sums(bean interface{}, colNames ...string) ([]float64, error) SumsInt(bean interface{}, colNames ...string) ([]int64, error) Table(tableNameOrBean interface{}) *Session Unscoped() *Session Update(bean interface{}, condiBeans ...interface{}) (int64, error) UseBool(...string) *Session Where(interface{}, ...interface{}) *Session }
Interface defines the interface which Engine, EngineGroup and Session will implementate.
type JSONInterface ¶
type JSONInterface interface { Marshal(v interface{}) ([]byte, error) Unmarshal(data []byte, v interface{}) error }
JSONInterface represents an interface to handle json data
var ( // DefaultJSONHandler default json handler DefaultJSONHandler JSONInterface = StdJSON{} )
type JetTemplate ¶
type JetTemplate struct { SqlTemplateRootDir string Template map[string]*jet.Template Capacity uint Cipher Cipher Funcs map[string]FuncMap // contains filtered or unexported fields }
func Jet ¶
func Jet(directory, extension string) *JetTemplate
func (*JetTemplate) AddSqlTemplate ¶
func (sqlTemplate *JetTemplate) AddSqlTemplate(key string, sqlTemplateStr string) error
func (*JetTemplate) BatchAddSqlTemplate ¶
func (sqlTemplate *JetTemplate) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
func (*JetTemplate) BatchLoadSqlTemplate ¶
func (sqlTemplate *JetTemplate) BatchLoadSqlTemplate(filepathSlice []string) error
func (*JetTemplate) BatchReloadSqlTemplate ¶
func (sqlTemplate *JetTemplate) BatchReloadSqlTemplate(filepathSlice []string) error
func (*JetTemplate) BatchRemoveSqlTemplate ¶
func (sqlTemplate *JetTemplate) BatchRemoveSqlTemplate(key []string)
func (*JetTemplate) BatchUpdateSqlTemplate ¶
func (sqlTemplate *JetTemplate) BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
func (*JetTemplate) Execute ¶
func (sqlTemplate *JetTemplate) Execute(key string, args ...interface{}) (string, error)
func (*JetTemplate) Extension ¶
func (sqlTemplate *JetTemplate) Extension() string
func (*JetTemplate) GetSqlTemplate ¶
func (sqlTemplate *JetTemplate) GetSqlTemplate(key string) *jet.Template
func (*JetTemplate) GetSqlTemplates ¶
func (sqlTemplate *JetTemplate) GetSqlTemplates(keys ...interface{}) map[string]*jet.Template
func (*JetTemplate) LoadSqlTemplate ¶
func (sqlTemplate *JetTemplate) LoadSqlTemplate(filepath string) error
-------------------------------------------------------------------------------------------------------------
func (*JetTemplate) ReadTemplate ¶
func (sqlTemplate *JetTemplate) ReadTemplate(filepath string) ([]byte, error)
func (*JetTemplate) ReloadSqlTemplate ¶
func (sqlTemplate *JetTemplate) ReloadSqlTemplate(filepath string) error
func (*JetTemplate) RemoveSqlTemplate ¶
func (sqlTemplate *JetTemplate) RemoveSqlTemplate(key string)
func (*JetTemplate) RootDir ¶
func (sqlTemplate *JetTemplate) RootDir() string
func (*JetTemplate) SetFuncs ¶
func (sqlTemplate *JetTemplate) SetFuncs(key string, funcMap FuncMap)
func (*JetTemplate) SetSqlTemplateCipher ¶
func (sqlTemplate *JetTemplate) SetSqlTemplateCipher(cipher Cipher)
func (*JetTemplate) UpdateSqlTemplate ¶
func (sqlTemplate *JetTemplate) UpdateSqlTemplate(key string, sqlTemplateStr string) error
type JsonSqlMap ¶
type JsonSqlMap struct {
// contains filtered or unexported fields
}
func Json ¶
func Json(directory, extension string) *JsonSqlMap
func (*JsonSqlMap) Extension ¶
func (sqlMap *JsonSqlMap) Extension() string
func (*JsonSqlMap) RootDir ¶
func (sqlMap *JsonSqlMap) RootDir() string
type NullBool ¶
func (NullBool) MarshalJSON ¶
func (NullBool) MarshalText ¶
func (*NullBool) UnmarshalJSON ¶
func (*NullBool) UnmarshalText ¶
func (NullBool) ValueOrZero ¶
type NullFloat32 ¶
func (NullFloat32) IsNil ¶
func (nf NullFloat32) IsNil() bool
func (NullFloat32) MarshalJSON ¶
func (nf NullFloat32) MarshalJSON() ([]byte, error)
func (NullFloat32) MarshalText ¶
func (nf NullFloat32) MarshalText() ([]byte, error)
func (NullFloat32) Ptr ¶
func (nf NullFloat32) Ptr() *float32
func (*NullFloat32) UnmarshalJSON ¶
func (nf *NullFloat32) UnmarshalJSON(data []byte) error
func (*NullFloat32) UnmarshalText ¶
func (nf *NullFloat32) UnmarshalText(text []byte) error
func (NullFloat32) ValueOrZero ¶
func (nf NullFloat32) ValueOrZero() float32
type NullFloat64 ¶
func (NullFloat64) IsNil ¶
func (nf NullFloat64) IsNil() bool
func (NullFloat64) MarshalJSON ¶
func (nf NullFloat64) MarshalJSON() ([]byte, error)
func (NullFloat64) MarshalText ¶
func (nf NullFloat64) MarshalText() ([]byte, error)
func (NullFloat64) Ptr ¶
func (nf NullFloat64) Ptr() *float64
func (*NullFloat64) UnmarshalJSON ¶
func (nf *NullFloat64) UnmarshalJSON(data []byte) error
func (*NullFloat64) UnmarshalText ¶
func (nf *NullFloat64) UnmarshalText(text []byte) error
func (NullFloat64) ValueOrZero ¶
func (nf NullFloat64) ValueOrZero() float64
type NullInt ¶
func (NullInt) MarshalJSON ¶
func (NullInt) MarshalText ¶
func (*NullInt) UnmarshalJSON ¶
func (*NullInt) UnmarshalText ¶
func (NullInt) ValueOrZero ¶
type NullInt16 ¶
func (NullInt16) MarshalJSON ¶
func (NullInt16) MarshalText ¶
func (*NullInt16) UnmarshalJSON ¶
func (*NullInt16) UnmarshalText ¶
func (NullInt16) ValueOrZero ¶
type NullInt32 ¶
func (NullInt32) MarshalJSON ¶
func (NullInt32) MarshalText ¶
func (*NullInt32) UnmarshalJSON ¶
func (*NullInt32) UnmarshalText ¶
func (NullInt32) ValueOrZero ¶
type NullInt64 ¶
func (NullInt64) MarshalJSON ¶
func (NullInt64) MarshalText ¶
func (*NullInt64) UnmarshalJSON ¶
func (*NullInt64) UnmarshalText ¶
func (NullInt64) ValueOrZero ¶
type NullInt8 ¶
func (NullInt8) MarshalJSON ¶
func (NullInt8) MarshalText ¶
func (*NullInt8) UnmarshalJSON ¶
func (*NullInt8) UnmarshalText ¶
func (NullInt8) ValueOrZero ¶
type NullString ¶
func (NullString) IsNil ¶
func (ns NullString) IsNil() bool
func (NullString) MarshalJSON ¶
func (ns NullString) MarshalJSON() ([]byte, error)
func (NullString) MarshalText ¶
func (ns NullString) MarshalText() ([]byte, error)
func (NullString) Ptr ¶
func (ns NullString) Ptr() *string
func (*NullString) UnmarshalJSON ¶
func (ns *NullString) UnmarshalJSON(data []byte) error
func (*NullString) UnmarshalText ¶
func (ns *NullString) UnmarshalText(text []byte) error
func (NullString) ValueOrZero ¶
func (ns NullString) ValueOrZero() string
type NullTime ¶
func (NullTime) ValueOrZero ¶
type NullUint ¶
func (NullUint) MarshalJSON ¶
func (NullUint) MarshalText ¶
func (*NullUint) UnmarshalJSON ¶
func (*NullUint) UnmarshalText ¶
func (NullUint) ValueOrZero ¶
type NullUint16 ¶
func (NullUint16) IsNil ¶
func (nu NullUint16) IsNil() bool
func (NullUint16) MarshalJSON ¶
func (nu NullUint16) MarshalJSON() ([]byte, error)
func (NullUint16) MarshalText ¶
func (nu NullUint16) MarshalText() ([]byte, error)
func (NullUint16) Ptr ¶
func (nu NullUint16) Ptr() *uint16
func (*NullUint16) UnmarshalJSON ¶
func (nu *NullUint16) UnmarshalJSON(data []byte) error
func (*NullUint16) UnmarshalText ¶
func (nu *NullUint16) UnmarshalText(text []byte) error
func (NullUint16) ValueOrZero ¶
func (nu NullUint16) ValueOrZero() uint16
type NullUint32 ¶
func (NullUint32) IsNil ¶
func (nu NullUint32) IsNil() bool
func (NullUint32) MarshalJSON ¶
func (nu NullUint32) MarshalJSON() ([]byte, error)
func (NullUint32) MarshalText ¶
func (nu NullUint32) MarshalText() ([]byte, error)
func (NullUint32) Ptr ¶
func (nu NullUint32) Ptr() *uint32
func (*NullUint32) UnmarshalJSON ¶
func (nu *NullUint32) UnmarshalJSON(data []byte) error
func (*NullUint32) UnmarshalText ¶
func (nu *NullUint32) UnmarshalText(text []byte) error
func (NullUint32) ValueOrZero ¶
func (nu NullUint32) ValueOrZero() uint32
type NullUint64 ¶
func (NullUint64) IsNil ¶
func (nu NullUint64) IsNil() bool
func (NullUint64) MarshalJSON ¶
func (nu NullUint64) MarshalJSON() ([]byte, error)
func (NullUint64) MarshalText ¶
func (nu NullUint64) MarshalText() ([]byte, error)
func (NullUint64) Ptr ¶
func (nu NullUint64) Ptr() *uint64
func (*NullUint64) UnmarshalJSON ¶
func (nu *NullUint64) UnmarshalJSON(data []byte) error
func (*NullUint64) UnmarshalText ¶
func (nu *NullUint64) UnmarshalText(text []byte) error
func (NullUint64) ValueOrZero ¶
func (nu NullUint64) ValueOrZero() uint64
type NullUint8 ¶
func (NullUint8) MarshalJSON ¶
func (NullUint8) MarshalText ¶
func (*NullUint8) UnmarshalJSON ¶
func (*NullUint8) UnmarshalText ¶
func (NullUint8) ValueOrZero ¶
type Pongo2Template ¶
type Pongo2Template struct { SqlTemplateRootDir string Template map[string]*pongo2.Template Capacity uint Cipher Cipher Type int Funcs map[string]FuncMap // contains filtered or unexported fields }
func Pongo2 ¶
func Pongo2(directory, extension string) *Pongo2Template
func (*Pongo2Template) AddSqlTemplate ¶
func (sqlTemplate *Pongo2Template) AddSqlTemplate(key string, sqlTemplateStr string) error
func (*Pongo2Template) BatchAddSqlTemplate ¶
func (sqlTemplate *Pongo2Template) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
func (*Pongo2Template) BatchLoadSqlTemplate ¶
func (sqlTemplate *Pongo2Template) BatchLoadSqlTemplate(filepathSlice []string) error
func (*Pongo2Template) BatchReloadSqlTemplate ¶
func (sqlTemplate *Pongo2Template) BatchReloadSqlTemplate(filepathSlice []string) error
func (*Pongo2Template) BatchRemoveSqlTemplate ¶
func (sqlTemplate *Pongo2Template) BatchRemoveSqlTemplate(key []string)
func (*Pongo2Template) BatchUpdateSqlTemplate ¶
func (sqlTemplate *Pongo2Template) BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error
func (*Pongo2Template) Execute ¶
func (sqlTemplate *Pongo2Template) Execute(key string, args ...interface{}) (string, error)
func (*Pongo2Template) Extension ¶
func (sqlTemplate *Pongo2Template) Extension() string
func (*Pongo2Template) GetSqlTemplate ¶
func (sqlTemplate *Pongo2Template) GetSqlTemplate(key string) *pongo2.Template
func (*Pongo2Template) GetSqlTemplates ¶
func (sqlTemplate *Pongo2Template) GetSqlTemplates(keys ...interface{}) map[string]*pongo2.Template
func (*Pongo2Template) LoadSqlTemplate ¶
func (sqlTemplate *Pongo2Template) LoadSqlTemplate(filepath string) error
-------------------------------------------------------------------------------------------------------------
func (*Pongo2Template) ReadTemplate ¶
func (sqlTemplate *Pongo2Template) ReadTemplate(filepath string) ([]byte, error)
func (*Pongo2Template) ReloadSqlTemplate ¶
func (sqlTemplate *Pongo2Template) ReloadSqlTemplate(filepath string) error
func (*Pongo2Template) RemoveSqlTemplate ¶
func (sqlTemplate *Pongo2Template) RemoveSqlTemplate(key string)
func (*Pongo2Template) RootDir ¶
func (sqlTemplate *Pongo2Template) RootDir() string
func (*Pongo2Template) SetFuncs ¶
func (sqlTemplate *Pongo2Template) SetFuncs(key string, funcMap FuncMap)
func (*Pongo2Template) SetSqlTemplateCipher ¶
func (sqlTemplate *Pongo2Template) SetSqlTemplateCipher(cipher Cipher)
func (*Pongo2Template) UpdateSqlTemplate ¶
func (sqlTemplate *Pongo2Template) UpdateSqlTemplate(key string, sqlTemplateStr string) error
type ResultBean ¶
func (*ResultBean) GetResult ¶
func (resultBean *ResultBean) GetResult() (bool, interface{}, error)
type ResultMap ¶
func (*ResultMap) SaveAsHTML ¶
func (*ResultMap) SaveAsJSON ¶
func (*ResultMap) SaveAsXLSX ¶
func (*ResultMap) SaveAsXMLWithTagNamePrefixIndent ¶
func (*ResultMap) SaveAsYAML ¶
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)
type ResultValue ¶
func (*ResultValue) Count ¶
func (resultValue *ResultValue) Count() (int, error)
func (*ResultValue) List ¶
func (resultValue *ResultValue) List() (Result, error)
type Rows ¶
type Rows struct {
// contains filtered or unexported fields
}
Rows rows wrapper a rows to
func (*Rows) Err ¶
Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.
type RsaEncrypt ¶
type RsaEncrypt struct { PubKey string PriKey string EncryptMode int DecryptMode int // contains filtered or unexported fields }
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session keep a pointer to sql.DB and provides all execution of all kind of database operations.
func (*Session) BeginTrans ¶
func (session *Session) BeginTrans(transactionDefinition ...int) (*Transaction, error)
func (*Session) BufferSize ¶
BufferSize sets the buffersize for iterate
func (*Session) ContextCache ¶
func (session *Session) ContextCache(context contexts.ContextCache) *Session
ContextCache enable context cache or not
func (*Session) CreateIndexes ¶
CreateIndexes create indexes
func (*Session) CreateTable ¶
CreateTable create a table according a bean
func (*Session) CreateUniques ¶
CreateUniques create uniques
func (*Session) Desc ¶
Desc provide desc order by query condition, the input parameters are columns.
func (*Session) Distinct ¶
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 ¶
DropIndexes drop indexes
func (*Session) DropTable ¶
DropTable drop table will drop table if exist, if drop failed, it will return error
func (*Session) Find ¶
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) FindAndCount ¶
func (session *Session) FindAndCount(rowsSlicePtr interface{}, condiBean ...interface{}) (int64, error)
FindAndCount find the results and also return the counts
func (*Session) Get ¶
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) ImportFile ¶
ImportFile SQL DDL file
func (*Session) InsertMulti ¶
InsertMulti insert multiple records
func (*Session) InsertOne ¶
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 ¶
IsTableEmpty if table have any records
func (*Session) IsTableExist ¶
IsTableExist if a table is exist
func (*Session) Iterate ¶
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) MustLogSQL ¶
MustLogSQL means record SQL or not and don't follow engine's setting
func (*Session) NoAutoCondition ¶
NoAutoCondition disable generate SQL condition from beans
func (*Session) NoAutoTime ¶
NoAutoTime means do not automatically give created field and updated field the current time on the current session temporarily
func (*Session) NoCache ¶
NoCache ask this session do not retrieve data from cache system and get data from database directly.
func (*Session) OrderBy ¶
OrderBy provide order by query condition, the input parameter is the content after order by on a sql statement.
func (*Session) PingContext ¶
PingContext test if database is ok
func (*Session) Prepare ¶
Prepare set a flag to session that should be prepare statement before execute query
func (*Session) QueryBytes ¶
Query runs a raw sql and return records as []map[string][]byte
func (*Session) QueryExpr ¶
func (session *Session) QueryExpr(sqlOrArgs ...interface{}) sqlExpr
QueryExpr returns the query as bound SQL
func (*Session) QueryInterface ¶
QueryInterface runs a raw sql and return records as []map[string]interface{}
func (*Session) QueryResult ¶
func (session *Session) QueryResult(sqlOrArgs ...interface{}) *ResultValue
Query runs a raw sql and return records as ResultValue
func (*Session) QuerySliceString ¶
QuerySliceString runs a raw sql and return records as [][]string
func (*Session) QueryString ¶
QueryString runs a raw sql and return records as []map[string]string
func (*Session) QueryValue ¶
func (*Session) QueryWithDateFormat ¶
Exec a raw sql and return records as ResultMap
func (*Session) Rows ¶
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) SQL ¶
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) Search ¶
func (session *Session) Search(rowsSlicePtr interface{}, condiBean ...interface{}) *ResultStructs
func (*Session) SqlMapClient ¶
func (*Session) SqlMapsClient ¶
func (session *Session) SqlMapsClient(sqlkeys interface{}, parmas ...interface{}) *SqlMapsExecutor
func (*Session) SqlTemplateClient ¶
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 ¶
StoreEngine is only avialble mysql dialect currently
func (*Session) Table ¶
Table can input a string or pointer to struct for special a table to operate.
func (*Session) Update ¶
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
type SqlMapsExecutor ¶
type SqlMapsExecutor struct {
// contains filtered or unexported fields
}
type SqlTemplate ¶
type SqlTemplate interface { WalkFunc(path string, info os.FileInfo, err error) error ReadTemplate(filepath string) ([]byte, error) Execute(key string, args ...interface{}) (string, error) RootDir() string Extension() string SetSqlTemplateCipher(cipher Cipher) LoadSqlTemplate(filepath string) error BatchLoadSqlTemplate(filepathSlice []string) error ReloadSqlTemplate(filepath string) error BatchReloadSqlTemplate(filepathSlice []string) error AddSqlTemplate(key string, sqlTemplateStr string) error UpdateSqlTemplate(key string, sqlTemplateStr string) error RemoveSqlTemplate(key string) BatchAddSqlTemplate(key string, sqlTemplateStrMap map[string]string) error BatchUpdateSqlTemplate(key string, sqlTemplateStrMap map[string]string) error BatchRemoveSqlTemplate(key []string) SetFuncs(key string, funcMap FuncMap) // contains filtered or unexported methods }
type SqlTemplatesExecutor ¶
type SqlTemplatesExecutor struct {
// contains filtered or unexported fields
}
type SqlsExecutor ¶
type SqlsExecutor struct {
// contains filtered or unexported fields
}
type StdJSON ¶
type StdJSON struct{}
StdJSON implements JSONInterface via encoding/json
type StringBuilder ¶
type StringBuilder struct {
// contains filtered or unexported fields
}
A StringBuilder is used to efficiently build a string using Write methods. It minimizes memory copying. The zero value is ready to use. Do not copy a non-zero Builder.
func (*StringBuilder) Grow ¶
func (b *StringBuilder) Grow(n int)
Grow grows b's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to b without another allocation. If n is negative, Grow panics.
func (*StringBuilder) Len ¶
func (b *StringBuilder) Len() int
Len returns the number of accumulated bytes; b.Len() == len(b.String()).
func (*StringBuilder) String ¶
func (b *StringBuilder) String() string
String returns the accumulated string.
func (*StringBuilder) Write ¶
func (b *StringBuilder) Write(p []byte) (int, error)
Write appends the contents of p to b's buffer. Write always returns len(p), nil.
func (*StringBuilder) WriteByte ¶
func (b *StringBuilder) WriteByte(c byte) error
WriteByte appends the byte c to b's buffer. The returned error is always nil.
func (*StringBuilder) WriteRune ¶
func (b *StringBuilder) WriteRune(r rune) (int, error)
WriteRune appends the UTF-8 encoding of Unicode code point r to b's buffer. It returns the length of r and a nil error.
func (*StringBuilder) WriteString ¶
func (b *StringBuilder) WriteString(s string) (int, error)
WriteString appends the contents of s to b's buffer. It returns the length of s and a nil error.
type Transaction ¶
type Transaction struct {
// contains filtered or unexported fields
}
func (*Transaction) BeginTrans ¶
func (transaction *Transaction) BeginTrans() error
Begin a transaction
func (*Transaction) CommitTrans ¶
func (transaction *Transaction) CommitTrans() error
Commit When using transaction, Commit will commit all operations.
func (*Transaction) Do ¶
func (transaction *Transaction) Do(doFunc func(params ...interface{}), params ...interface{})
func (*Transaction) GetSavePointID ¶
func (transaction *Transaction) GetSavePointID() string
func (*Transaction) IsExistingTransaction ¶
func (transaction *Transaction) IsExistingTransaction() bool
func (*Transaction) RollbackToSavePoint ¶
func (transaction *Transaction) RollbackToSavePoint(savePointID string) error
func (*Transaction) RollbackTrans ¶
func (transaction *Transaction) RollbackTrans() error
Rollback When using transaction, you can rollback if any error
func (*Transaction) SavePoint ¶
func (transaction *Transaction) SavePoint(savePointID string) error
func (*Transaction) Session ¶
func (transaction *Transaction) Session() *Session
func (*Transaction) TransactionDefinition ¶
func (transaction *Transaction) TransactionDefinition() int
func (*Transaction) WaitForDo ¶
func (transaction *Transaction) WaitForDo(doFunc func(params ...interface{}), params ...interface{})
type TripleDesEncrypt ¶
type TripleDesEncrypt struct {
PubKey string
}
type Value ¶
type Value []byte
func (Value) NullFloat32 ¶
func (v Value) NullFloat32() NullFloat32
func (Value) NullFloat64 ¶
func (v Value) NullFloat64() NullFloat64
func (Value) NullString ¶
func (v Value) NullString() NullString
func (Value) NullUint16 ¶
func (v Value) NullUint16() NullUint16
func (Value) NullUint32 ¶
func (v Value) NullUint32() NullUint32
func (Value) NullUint64 ¶
func (v Value) NullUint64() NullUint64
func (Value) TimeDuration ¶
Source Files
- cipher.go
- context_cache.go
- convert.go
- databook.go
- dataset.go
- encrypt_aes.go
- encrypt_des.go
- encrypt_rsa.go
- engine.go
- engine_group.go
- engine_group_policy.go
- engine_sqlmap.go
- engine_sqltemplate.go
- engineplus.go
- error.go
- fswatcher.go
- helpers_plus.go
- interface.go
- json.go
- null.go
- null_bool.go
- null_float32.go
- null_float64.go
- null_int.go
- null_int16.go
- null_int32.go
- null_int64.go
- null_int8.go
- null_string.go
- null_time.go
- null_uint.go
- null_uint16.go
- null_uint32.go
- null_uint64.go
- null_uint8.go
- processors.go
- rows.go
- session.go
- session_cols.go
- session_cond.go
- session_convert.go
- session_delete.go
- session_exist.go
- session_find.go
- session_get.go
- session_insert.go
- session_iterate.go
- session_plus.go
- session_query.go
- session_raw.go
- session_schema.go
- session_stats.go
- session_tx.go
- session_tx_plus.go
- session_update.go
- sql_executor.go
- sql_expr.go
- sqlmap.go
- sqlmap_json.go
- sqlmap_xml.go
- sqlmap_xsql.go
- sqlmaps_executor.go
- sqltemplate.go
- sqltemplate_default.go
- sqltemplate_jet.go
- sqltemplate_pongo2.go
- sqltemplates_executor.go
- string_builder.go
- value.go
- xorm.go
- xormplus.go