spellsql

package module
v1.5.15 Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2022 License: MulanPSL-2.0 Imports: 13 Imported by: 0

README

spellsql Open Source Love

1. 介绍
  • 通过 sync.Pool, strings.Builder 等实现的高性能 sql 拼接工具
  • 具有: 可控打印 sql 最终的 log, 非法字符自动转义, 支持格式化 sql等
  • 支持轻量级 orm, 性能方面接近原生(即: database/sql)
  • 安装:
    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
    
    1. 第二种用法: 当 arg 为 []int, 暂时支持 []int, []int32, []int64
        如: 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");
    
  • 注: 由于这种不会进行转义处理, 所有这种不推荐用于请求输入(外部非法输入)的内容, 会出现 SQL 注入风险; 当我们明确知道参数是干什么的可以使用会简化我们代码, 这里就不进行演示.

3. spellsql 使用
  • 可以参考 getsqlstr_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. 在查询方面的性能接近原生, 其中做几个性能对比: 原生 >= spellsql_orm > gorm (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 类型)
其他
  • 欢迎大佬们指正, 希望大佬给 star

Documentation

Index

Examples

Constants

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 // 右连接
)

Variables

This section is empty.

Functions

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 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 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 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 FindAll added in v1.3.9

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

FindAll 多查询 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 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 FindOneFn added in v1.4.9

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

FindOneFn 单查询 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 Man
_ = FindWhere(db, "man", &m, "id=?", 1)

myPrint(m, true)
Output:

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

func FmtSqlStr

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

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

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 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 IsNullRow added in v1.4.8

func IsNullRow(err error) bool

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

func NewCjLogger

func NewCjLogger() *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 []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 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 Man
_ = SelectFindOne(db, "name,addr", "man", "id=1", &m)

myPrint(m, true)
Output:

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

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 Man
_ = SelectFindOneFn(db, "name,age", "man", "id=1", &m, func(_row interface{}) error {
	v := _row.(*Man)
	v.Name = "被修改了哦"
	return nil
})

myPrint(m, true)
Output:

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

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 Man
var idMap = make(map[int32]string, 10)
_ = SelectFindOneIgnoreResult(db, "id,name", "man", "id<10", &m, func(_row interface{}) error {
	v := _row.(*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 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 Man
_ = SelectFindWhere(db, "name,addr", "man", &m, "id=?", 1)

myPrint(m, true)
Output:

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

func SetLogger

func SetLogger(logger Logger)

SetLogger 设置 logger

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: "成都市",
}

r, _ := 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":"成都市"}

Types

type DBer

type DBer interface {
	Query(query string, args ...interface{}) (*sql.Rows, error)
	QueryRow(query string, args ...interface{}) *sql.Row
	Exec(query string, args ...interface{}) (sql.Result, error)
}

DBer

type Logger

type Logger interface {
	Info(v ...interface{})
	Infof(format string, v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
	Warning(v ...interface{})
	Warningf(format string, v ...interface{})
}

Logger

type SelectCallBackFn added in v1.3.8

type SelectCallBackFn func(_row interface{}) error // 对每行查询结果进行取出处理

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. sqlStr 字符长度必须大于 6 b. 此函数只支持调用一次 GetSqlStr 方法, 如果要调用多次需要使用 NewSql c. 此函数不支持 Clone 方法, 如果要使用 Clone 需要调用 NewSql 说明: b, c 是防止同一对象被两个协程共同使用
  1. 占位符为: ?, 直接根据 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 为 []int, 暂时支持 []int, []int32, []int64 如: 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)

  1. 占位符为: ?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)

  1. 占位符为: ?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) 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 为打印 log 的标题, 对外只支持一个参数, 多传没有用

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) SetGroupByStr

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

SetGroupByStr 设置 groupBy

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) SetLeftLike

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

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

func (*SqlStrObj) SetLimit

func (s *SqlStrObj) SetLimit(page, size int32) *SqlStrObj

SetLimit 设置分页

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) SetRightLike

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

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

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) Between added in v1.5.7

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

Between

func (*Table) Count

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

Count 获取总数

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) 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) Insert

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

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) Limit

func (t *Table) Limit(page int32, size int32) *Table

Limit

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) 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) 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) 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-左模糊

Jump to

Keyboard shortcuts

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