spellsql

package module
v1.6.12 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: MIT Imports: 15 Imported by: 0

README

spellsql

🚀🚀🚀 项目背景
  • 公司选择了一波 orm 框架, 大多数框架都比较重, 重和性能相互, 最终放弃 orm;

  • 决定用原生 database/sql, 优势: 性能好, bug容易定位, 使用成本低等; 劣势: 代码拼接, 代码量很多, NULL处理等;

  • 为了解决 sql 拼接实现了 spellsql:

    1.使用 sync.Pool, strings.Builder 等提高 sql 拼接工具的性能
    2.💯覆盖使用场景
    3.支持 可控打印 sql 最终的 log; 非法字符自动转义; 支持格式化 sql

  • 为了解决满足性能和释放双手添加了 orm 功能, 支持: mysql|pg

    1.新增/更新: 支持通过 struct 解析值进行操作; 支持对字段进行 序列化 操作; 支持设置别名, 设置默认值
    2.删除: 支持通过 struct 解析值进行
    3.查询: 支持单表/多表查询; 支持对结果进行回调处理; 查询性能接近原生; 支持对结果映射到 struct/map/slice/单字段

1. 使用介绍
  • 安装:
go get -u gitee.com/xuesongtao/spellsql
2. 占位符
  • 目前支持占位符 ?, ?d, ?v, 说明如下:
2.1 占位符 ?
  • 直接根据 args 中类型来自动推动 arg 的类型, 使用如下:

1.第一种用法: 根据 args 中类型来自动推动 arg 的类型

如: NewCacheSql("SELECT username, password FROM sys_user WHERE username = ? AND password = ?", "test", 123).GetSqlStr()
=> SELECT username, password FROM sys_user WHERE username = "test" AND password = 123

2.第二种用法: 当 arg 为 []int8/int 等

如: NewCacheSql("SELECT username, password FROM sys_user WHERE id IN (?)", []int{1, 2, 3}).GetSqlStr()
=> SELECT username, password FROM sys_user WHERE id IN (1,2,3)
2.2 占位符 ?d
  • 只会把数字型的字符串转为数字型, 如果是字母的话会被转义为 0, 如: "123" => 123; []string{"1", "2", "3"} => 1,2,3, 如下: 第一种用法: 当 arg 为字符串时, 又想不加双引号就用这个
如: NewCacheSql("SELECT username, password FROM sys_user WHERE id = ?d", "123").GetSqlStr()
=> SELECT username, password FROM sys_user WHERE id = 123

第二种用法: 当 arg 为 []string, 又想把解析后的单个元素不加引号

如: NewCacheSql("SELECT username, password FROM sys_user WHERE id IN (?d)", []string{"1", "2", "3"}).GetSqlStr()
=> SELECT username, password FROM sys_user WHERE id IN (1,2,3)
2.3 占位符为: ?v
  • 这样会让字符串类型不加引号, 原样输出, 如: "test" => test; 第一种用法: 当 arg 为字符串时, 又想不加双引号就用这个, 注: 只支持 arg 为字符串类型
如: NewCacheSql("SELECT username, password FROM ?v WHERE id = ?d", "sys_user", "123").GetSqlStr()
=> SELECT username, password FROM sys_user WHERE id = 123

第二种用法: 子查询

如: NewCacheSql("SELECT u.username, u.password FROM sys_user su LEFT JOIN user u ON su.id = u.id WHERE u.id IN (?v)", FmtSqlStr("SELECT id FROM user WHERE name=?", "test").GetSqlStr()
=> SELECT u.username, u.password FROM sys_user su LEFT JOIN user u ON su.id = u.id WHERE u.id IN (SELECT id FROM user WHERE name="test");
  • 注: 由于 ?v 这种不会进行转义处理, 所有这种不推荐直接用于请求输入(外部非法输入)的内容, 会出现 SQL 注入风险; 当我们明确知道参数是干什么的可以使用会简化我们代码, 这里就不进行演示.
3. spellsql 使用
  • 可以参考 getsqlstr_test.goexample_spellsql_test.go 里的测试方法
3.1 新增
s := NewCacheSql("INSERT INTO sys_user (username, password, name)")
s.SetInsertValues("xuesongtao", "123456", "阿桃")
s.SetInsertValues("xuesongtao", "123456", "阿桃")
s.GetSqlStr()

// Output:
// INSERT INTO sys_user (username, password, name) VALUES ("test", 123456, "阿涛"), ("xuesongtao", "123456", "阿桃"), ("xuesongtao", "123456", "阿桃");
3.2 删除
s := NewCacheSql("DELETE FROM sys_user WHERE id = ?", 123)
if true {
    s.SetWhere("name", "test")
}
s.GetSqlStr()
// Output:
// DELETE FROM sys_user WHERE id = 123 AND name = "test";
3.3 查询
s := NewCacheSql("SELECT * FROM user u LEFT JOIN role r ON u.id = r.user_id")
s.SetOrWhere("u.name", "xue")
s.SetOrWhereArgs("(r.id IN (?d))", []string{"1", "2"})
s.SetWhere("u.age", ">", 20)
s.SetWhereArgs("u.addr = ?", "南部")
s.GetTotalSqlStr()
s.SetLimit(1, 10)
s.GetSqlStr()

// Output:
// sqlTotalStr: SELECT COUNT(*) FROM user u LEFT JOIN role r ON u.id = r.user_id WHERE u.name = "xue" OR (r.id IN (1,2)) AND u.age > 20 AND u.addr = "南部";
// sqlStr: SELECT * FROM user u LEFT JOIN role r ON u.id = r.user_id WHERE u.name = "xue" OR (r.id IN (1,2)) AND u.age > 20 AND u.addr = "南部" LIMIT 0, 10;
3.4 修改
s := NewCacheSql("UPDATE sys_user SET")
idsStr := []string{"1", "2", "3", "4", "5"}
s.SetUpdateValue("name", "xue")
s.SetUpdateValueArgs("age = ?, score = ?", 18, 90.5)
s.SetWhereArgs("id IN (?d) AND name = ?", idsStr, "tao")
s.GetSqlStr()

// Output:
// UPDATE sys_user SET name = "xue", age = 18, score = 90.50 WHERE id IN (1,2,3,4,5) AND name = "tao";
3.5 追加
s := NewCacheSql("INSERT INTO sys_user (username, password, age)")
s.SetInsertValuesArgs("?, ?, ?d", "xuesongtao", "123", "20")
s.Append("ON DUPLICATE KEY UPDATE username=VALUES(username)")
s.GetSqlStr()

// Output:
// INSERT INTO sys_user (username, password, age) VALUES ("xuesongtao", "123", 20) ON DUPLICATE KEY UPDATE username=VALUES(username);
3.6 复用
    1. NewCacheSql() 获取的对象在调用 GetSqlStr() 后会重置并放入内存池, 是不能对结果进行再进行 GetSqlStr(), 当然你是可以对结果作为 NewCacheSql() 的入参进行使用以此达到复用, 这样代码看起来不是多优雅, 分页处理案例如下:
sqlObj := NewCacheSql("SELECT * FROM user_info WHERE status = 1")
handleFn := func(obj *SqlStrObj, page, size int32) {
    // 业务代码
    fmt.Println(obj.SetLimit(page, size).SetPrintLog(false).GetSqlStr())
}

// 每次同步大小
var (
    totalNum int32 = 30
    page int32 = 1
    size int32 = 10
    totalPage int32 = int32(math.Ceil(float64(totalNum / size)))
)

sqlStr := sqlObj.SetPrintLog(false).GetSqlStr("", "")
for page <= totalPage {
    handleFn(NewCacheSql(sqlStr), page, size)
    page++
}

// Output:
// SELECT * FROM user_info WHERE u_status = 1 LIMIT 0, 10;
// SELECT * FROM user_info WHERE u_status = 1 LIMIT 10, 10;
// SELECT * FROM user_info WHERE u_status = 1 LIMIT 20, 10;
  • NewSql() 的产生的对象不会放入内存池, 可以进行多次调用 GetSqlStr(), 对应上面的示例可以使用 NewSql() 再调用 Clone() 进行处理, 如下:
sqlObj := NewSql("SELECT u_name, phone, account_id FROM user_info WHERE u_status = 1")
handleFn := func(obj *SqlStrObj, page, size int32) {
    // 业务代码
    fmt.Println(obj.SetLimit(page, size).SetPrintLog(false).GetSqlStr())
}

// 每次同步大小
var (
    totalNum int32 = 30
    page int32 = 1
    size int32 = 10
    totalPage int32 = int32(math.Ceil(float64(totalNum / size)))
)

for page <= totalPage {
    handleFn(sqlObj.Clone(), page, size)
    page++
}

// Output:
// SELECT * FROM user_info WHERE u_status = 1 LIMIT 0, 10;
// SELECT * FROM user_info WHERE u_status = 1 LIMIT 10, 10;
// SELECT * FROM user_info WHERE u_status = 1 LIMIT 20, 10;
4 orm使用介绍
  • spellsql_orm 能够高效的处理单表 CURD. 在查询方面的性能接近原生(orm_test.go 里有测试数据), 可以在 dev 分支上测试
  • 支持自定义 tag, 默认 json
type Man struct {
    Id int32 `json:"id,omitempty"`
    Name string `json:"name,omitempty"`
    Age int32 `json:"age,omitempty"`
    Addr string `json:"addr,omitempty"`
}

4.1 新增
m := Man{
    Name: "xue1234",
    Age: 18,
    Addr: "成都市",
}

// 1
rows, _ = InsertForObj(db, "man", m)
t.Log(rows.LastInsertId())

// 3
sqlObj := NewCacheSql("INSERT INTO man (name,age,addr) VALUES (?, ?, ?)", m.Name, m.Age, m.Addr)
rows, _ = ExecForSql(db, sqlObj)
t.Log(rows.LastInsertId())
4.2 删除
m := Man{
    Id: 9,
}

// 1
rows, _ := NewTable(db).Delete(m).Exec()
t.Log(rows.LastInsertId())

// 2
rows, _ = DeleteWhere(db, "man", "id=?", 9)
t.Log(rows.LastInsertId())

// 3
sqlObj := NewCacheSql("DELETE FROM man WHERE id=?", 9)
rows, _ = ExecForSql(db, sqlObj)
t.Log(rows.LastInsertId())
4.3 修改
m := Man{
    Name: "xue12",
    Age: 20,
    Addr: "测试",
}

// 1
rows, _ := NewTable(db).Update(m, "id=?", 7).Exec()
t.Log(rows.LastInsertId())

// 2
sqlObj := NewCacheSql("UPDATE man SET name=?,age=?,addr=? WHERE id=?", m.Name, m.Age, m.Addr, 7)
rows, _ = ExecForSql(db, sqlObj)
t.Log(rows.LastInsertId())
4.4 查询
4.4.1 单查询
var m Man
// 1
_ = NewTable(db, "man").Select("name,age").Where("id=?", 1).FindOne(&m)
t.Log(m)

// 2
_ = NewTable(db).SelectAuto("name,age", "man").Where("id=?", 1).FindOne(&m)
t.Log(m)

// 3
_ = FindOne(db, NewCacheSql("SELECT name,age FROM man WHERE id=?", 1), &m)
t.Log(m)

// 4, 对查询结果进行内容修改
_ = FindOneFn(db, NewCacheSql("SELECT name,age FROM man WHERE id=?", 1), &m, func(_row interface{}) error {
    v := _row.(*Man)
    v.Name = "被修改了哦"
    v.Age = 100000
    return nil
})
t.Log(m)

// 5
_ = FindWhere(db, "man", &m, "id=?", 1)
t.Log(m)

// 6
var b map[string]string
_ = FindWhere(db, "man", &b, "id=?", 1)
t.Log(b)
  • 查询结果支持: struct, map, 单字段
  • 数据库返回的 NULL 类型, 不需要处理, orm 会自行处理, 如果传入空类型值会报错(如: sql.NullString)
4.4.2 多条记录查询
var m []*Man
err := NewTable(db, "man").Select("id,name,age,addr").Where("id>?", 1).FindAll(&m, func(_row interface{}) error {
    v := _row.(*Man)
    if v.Id == 5 {
        v.Name = "test"
    }
    fmt.Println(v.Id, v.Name, v.Age)
    return nil
})
if err != nil {
    t.Fatal(err)
}
t.Logf("%+v", m)
  • 查询结果支持的切片类型: struct, map, 单字段
  • 数据库返回的 NULL 类型, 不需要处理, orm 会自行处理, 如果传入空类型值会报错(如: sql.NullString)
4.4.3 别名查询
type Tmp struct {
    Name1 string `json:"name_1,omitempty"`
    Age1 int32 `json:"age_1,omitempty"`
}

var m Tmp
err := NewTable(db).
TagAlias(map[string]string{"name_1": "name", "age_1": "age"}).
Select("name,age").
From("man").
FindWhere(&m, "id=?", 1)
if err != nil {
    t.Fatal(err)
}
4.4.3 其他
  • 使用可以参考 orm_test.goexample_orm_test.go
  • 在连表查询时, 如果两个表的列名相同查询结果会出现错误, 我们可以通过根据别名来区分, 或者直接调用 Query 来自行对结果进行处理(注: 调用 Query 时需要处理 Null 类型)
其他
  • 欢迎大佬们指正, 希望大佬给❤️,to gitee github

Documentation

Index

Examples

Constants

View Source
const (
	PriFlag     = "PRI" // 主键标识
	NotNullFlag = "NO"  // 非空标识
)
View Source
const (
	INSERT uint8
	DELETE
	SELECT
	UPDATE

	// sql LIKE 语句
	ALK // 全模糊 如: xxx LIKE "%xxx%"
	RLK // 右模糊 如: xxx LIKE "xxx%"
	LLK // 左模糊 如: xxx LIKE "%xxx"

	// sql join 语句
	LJI // 左连接
	RJI // 右连接
)
View Source
const (
	NULL = "NULL"
)

Variables

This section is empty.

Functions

func ConvStruct added in v1.6.12

func ConvStruct(src interface{}, dest interface{}) error

ConvStruct 转换 struct 的值

func Count added in v1.4.0

func Count(db DBer, tableName string, dest interface{}, where string, args ...interface{}) error

Count 获取总数

Example
var count int
_ = Count(db, "man", &count, "id<?", 10)

myPrint(count, false)
Output:

8

func CountCtx added in v1.6.10

func CountCtx(ctx context.Context, db DBer, tableName string, dest interface{}, where string, args ...interface{}) error

CountCtx 获取总数

func DeleteWhere added in v1.4.9

func DeleteWhere(db DBer, tableName string, where string, args ...interface{}) (sql.Result, error)

DeleteWhere 根据条件删除

Example
_, _ = DeleteWhere(db, "man", "id=100")
Output:

func DeleteWhereCtx added in v1.6.10

func DeleteWhereCtx(ctx context.Context, db DBer, tableName string, where string, args ...interface{}) (sql.Result, error)

DeleteWhereCtx 根据条件删除

func DistinctIds added in v1.5.6

func DistinctIds(ids []string) []string

DistinctIds 去重

func DistinctIdsStr

func DistinctIdsStr(s string, split string) string

DistinctIdsStr 将输入拼接 id 参数按照指定字符进行去重, 如: DistinctIdsStr("12345,123,20,123,20,15", ",") => 12345,123,20,15

func Escape added in v1.6.8

func Escape(val []byte, escapeMap map[byte][]byte) []byte

Escape 转义字符

func ExecForSql added in v1.4.7

func ExecForSql(db DBer, sql interface{}) (sql.Result, error)

ExecForSql 根据 sql 进行执行 INSERT/UPDATE/DELETE 等操作 sql sqlStr 或 *SqlStrObj

Example
// 新增
insertSql := NewCacheSql("INSERT INTO man (name,age,addr) VALUES")
insertSql.SetInsertValues("test1", 18, "四川成都")
if _, err := ExecForSql(db, insertSql); err != nil {
	myPrint(err, false)
	return
}

// 修改
updateSql := NewCacheSql("UPDATE man SET")
updateSql.SetUpdateValue("name", "test12")
updateSql.SetWhere("id", 8)
if _, err := ExecForSql(db, updateSql); err != nil {
	myPrint(err, false)
	return
}

// 删除
deleteSql := NewCacheSql("DELETE FROM man WHERE id=100")
if _, err := ExecForSql(db, deleteSql); err != nil {
	myPrint(err, false)
	return
}
Output:

func ExecForSqlCtx added in v1.6.10

func ExecForSqlCtx(ctx context.Context, db DBer, sql interface{}) (sql.Result, error)

ExecForSqlCtx 根据 sql 进行执行 INSERT/UPDATE/DELETE 等操作 sql sqlStr 或 *SqlStrObj

func FindAll added in v1.3.9

func FindAll(db DBer, sql interface{}, dest interface{}, fn ...SelectCallBackFn) error

FindAll 多查询 sql sqlStr 或 *SqlStrObj

func FindAllCtx added in v1.6.10

func FindAllCtx(ctx context.Context, db DBer, sql interface{}, dest interface{}, fn ...SelectCallBackFn) error

FindAllCtx 多查询 sql sqlStr 或 *SqlStrObj

func FindOne added in v1.3.9

func FindOne(db DBer, sql interface{}, dest ...interface{}) error

FindOne 单查询 sql sqlStr 或 *SqlStrObj

Example
var m test.Man
sqlObj := NewCacheSql("SELECT name,age,addr FROM man WHERE id=?", 1)
_ = FindOne(db, sqlObj, &m)

myPrint(m, true)
Output:

{"name":"测试1","age":20,"json_txt":{},"xml_txt":{},"json1_txt":{}}

func FindOneCtx added in v1.6.10

func FindOneCtx(ctx context.Context, db DBer, sql interface{}, dest ...interface{}) error

FindOneCtx 单查询 sql sqlStr 或 *SqlStrObj

func FindOneFn added in v1.4.9

func FindOneFn(db DBer, sql interface{}, dest interface{}, fn ...SelectCallBackFn) error

FindOneFn 单查询 sql sqlStr 或 *SqlStrObj

func FindOneFnCtx added in v1.6.10

func FindOneFnCtx(ctx context.Context, db DBer, sql interface{}, dest interface{}, fn ...SelectCallBackFn) error

FindOneFnCtx 单查询 sql sqlStr 或 *SqlStrObj

func FindWhere added in v1.4.2

func FindWhere(db DBer, tableName string, dest interface{}, where string, args ...interface{}) error

FindWhere 查询对象中的字段内容

Example
var m test.Man
_ = FindWhere(db, "man", &m, "id=?", 1)

myPrint(m, true)
Output:

{"id":1,"name":"测试1","age":20,"json_txt":{},"xml_txt":{},"json1_txt":{}}

func FindWhereCtx added in v1.6.10

func FindWhereCtx(ctx context.Context, db DBer, tableName string, dest interface{}, where string, args ...interface{}) error

FindWhereCtx 查询对象中的字段内容

func FmtSqlStr

func FmtSqlStr(sqlStr string, args ...interface{}) string

FmtSqlStr 适用直接获取 sqlStr, 不会打印日志

Example
sqlStr := FmtSqlStr("SELECT * FROM ?v WHERE id IN (?d) AND name=?", "user_info", []string{"1", "2"}, "测试")
fmt.Println(sqlStr)
Output:

SELECT * FROM user_info WHERE id IN (1,2) AND name="测试"

func FreeTmerFlag added in v1.6.1

func FreeTmerFlag(is bool)

FreeTmerFlag 是否每次调用 orm 完后需要释放 tmer 如果都是适配相同的数据库, 则可以设置 false, 避免每次都需要初始化适配器 反之应该设置为 true

func GetLikeSqlStr

func GetLikeSqlStr(likeType uint8, sqlStr, fieldName, value string, printLog ...bool) string

GetLikeSqlStr 针对 LIKE 语句, 只有一个条件 如: obj := GetLikeSqlStr(ALK, "SELECT id, username FROM sys_user", "name", "xue")

=> SELECT id, username FROM sys_user WHERE name LIKE "%xue%"

func GetSqlStr

func GetSqlStr(sqlStr string, args ...interface{}) string

GetSqlStr 适用直接获取 sqlStr, 每次会自动打印日志

func GetSqlStrCtx added in v1.6.10

func GetSqlStrCtx(ctx context.Context, sqlStr string, args ...interface{}) string

GetSqlStrCtx 适用直接获取 sqlStr, 每次会自动打印日志

func GetValueEscapeMap added in v1.6.8

func GetValueEscapeMap() map[byte][]byte

GetValueEscapeMap 获取值的转义处理

func GlobalTmer added in v1.6.0

func GlobalTmer(f func() TableMetaer)

GlobalTmer 设置全局 tmer, 如果要局部使用, 请使用 Tmer

func IndexForBF

func IndexForBF(isFont2End bool, s, substr string) int

IndexForBF 查找, 通过 BF 算法来获取匹配的 index isFont2End 是否从主串前向后遍历查找 如果匹配的内容靠前建议 isFont2End=true, 反之 false TODO 暂不支持中文

func InsertForObj added in v1.3.9

func InsertForObj(db DBer, tableName string, src ...interface{}) (sql.Result, error)

InsertForObj 根据对象新增

Example
type Tmp struct {
	Id   int32  `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
	Age  int32  `json:"age,omitempty"`
	Addr string `json:"addr,omitempty"`
}

m := Tmp{
	Name: "xue1234",
	Age:  18,
	Addr: "成都市",
}

r, _ := InsertForObj(db, "man", m)
rr, _ := r.RowsAffected()
myPrint(rr, false)
Output:

1

func InsertForObjCtx added in v1.6.10

func InsertForObjCtx(ctx context.Context, db DBer, tableName string, src ...interface{}) (sql.Result, error)

InsertForObjCtx 根据对象新增

func InsertHasDefaultForObj added in v1.5.38

func InsertHasDefaultForObj(db DBer, tableName string, tag2DefaultMap map[string]interface{}, src interface{}) (sql.Result, error)

InsertHasDefaultForObj 根据对象新增, 同时支持默认值

Example
type Tmp struct {
	Id   int32  `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
	Age  int32  `json:"age,omitempty"`
	Addr string `json:"addr,omitempty"`
}

m := Tmp{
	Name: "xue1234",
	Addr: "成都市",
}

r, err := InsertHasDefaultForObj(db, "man", nil, m)
if err != nil {
	fmt.Println(`field "age" should't null, you can first call TagDefault`)
	return
}
rr, _ := r.RowsAffected()
myPrint(rr, false)
Output:

field "age" should't null, you can first call TagDefault

func InsertHasDefaultForObjCtx added in v1.6.10

func InsertHasDefaultForObjCtx(ctx context.Context, db DBer, tableName string, tag2DefaultMap map[string]interface{}, src interface{}) (sql.Result, error)

InsertHasDefaultForObjCtx 根据对象新增, 同时支持默认值

func InsertIgForObj added in v1.5.35

func InsertIgForObj(db DBer, tableName string, src interface{}) (sql.Result, error)

InsertIgForObj 根据对象新增, 冲突忽略

func InsertIgForObjCtx added in v1.6.10

func InsertIgForObjCtx(ctx context.Context, db DBer, tableName string, src interface{}) (sql.Result, error)

InsertIgForObjCtx 根据对象新增, 冲突忽略

func InsertODKUForObj added in v1.5.35

func InsertODKUForObj(db DBer, tableName string, src interface{}, keys ...string) (sql.Result, error)

InsertODKUForObj 根据对象新增, 冲突更新

func InsertODKUForObjCtx added in v1.6.10

func InsertODKUForObjCtx(ctx context.Context, db DBer, tableName string, src interface{}, keys ...string) (sql.Result, error)

InsertODKUForObjCtx 根据对象新增, 冲突更新

func InsertsHasDefaultForObjCtx added in v1.6.12

func InsertsHasDefaultForObjCtx(ctx context.Context, db DBer, tableName string, tag2DefaultMap map[string]interface{}, src ...interface{}) (sql.Result, error)

InsertHasDefaultForObjCtx 根据对象新增, 同时支持默认值

func Int64 added in v1.6.0

func Int64(num interface{}) int64

Int64 将数字型类型转为 int64

func IsNullRow added in v1.4.8

func IsNullRow(err error) bool

IsNullRow 根据 err 判断是否结果为空

func NewLogger added in v1.6.6

func NewLogger() *defaultLogger

func SelectFindAll added in v1.5.5

func SelectFindAll(db DBer, fields interface{}, tableName string, where string, dest interface{}, fn ...SelectCallBackFn) error

SelectFindAll 多行指定内容查询 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

Example
var m []test.Man
_ = SelectFindAll(db, "id,name", "man", "id<3", &m)

myPrint(m, true)
Output:

[{"id":1,"name":"测试1","json_txt":{},"xml_txt":{},"json1_txt":{}},{"id":2,"name":"xue1","json_txt":{},"xml_txt":{},"json1_txt":{}}]

func SelectFindAllCtx added in v1.6.10

func SelectFindAllCtx(ctx context.Context, db DBer, fields interface{}, tableName string, where string, dest interface{}, fn ...SelectCallBackFn) error

SelectFindAllCtx 多行指定内容查询 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

func SelectFindOne added in v1.5.1

func SelectFindOne(db DBer, fields interface{}, tableName string, where string, dest ...interface{}) error

SelectFindOne 单行指定内容查询 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

Example
var m test.Man
_ = SelectFindOne(db, "name,addr", "man", "id=1", &m)

myPrint(m, true)
Output:

{"name":"测试1","json_txt":{},"xml_txt":{},"json1_txt":{}}

func SelectFindOneCtx added in v1.6.10

func SelectFindOneCtx(ctx context.Context, db DBer, fields interface{}, tableName string, where string, dest ...interface{}) error

SelectFindOneCtx 单行指定内容查询 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

func SelectFindOneFn added in v1.5.5

func SelectFindOneFn(db DBer, fields interface{}, tableName string, where string, dest interface{}, fn ...SelectCallBackFn) error

SelectFindOneFn 单行指定内容查询 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

Example
var m test.Man
_ = SelectFindOneFn(db, "name,age", "man", "id=1", &m, func(_row interface{}) error {
	v := _row.(*test.Man)
	v.Name = "被修改了哦"
	return nil
})

myPrint(m, true)
Output:

{"name":"被修改了哦","age":20,"json_txt":{},"xml_txt":{},"json1_txt":{}}

func SelectFindOneFnCtx added in v1.6.10

func SelectFindOneFnCtx(ctx context.Context, db DBer, fields interface{}, tableName string, where string, dest interface{}, fn ...SelectCallBackFn) error

SelectFindOneFnCtx 单行指定内容查询 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

func SelectFindOneIgnoreResult added in v1.5.6

func SelectFindOneIgnoreResult(db DBer, fields interface{}, tableName string, where string, dest interface{}, fn ...SelectCallBackFn) error

SelectFindOneIgnoreResult 查询结果支持多个, 此使用场景为需要使用 SelectCallBackFn 对每行进行处理 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

Example
var m test.Man
var idMap = make(map[int32]string, 10)
_ = SelectFindOneIgnoreResult(db, "id,name", "man", "id<10", &m, func(_row interface{}) error {
	v := _row.(*test.Man)
	idMap[v.Id] = v.Name
	return nil
})

myPrint(idMap, true)
Output:

{"1":"测试1","2":"xue1","3":"xue12","4":"xue123","5":"xue1234","6":"xue1234","7":"xue1234","8":"test12"}

func SelectFindOneIgnoreResultCtx added in v1.6.10

func SelectFindOneIgnoreResultCtx(cxt context.Context, db DBer, fields interface{}, tableName string, where string, dest interface{}, fn ...SelectCallBackFn) error

SelectFindOneIgnoreResultCtx 查询结果支持多个, 此使用场景为需要使用 SelectCallBackFn 对每行进行处理 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

func SelectFindWhere added in v1.4.4

func SelectFindWhere(db DBer, fields interface{}, tableName string, dest interface{}, where string, args ...interface{}) error

SelectFindWhere 查询指定内容的 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

Example
var m test.Man
_ = SelectFindWhere(db, "name,addr", "man", &m, "id=?", 1)

myPrint(m, true)
Output:

{"name":"测试1","json_txt":{},"xml_txt":{},"json1_txt":{}}

func SelectFindWhereCtx added in v1.6.10

func SelectFindWhereCtx(ctx context.Context, db DBer, fields interface{}, tableName string, dest interface{}, where string, args ...interface{}) error

SelectFindWhereCtx 查询指定内容的 fields 可以字符串(如: "name,age,addr"), 同时也可以为 struct/struct slice(如: Man/[]Man), 会将 struct 的字段解析为查询内容

func SetLogger

func SetLogger(logger Logger)

SetLogger 设置 logger

func Str added in v1.5.26

func Str(src interface{}) string

Str 将内容转为 string

func UpdateForObj added in v1.3.9

func UpdateForObj(db DBer, tableName string, src interface{}, where string, args ...interface{}) (sql.Result, error)

UpdateForObj 根据对象更新

Example
type Tmp struct {
	Id   int32  `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
	Age  int32  `json:"age,omitempty"`
	Addr string `json:"addr,omitempty"`
}

m := Tmp{
	Name: "xue1234",
	Age:  18,
	Addr: "成都市",
}

_, _ = UpdateForObj(db, "man", m, "id=7")
// rr, _ := r.RowsAffected()
// myPrint(rr, false)

var b Tmp
_ = SelectFindOne(db, "name,age,addr", "man", "id=7", &b)
myPrint(b, true)
Output:

{"name":"xue1234","age":18,"addr":"成都市"}

func UpdateForObjCtx added in v1.6.10

func UpdateForObjCtx(ctx context.Context, db DBer, tableName string, src interface{}, where string, args ...interface{}) (sql.Result, error)

UpdateForObjCtx 根据对象更新

Types

type CommonTable added in v1.6.2

type CommonTable struct {
}

CommonTable 基类

func (*CommonTable) GetAdapterName added in v1.6.2

func (c *CommonTable) GetAdapterName() string

func (*CommonTable) GetField2ColInfoMap added in v1.6.2

func (c *CommonTable) GetField2ColInfoMap(db DBer, printLog bool) (map[string]*TableColInfo, error)

func (*CommonTable) GetParcelFieldSymbol added in v1.6.7

func (c *CommonTable) GetParcelFieldSymbol() byte

func (*CommonTable) GetValueEscapeMap added in v1.6.8

func (c *CommonTable) GetValueEscapeMap() map[byte][]byte

func (*CommonTable) GetValueStrSymbol added in v1.6.8

func (c *CommonTable) GetValueStrSymbol() byte

func (*CommonTable) SetCtx added in v1.6.10

func (c *CommonTable) SetCtx(ctx context.Context)

func (*CommonTable) SetTableName added in v1.6.2

func (c *CommonTable) SetTableName(tableName string)

type ConvStructObj added in v1.6.12

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

func NewConvStruct added in v1.6.12

func NewConvStruct(tagName ...string) *ConvStructObj

NewConvStruct 转换 struct, 将两个对象相同 tag 进行转换, 所有内容进行深拷贝 字段取值默认按 defaultTableTag 来取值

func (*ConvStructObj) Convert added in v1.6.12

func (c *ConvStructObj) Convert() error

Convert 转换, 所有内容进行深拷贝

func (*ConvStructObj) Exclude added in v1.6.12

func (c *ConvStructObj) Exclude(tagVals ...string) *ConvStructObj

Exclude 需要排除 dest 的转换的值 注: 需要晚于 Init 调用

func (*ConvStructObj) Init added in v1.6.12

func (c *ConvStructObj) Init(src, dest interface{}) error

Init 初始化

func (*ConvStructObj) SrcMarshal added in v1.6.12

func (c *ConvStructObj) SrcMarshal(fn marshalFn, tagVal ...string) *ConvStructObj

SrcMarshal 设置需要将 src marshal 转 dest 如: src: obj => dest: string 注: 需要晚于 Init 调用

func (*ConvStructObj) SrcUnmarshal added in v1.6.12

func (c *ConvStructObj) SrcUnmarshal(fn unmarshalFn, tagVal ...string) *ConvStructObj

SrcUnmarshal 设置需要 src unmarshal 转 dest 如: src: string => dest: obj 注: 需要晚于 Init 调用

type DBer

type DBer interface {
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}

DBer

type LRUCache added in v1.5.33

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

func NewLRU added in v1.5.33

func NewLRU(max ...int) *LRUCache

func (*LRUCache) Delete added in v1.5.34

func (l *LRUCache) Delete(key interface{})

func (*LRUCache) Dump added in v1.5.33

func (l *LRUCache) Dump() string

func (*LRUCache) Len added in v1.5.33

func (l *LRUCache) Len() int

Len 长度 return -1 的话, 长度不正确

func (*LRUCache) Load added in v1.5.33

func (l *LRUCache) Load(key interface{}) (data interface{}, ok bool)

func (*LRUCache) SetDelCallBackFn added in v1.5.34

func (l *LRUCache) SetDelCallBackFn(f func(key, value interface{}))

func (*LRUCache) Store added in v1.5.33

func (l *LRUCache) Store(key, value interface{})

type Logger

type Logger interface {
	Info(ctx context.Context, v ...interface{})
	Error(ctx context.Context, v ...interface{})
	Warning(ctx context.Context, v ...interface{})
}

Logger

type MysqlTable added in v1.6.0

type MysqlTable struct {
	CommonTable
	// contains filtered or unexported fields
}

func Mysql added in v1.6.0

func Mysql() *MysqlTable

Mysql

func (*MysqlTable) GetAdapterName added in v1.6.0

func (m *MysqlTable) GetAdapterName() string

func (*MysqlTable) GetField2ColInfoMap added in v1.6.0

func (m *MysqlTable) GetField2ColInfoMap(db DBer, printLog bool) (map[string]*TableColInfo, error)

func (*MysqlTable) SetCtx added in v1.6.10

func (m *MysqlTable) SetCtx(ctx context.Context)

func (*MysqlTable) SetTableName added in v1.6.0

func (m *MysqlTable) SetTableName(name string)

type PgTable added in v1.6.0

type PgTable struct {
	CommonTable
	// contains filtered or unexported fields
}

func Pg added in v1.6.0

func Pg(initArgs ...string) *PgTable

Pg, 默认模式: public initArgs 允许自定义两个参数 initArgs[0] 为 schema initArgs[1] 为 table name (此参数可以忽略, 因为 orm 内部会处理该值)

func (*PgTable) GetAdapterName added in v1.6.0

func (p *PgTable) GetAdapterName() string

func (*PgTable) GetField2ColInfoMap added in v1.6.0

func (p *PgTable) GetField2ColInfoMap(db DBer, printLog bool) (map[string]*TableColInfo, error)

func (*PgTable) GetParcelFieldSymbol added in v1.6.7

func (p *PgTable) GetParcelFieldSymbol() byte

func (*PgTable) GetValueEscapeMap added in v1.6.8

func (p *PgTable) GetValueEscapeMap() map[byte][]byte

func (*PgTable) GetValueStrSymbol added in v1.6.8

func (p *PgTable) GetValueStrSymbol() byte

func (*PgTable) SetCtx added in v1.6.10

func (p *PgTable) SetCtx(ctx context.Context)

func (*PgTable) SetTableName added in v1.6.0

func (p *PgTable) SetTableName(name string)

type SelectCallBackFn added in v1.3.8

type SelectCallBackFn func(_row interface{}) error

SelectCallBackFn 对每行查询结果进行取出处理

type SortByTableColInfo added in v1.6.6

type SortByTableColInfo []*TableColInfo

func (SortByTableColInfo) Len added in v1.6.6

func (a SortByTableColInfo) Len() int

func (SortByTableColInfo) Less added in v1.6.6

func (a SortByTableColInfo) Less(i, j int) bool

func (SortByTableColInfo) Swap added in v1.6.6

func (a SortByTableColInfo) Swap(i, j int)

type SqlStrObj

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

SqlStrObj 拼接 sql 对象

func NewCacheSql

func NewCacheSql(sqlStr string, args ...interface{}) *SqlStrObj

NewCacheSql 初始化, 支持占位符, 此函数比 NewSql 更加高效(有缓存)

  1. 注意: a. 此函数只支持调用一次 GetSqlStr 方法, 如果要调用多次需要使用 NewSql b. 此函数不支持 Clone 方法, 如果要使用 Clone 需要调用 NewSql 说明: 是防止同一对象被两个协程共同使用

  2. 占位符为: ?, 直接根据 args 中类型来自动推动 arg 的类型 第一种用法: 根据 args 中类型来自动推动 arg 的类型 如: NewCacheSql("SELECT username, password FROM sys_user WHERE username = ? AND password = ?", "test", 123) => SELECT username, password FROM sys_user WHERE username = "test" AND password = 123

    第二种用法: 当 arg 为 []int8/int 等 如: NewCacheSql("SELECT username, password FROM sys_user WHERE id IN (?)", []int{1, 2, 3}) => SELECT username, password FROM sys_user WHERE id IN (1,2,3)

  3. 占位符为: ?d, 只会把数字型的字符串转为数字型, 如果是字母的话会被转义为 0, 如: "123" => 123; []string{"1", "2", "3"} => 1,2,3 第一种用法: 当 arg 为字符串时, 又想不加双引号就用这个 如: NewCacheSql("SELECT username, password FROM sys_user WHERE id = ?d", "123") => SELECT username, password FROM sys_user WHERE id = 123

    第二种用法: 当 arg 为 []string, 又想把解析后的单个元素不加引号 如: NewCacheSql("SELECT username, password FROM sys_user WHERE id IN (?d)", []string{"1", "2", "3"}) => SELECT username, password FROM sys_user WHERE id IN (1,2,3)

  4. 占位符为: ?v, 这样会让字符串类型不加引号, 原样输出, 如: "test" => test; 第一种用法: 当 arg 为字符串时, 又想不加双引号就用这个, 注: 只支持 arg 为字符串类型 如: NewCacheSql("SELECT username, password FROM ?v WHERE id = ?d", "sys_user", "123") => SELECT username, password FROM sys_user WHERE id = 123

func NewSql

func NewSql(sqlStr string, args ...interface{}) *SqlStrObj

NewSql 此函数与 NewCacheSql 功能一样, 此函数的使用场景: 1. 需要调用多次 GetSqlStr; 2. 需要调用 Clone

func (*SqlStrObj) Append

func (s *SqlStrObj) Append(sqlStr string, args ...interface{}) *SqlStrObj

Append 将类型追加在最后

func (*SqlStrObj) Clone

func (s *SqlStrObj) Clone() *SqlStrObj

Clone 克隆对象. 注意: 如果是 NewCacheSql 初始化将返回 nil, 需要采用 NewSql 进行初始化

func (*SqlStrObj) FmtSql added in v1.5.32

func (s *SqlStrObj) FmtSql() string

FmtSql 获取格式化后的 sql

func (*SqlStrObj) GetOffset added in v1.6.0

func (s *SqlStrObj) GetOffset(page, size interface{}) (int64, int64)

GetOffset 根据分页获取 offset 注: page, size 只支持 int 系列类型

func (*SqlStrObj) GetSqlStr

func (s *SqlStrObj) GetSqlStr(title ...string) (sqlStr string)

GetSqlStr 获取最终 sqlStr, 默认打印 sqlStr, title[0] 为打印 log 的标题; title[1] 为 sqlStr 的结束符, 默认为 ";" 注意: 通过 NewCacheSql 初始化对象的只能调用一次此函数, 因为调用后会清空所有buf; 通过 NewSql 初始化对象的可以调用多次此函数

func (*SqlStrObj) GetTotalSqlStr

func (s *SqlStrObj) GetTotalSqlStr(title ...string) (findSqlStr string)

GetTotalSqlStr 将查询条件替换为 COUNT(*), 默认打印 sqlStr, title[0] 为打印 log 的标题; title[1] 为 sqlStr 的结束符, 默认为 ";"

func (*SqlStrObj) Int2Str

func (s *SqlStrObj) Int2Str(num int64) string

Int2Str 数字转字符串

func (*SqlStrObj) LimitIsEmpty added in v1.4.8

func (s *SqlStrObj) LimitIsEmpty() bool

LimitIsEmpty 是否添加 limit

func (*SqlStrObj) SetAllLike

func (s *SqlStrObj) SetAllLike(fieldName string, val string) *SqlStrObj

SetAllLike 设置全模糊, 如: xxx LIKE "%test%"

func (*SqlStrObj) SetBetween

func (s *SqlStrObj) SetBetween(fieldName string, leftVal, rightVal interface{}) *SqlStrObj

SetBetween 设置 BETWEEN ? AND ?

func (*SqlStrObj) SetCallerSkip

func (s *SqlStrObj) SetCallerSkip(skip uint8) *SqlStrObj

SetCallerSkip 设置打印调用跳过的层数

func (*SqlStrObj) SetCtx added in v1.6.10

func (s *SqlStrObj) SetCtx(ctx context.Context) *SqlStrObj

SetCtx 设置 context

func (*SqlStrObj) SetEscapeMap added in v1.6.8

func (s *SqlStrObj) SetEscapeMap(escapeMap map[byte][]byte) *SqlStrObj

SetEscapeMap 设置对值的转义处理

func (*SqlStrObj) SetGroupByStr

func (s *SqlStrObj) SetGroupByStr(groupByStr string) *SqlStrObj

SetGroupByStr 设置 groupBy

func (*SqlStrObj) SetHaving added in v1.5.26

func (s *SqlStrObj) SetHaving(having string, args ...interface{}) *SqlStrObj

SetHaving 设置 Having

func (*SqlStrObj) SetInsertValues

func (s *SqlStrObj) SetInsertValues(args ...interface{}) *SqlStrObj

SetInsertValues 批量插入拼接, 如: xxx VALUES (xxx, xxx), (xxx, xxx)

func (*SqlStrObj) SetInsertValuesArgs

func (s *SqlStrObj) SetInsertValuesArgs(sqlStr string, args ...interface{}) *SqlStrObj

SetInsertValuesArgs 支持占位符, 如 SetInsertValuesArg("(?, ?, ?d)", "test", "12345", "123456") 或 SetInsertValuesArg("?, ?, ?d", "test", "12345", "123456") => ("test", "123456", 123456) 批量插入拼接, 如: xxx VALUES (xxx, xxx), (xxx, xxx)

func (*SqlStrObj) SetJoin added in v1.5.11

func (s *SqlStrObj) SetJoin(tableName string, on string, joinType ...uint8) *SqlStrObj

SetJoin 设置 join

func (*SqlStrObj) SetLeftJoin added in v1.6.0

func (s *SqlStrObj) SetLeftJoin(tableName string, on string) *SqlStrObj

SetLeftJoin 设置 left join

func (*SqlStrObj) SetLeftLike

func (s *SqlStrObj) SetLeftLike(fieldName string, val string) *SqlStrObj

SetLeftLike 设置左模糊查询, 如: xxx LIKE "%test"

func (*SqlStrObj) SetLimit

func (s *SqlStrObj) SetLimit(page, size interface{}) *SqlStrObj

SetLimit 设置分页 page 从 1 开始 注: page, size 只支持 int 系列类型

func (*SqlStrObj) SetLimitStr

func (s *SqlStrObj) SetLimitStr(limitStr string) *SqlStrObj

SetLimitStr 字符串来设置

func (*SqlStrObj) SetOrWhere

func (s *SqlStrObj) SetOrWhere(fieldName string, args ...interface{}) *SqlStrObj

SetOrWhere 设置过滤条件, 连接符为 OR 如果 len = 1 的时候, 会拼接成: filed = arg 如果 len = 2 的时候, 会拼接成: filed arg[0] arg[1]

func (*SqlStrObj) SetOrWhereArgs

func (s *SqlStrObj) SetOrWhereArgs(sqlStr string, args ...interface{}) *SqlStrObj

SetOrWhereArgs 支持占位符 如: SetOrWhereArgs("username = ? AND password = ?d", "test", "123") => xxx OR "username = "test" AND password = 123

func (*SqlStrObj) SetOrderByStr

func (s *SqlStrObj) SetOrderByStr(orderByStr string) *SqlStrObj

SetOrderByStr 设置排序

func (*SqlStrObj) SetPrintLog

func (s *SqlStrObj) SetPrintLog(isPrint bool) *SqlStrObj

SetPrintLog 设置是否打印 sqlStr log

func (*SqlStrObj) SetRightJoin added in v1.6.0

func (s *SqlStrObj) SetRightJoin(tableName string, on string) *SqlStrObj

SetRightJoin 设置 right join

func (*SqlStrObj) SetRightLike

func (s *SqlStrObj) SetRightLike(fieldName string, val string) *SqlStrObj

SetRightLike 设置右模糊查询, 如: xxx LIKE "test%"

func (*SqlStrObj) SetStrSymbol added in v1.6.0

func (s *SqlStrObj) SetStrSymbol(strSymbol byte) *SqlStrObj

SetStrSymbol 设置在解析值时字符串符号, 不同的数据库符号不同 如: mysql 字符串值可以用 ""或”; pg 字符串值只能用 ”

func (*SqlStrObj) SetUpdateValue

func (s *SqlStrObj) SetUpdateValue(fieldName string, arg interface{}) *SqlStrObj

SetUpdateValue update 语句中, 设置字段值

func (*SqlStrObj) SetUpdateValueArgs

func (s *SqlStrObj) SetUpdateValueArgs(sqlStr string, arg ...interface{}) *SqlStrObj

SetUpdateValueArgs 支持占位符 如: SetUpdateValueArgs("username = ?, age = ?d", "test", "20") => username = "test", age = 20

func (*SqlStrObj) SetWhere

func (s *SqlStrObj) SetWhere(fieldName string, args ...interface{}) *SqlStrObj

SetWhere 设置过滤条件, 连接符为 AND 如果 len = 1 的时候, 会拼接成: filed = arg 如果 len = 2 的时候, 会拼接成: filed arg[0] arg[1]

func (*SqlStrObj) SetWhereArgs

func (s *SqlStrObj) SetWhereArgs(sqlStr string, args ...interface{}) *SqlStrObj

SetWhereArgs 支持占位符 如: SetWhereArgs("username = ? AND password = ?d", "test", "123") => xxx AND "username = "test" AND password = 123

func (*SqlStrObj) SqlIsEmpty

func (s *SqlStrObj) SqlIsEmpty() bool

SqlIsEmpty sql 是否为空

func (*SqlStrObj) SqlStrLen

func (s *SqlStrObj) SqlStrLen() int

SqlStrLen sql 的总长度

func (*SqlStrObj) UInt2Str

func (s *SqlStrObj) UInt2Str(num uint64) string

UInt2Str

func (*SqlStrObj) ValueIsEmpty

func (s *SqlStrObj) ValueIsEmpty() bool

ValueIsEmpty insert/update 中 value 是否为空

func (*SqlStrObj) ValueStrLen

func (s *SqlStrObj) ValueStrLen() int

ValueStrLen valueBuf 长度

func (*SqlStrObj) WhereIsEmpty

func (s *SqlStrObj) WhereIsEmpty() bool

WhereIsEmpty 判断where条件是否为空

func (*SqlStrObj) WhereStrLen

func (s *SqlStrObj) WhereStrLen() int

WhereStrLen where 条件内容长度

type Table

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

Table 表的信息

func NewTable

func NewTable(db DBer, args ...string) *Table

NewTable 初始化, 通过 sync.Pool 缓存对象来提高性能 注: 使用 INSERT/UPDATE/DELETE/SELECT(SELECT 排除使用 Count)操作后该对象就会被释放, 如果继续使用会出现 panic args 支持两个参数 args[0]: 会解析为 tableName, 这里如果有值, 在进行操作表的时候就会以此表为准, 如果为空时, 在通过对象进行操作时按驼峰规则进行解析表名, 解析规则如: UserInfo => user_info args[1]: 会解析为待解析的 tag, 默认 defaultTableTag

func (*Table) AllLike added in v1.6.0

func (t *Table) AllLike(filedName, value string) *Table

AllLike 全模糊查询

func (*Table) AppendSql added in v1.6.8

func (t *Table) AppendSql(sqlStr string, args ...interface{}) *Table

AppendSql 对 sql 进行自定义追加

func (*Table) Between added in v1.5.7

func (t *Table) Between(filedName string, leftVal, rightVal interface{}) *Table

Between

func (*Table) Clone added in v1.5.36

func (t *Table) Clone() *Table

Clone 克隆对象 说明: 因为都为单线程使用, 不支持并发操作

func (*Table) Count

func (t *Table) Count(total interface{}) error

Count 获取总数

func (*Table) Ctx added in v1.6.10

func (t *Table) Ctx(ctx context.Context) *Table

Ctx 设置 context

func (*Table) Delete

func (t *Table) Delete(deleteObj ...interface{}) *Table

Delete 会以对象中有值得为条件进行删除 如果要排除其他可以调用 Exclude 方法自定义排除

func (*Table) Exclude added in v1.5.7

func (t *Table) Exclude(tags ...string) *Table

Exclude 对于 INSERT/UPDATE/DELETE/SELECT 操作中通过解析对象需要过滤的字段 注: 调用必须优先 Insert/Update/Delete/SelectAuto 操作的方法, 防止通过对象解析字段时失效

func (*Table) Exec

func (t *Table) Exec() (sql.Result, error)

Exec 执行

func (*Table) FindAll

func (t *Table) FindAll(dest interface{}, fn ...SelectCallBackFn) error

FindAll 多行查询 如果没有指定查询条数, 默认 defaultBatchSelectSize dest 支持(struct/单字段/map)切片 fn 支持将查询结果行进行处理, 需要处理每行内容时, fn 回调的 _row 需要类型断言为[切片中的类型]

func (*Table) FindOne

func (t *Table) FindOne(dest ...interface{}) error

FindOne 单行查询 注: 如果为空的话, 会返回 nullRowErr dest 长度 > 1 时, 支持多个字段查询 dest 长度 == 1 时, 支持 struct/单字段/map

func (*Table) FindOneFn added in v1.4.9

func (t *Table) FindOneFn(dest interface{}, fn ...SelectCallBackFn) error

FindOneFn 单行查询 注: 如果为空的话, 会返回 nullRowErr dest 支持 struct/单字段/map fn 支持将查询结果行进行修改, 需要修改的时候 fn 回调的 _row 需要类型断言为[指针]对象才能处理

func (*Table) FindOneIgnoreResult added in v1.5.6

func (t *Table) FindOneIgnoreResult(dest interface{}, fn ...SelectCallBackFn) error

FindOneIgnoreResult 查询结果支持多个, 此使用场景为需要使用 SelectCallBackFn 对每行进行处理 注: 因为查询的结果集为多个, dest 不为切片, 所有这个结果是不准确的 dest 支持 struct/map fn 支持将查询结果行进行修改, 需要修改的时候 fn 回调的 _row 需要类型断言为[指针]对象才能处理

func (*Table) FindWhere added in v1.3.6

func (t *Table) FindWhere(dest interface{}, where string, args ...interface{}) error

FindWhere 如果没有添加查询字段内容, 会根据输入对象进行解析查询 注: 如果为单行查询的话, 当为空的话, 会返回 nullRowErr 如果没有指定查询条数, 默认 defaultBatchSelectSize dest 支持 struct/slice/单字段/map

func (*Table) From added in v1.5.7

func (t *Table) From(tableName string) *Table

From 设置表名

func (*Table) GetCols added in v1.6.6

func (t *Table) GetCols(skipCols ...string) []string

GetCols 获取所有列

func (*Table) GetParcelFieldArr added in v1.6.8

func (t *Table) GetParcelFieldArr(fields ...string) []string

GetParcelFieldArr 获取被包裹字段内容

func (*Table) GetParcelFields added in v1.6.7

func (t *Table) GetParcelFields(fields ...string) string

GetParcelFields 获取数据库包裹字段后的字段内容, 会根据数据库的不同结果不同 如: mysql: `id`; pg: "id"

func (*Table) GetSqlObj

func (t *Table) GetSqlObj() *SqlStrObj

GetSqlObj 获取 SqlStrObj, 方便外部使用该对象的方法

func (*Table) GroupBy added in v1.4.9

func (t *Table) GroupBy(sqlStr string) *Table

GroupBy

func (*Table) Having added in v1.5.26

func (t *Table) Having(sqlStr string, args ...interface{}) *Table

Having

func (*Table) Insert

func (t *Table) Insert(insertObjs ...interface{}) *Table

Insert 提交, 支持批量提交 如果要排除其他可以调用 Exclude 方法自定义排除

func (*Table) InsertIg added in v1.5.35

func (t *Table) InsertIg(insertObj interface{}) *Table

InsertIg insert ignore into xxx 新增忽略 如果要排除其他可以调用 Exclude 方法自定义排除

func (*Table) InsertODKU added in v1.5.35

func (t *Table) InsertODKU(insertObj interface{}, keys ...string) *Table

InsertODKU insert 主键冲突更新 如果要排除其他可以调用 Exclude 方法自定义排除

func (*Table) InsertOfFields added in v1.6.8

func (t *Table) InsertOfFields(cols []string, insertObjs ...interface{}) *Table

InsertOfField 批量新增, 指定新增列

func (*Table) InsertsIg added in v1.6.7

func (t *Table) InsertsIg(insertObjs ...interface{}) *Table

InsertsIg insert ignore into xxx 新增批量忽略 如果要排除其他可以调用 Exclude 方法自定义排除

func (*Table) InsertsODKU added in v1.6.7

func (t *Table) InsertsODKU(insertObjs []interface{}, keys ...string) *Table

InsertsODKU insert 主键冲突更新批量 如果要排除其他可以调用 Exclude 方法自定义排除

func (*Table) IsPrintSql added in v1.3.6

func (t *Table) IsPrintSql(is bool) *Table

IsPrintSql 是否打印 sql

func (*Table) Join added in v1.5.11

func (t *Table) Join(joinTable, on string, joinType ...uint8) *Table

Join 连表查询 说明: 连表查询时, 如果两个表有相同字段名查询结果会出现错误 解决方法: 1. 推荐使用别名来区分; 2. 使用 Query 对结果我们自己进行处理

func (*Table) LefJoin added in v1.6.0

func (t *Table) LefJoin(joinTable, on string) *Table

LeftJoin 连表查询 说明: 连表查询时, 如果两个表有相同字段名查询结果会出现错误 解决方法: 1. 推荐使用别名来区分; 2. 使用 Query 对结果我们自己进行处理

func (*Table) LeftLike added in v1.6.0

func (t *Table) LeftLike(filedName, value string) *Table

LeftLike 左模糊

func (*Table) Limit

func (t *Table) Limit(page, size interface{}) *Table

Limit 分页 会对 page, size 进行校验处理 注: page, size 只支持 int 系列类型

func (*Table) NeedSetSize added in v1.4.9

func (t *Table) NeedSetSize(need bool) *Table

NeedSetSize 查询的时候, 是否需要设置默认 size

func (*Table) OrWhere

func (t *Table) OrWhere(sqlStr string, args ...interface{}) *Table

OrWhere 支持占位符 如: OrWhere("username = ? AND password = ?d", "test", "123") => xxx OR "username = "test" AND password = 123

func (*Table) OrderBy

func (t *Table) OrderBy(sqlStr string) *Table

OrderBy

func (*Table) ParseCol2Val added in v1.6.3

func (t *Table) ParseCol2Val(src interface{}, op ...uint8) ([]string, []interface{}, error)

ParseCol2Val 根据对象解析表的 col 和 val

func (*Table) PrintSqlCallSkip added in v1.4.7

func (t *Table) PrintSqlCallSkip(skip uint8) *Table

PrintSqlCallSkip 用于 sql 打印时候显示调用处的信息

func (*Table) Query

func (t *Table) Query(isNeedCache ...bool) (*sql.Rows, error)

Query 多行查询 注: 返回的 sql.Rows 需要调用 Close, 防止 goroutine 泄露

func (*Table) QueryRowScan

func (t *Table) QueryRowScan(dest ...interface{}) error

QueryRowScan 单行多值查询

func (*Table) Raw

func (t *Table) Raw(sql interface{}) *Table

Raw 执行原生操作 sql sqlStr 或 *SqlStrObj 说明: 在使用时, 设置了 tableName 时查询性能更好, 因为在调用 getScanValues 前需要 通过 tableName 获取表元信息, 再判断字段是否为 NULL, 在没有表元信息时会将所有查询结果都按 NULL 类型处理

func (*Table) RightJoin added in v1.6.0

func (t *Table) RightJoin(joinTable, on string) *Table

RightJoin 连表查询 说明: 连表查询时, 如果两个表有相同字段名查询结果会出现错误 解决方法: 1. 推荐使用别名来区分; 2. 使用 Query 对结果我们自己进行处理

func (*Table) RightLike added in v1.6.0

func (t *Table) RightLike(filedName, value string) *Table

RightLike 右模糊

func (*Table) Select

func (t *Table) Select(fields string) *Table

Select 查询内容 fields 多个通过逗号隔开

func (*Table) SelectAll

func (t *Table) SelectAll() *Table

SelectAll 查询所有字段

func (*Table) SelectAuto added in v1.4.7

func (t *Table) SelectAuto(src interface{}, tableName ...string) *Table

SelectAuto 根据输入类型进行自动推断要查询的字段值 src 如下:

  1. 为 string 的话会被直接解析成查询字段
  2. 为 struct/struct slice 会按 struct 进行解析, 查询字段为 struct 的 tag, 同时会过滤掉非当前表字段名
  3. 其他情况会被解析为查询所有

func (*Table) SelectCount added in v1.4.0

func (t *Table) SelectCount() *Table

SelectCount 查询总数

func (*Table) SetMarshalFn added in v1.5.5

func (t *Table) SetMarshalFn(fn marshalFn, tags ...string) *Table

SetMarshalFn 设置 struct 字段待序列化方法 注: 调用必须优先 Insert/Update 操作的方法, 防止通过对象解析字段时被排除

func (*Table) SetUnmarshalFn added in v1.5.5

func (t *Table) SetUnmarshalFn(fn unmarshalFn, tags ...string) *Table

SetUnmarshalFn 设置 struct 字段待反序列化方法 注: 调用必须优先于 SelectAuto, 防止 SelectAuto 解析时查询字段被排除

func (*Table) TagAlias added in v1.5.8

func (t *Table) TagAlias(tag2AliasMap map[string]string) *Table

TagAlias 设置 struct 字段别名, 默认是按字段的 tag 名 注: 调用必须优先 Insert/Update/Delete/SelectAuto 操作的方法, 防止通过对象解析字段时失效 tag2AliasMap key: struct 的 tag 名, value: 表的列名

func (*Table) TagDefault added in v1.5.38

func (t *Table) TagDefault(tag2DefaultMap map[string]interface{}) *Table

TagDefault 设置 struct 字段默认值 注: 调用必须优先 Insert/Update/Delete/SelectAuto 操作的方法, 防止通过对象解析字段时失效 tag2DefaultMap key: struct 的 tag 名, value: 字段默认值

func (*Table) Tmer added in v1.6.0

func (t *Table) Tmer(obj TableMetaer) *Table

Tmer 设置不同数据库表初始化表方式, 调用的时候应该首先调用 说明: 此方法为局部方法, 如果要全局设置可以 GlobalTmer 如: NewTable(db).Tmer(Pg("man")).xxx

func (*Table) Update

func (t *Table) Update(updateObj interface{}, where string, args ...interface{}) *Table

Update 会更新输入的值 默认排除更新主键, 如果要排除其他可以调用 Exclude 方法自定义排除

func (*Table) Where

func (t *Table) Where(sqlStr string, args ...interface{}) *Table

Where 支持占位符 如: Where("username = ? AND password = ?d", "test", "123") => xxx AND "username = "test" AND password = 123

func (*Table) WhereLike added in v1.5.6

func (t *Table) WhereLike(likeType uint8, filedName, value string) *Table

WhereLike like 查询 likeType ALK-全模糊 RLK-右模糊 LLK-左模糊

type TableColInfo

type TableColInfo struct {
	Index   int            // 字段在表的位置
	Field   string         // 字段名(必须)
	Type    string         // 数据库类型
	Null    string         // 是否为 NULL(建议)
	Key     string         // 索引名(建议)
	Default sql.NullString // 默认值
	Extra   string         // 预留字段
}

TableColInfo 表列详情

func (*TableColInfo) IsPri added in v1.6.0

func (t *TableColInfo) IsPri() bool

IsPri 是否为主键

func (*TableColInfo) NotNull added in v1.6.0

func (t *TableColInfo) NotNull() bool

NotNull 数据库字段非空约束, NO 不能为 NULL, YES 能为 NULL

type TableMetaer added in v1.6.0

type TableMetaer interface {
	GetValueStrSymbol() byte                                                      // 获取值字符串符号
	GetValueEscapeMap() map[byte][]byte                                           // 获取值转义规则
	GetParcelFieldSymbol() byte                                                   // 获取字段包裹符号
	GetAdapterName() string                                                       // 获取 db name
	SetTableName(tableName string)                                                // 方便框架调用设置 tableName 参数
	SetCtx(ctx context.Context)                                                   // 设置 context
	GetField2ColInfoMap(db DBer, printLog bool) (map[string]*TableColInfo, error) // key: field
}

TableMetaer 表元信息, 为了适配不同数据库

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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