ldb

package module
v2.22.0 Latest Latest
Warning

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

Go to latest
Published: Jan 29, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

README

ldb

下载
 // v1
 go get -u github.com/lontten/ldb
 // v2
 go get -u github.com/lontten/ldb/v2
 
init ldb

	conf := ldb.MysqlConf{
		Host:     "127.0.0.1",
		Port:     "3306",
		DbName:   "test",
		User:     "root",
		Password: "123456",
		Other:    "sslmode=disable TimeZone=Asia/Shanghai",
	}
	DB := ldb.MustConnect(&conf,nil)

type User struct {
	ID   int64
	Name string
	Age  int
}

func (u User) TableConf() *ldb.TableConfContext {
    return ldb.TableConf("t_user").
        PrimaryKeys("id").
        AutoColumn("id")
}

Insert
	user := User{
		Name: "tom",
		Age:  12,
	}
	num, err := ldb.Insert(DB,&user)
	if err != nil {
		return err
	}
	// num=1
	fmt.Println(num)
	//return id
	fmt.Println(user.ID)

update
	user := User{
		ID:   1,
		Name: "tom",
		Age:  12,
	}
	
	//根据主键更新
	num, err := ldb.UpdateByPrimaryKey(DB,&user)
	if err != nil {
		return err
	}
	// num=1
	fmt.Println(num)
	
	user := User{
		Name: "tom",
		Age:  12,
	}
	
	// ldb.W() 条件构造器
	num, err := ldb.Update(DB, &user, ldb.W().
            Eq("id", 1).
            In("id", 1, 2).
            Gt("id", 1).
            IsNull("name").
            Like("name", "abc"),
        )
	if err != nil {
		return err
	}
	// num=1
	fmt.Println(num)
	
	user := User{
		Name: "tom",
		Age:  12,
	}
	
	// 特殊配置
	num, err := ldb.Update(DB, &user, ldb.W(), ldb.E().
            SetNull("age").  // 设置age字段为null
            TableName("user2"). // 临时自定义表名 为 user2
            ShowSql(). // 打印执行 sql
		    NoRun(),  // 不具体执行sql,配合 ShowSql() 用来调试sql
        )
	if err != nil {
		return err
	}
	// num=1
	fmt.Println(num)

delete
 
	
	//根据主键删除
	num, err := db.Delete(User{}).ByPrimaryKey(id)
	if err != nil {
		return err
	}
	// num=1
	fmt.Println(num)
	
	//----------------
	
 
	//根据条件删除
	num, err := db.Delete(User{}).ByModel(NullUser{
		Name: types.NewString("tom"),
	})
	if err != nil {
		return err
	}
	// num=1
	fmt.Println(num)
	//-------------------
	
	 
	
	//使用条件构造器
	num, err := db.Delete(User{}).ByWhere(new(ldb.WhereBuilder).
		Eq("id", user.ID,true).
		NoLike("age", *user.Name, user.Name != nil).
		Ne("age", user.Age,false))
	if err != nil {
		return err
	}
	// num=1
	fmt.Println(num)

###select

	user := User{}
	num, err := db.Select(User{}).ByPrimaryKey(id).ScanOne(&user)
	if err != nil {
		return err
	}
	// num=1
	fmt.Println(num)
	
	fmt.Println(user)
	//-----------------
	
	users := make([]User,0)
	num, err := db.Select(User{}).ByPrimaryKey(id1,id2,id3).ScanList(&users)
	if err != nil {
		return err
	}
	// num=1
	fmt.Println(num)
	
	fmt.Println(user)
	//-----------------
	
	
	users := make([]User, 0)
	num, err := db.Select(User{}).ByModel(NullUser{
		Name: types.NewString("tom"),
		Age:  types.NewInt(12),
	}).ScanList(&users)
	if err != nil {
		return err
	}
	// num 查询的数据个数
	fmt.Println(num)
	
	fmt.Println(users)
	//----------------
	
	user := User{}
	//随机获取一个
	num, err := db.Select(User{}).ByModel(NullUser{
		Name: types.NewString("tom"),
		Age:  types.NewInt(12),
	}).ScanFirst(&user)
	if err != nil {
		return err
	}
	// num 查询的数据个数
	fmt.Println(num)
	
	fmt.Println(user)
	//-----------------------
	
	
	has, err := db.Select(User{}).ByModel(NullUser{
		Name: types.NewString("tom"),
		Age:  types.NewInt(12),
	})
	if err != nil {
		return err
	}
	// has 查询是否存在数据
	fmt.Println(num)
	
	
	
	//----------------------------
	has, err := db.Has(User{}).ByWhere(new(ldb.WhereBuilder).
		Eq("id", user.ID, true).
		NoLike("age", *user.Name, user.Name != nil).
		Ne("age", user.Age, false))
	if err != nil {
		return err
	}
	// has 查询是否存在数据
	fmt.Println(has)

	
	
	
	has, err := db.Has(User{}).ByWhere(new(ldb.WhereBuilder).
		Eq("id", user.ID, true).
		NoLike("age", *user.Name, user.Name != nil).
		Ne("age", user.Age, false))
	if err != nil {
		return err
	}
	// num 查询是否存在数据
	fmt.Println(has)

	
	
	

###tx

	tx := Db.Begin()
    err := tx.Commit()
    err := tx.Rollback()
init ldb pool log

	path := "./log/go.log"
	writer, _ := rotatelogs.New(
		path+".%Y-%m-%d",
		rotatelogs.WithLinkName(path),
		rotatelogs.WithMaxAge(time.Duration(365*24)*time.Hour),
		rotatelogs.WithRotationTime(time.Duration(24)*time.Hour),
	)
	newLogger := log.New(writer, "\r\n", log.LstdFlags)

	var dbName = pg.DbName

	pgConf := ldb.PgConf{
		Host:     pg.Ip,
		Port:     pg.Port,
		DbName:   pg.dbName,
		User:     pg.User,
		Password: pg.Pwd,
		Other:    "sslmode=disable TimeZone=Asia/Shanghai",
	}
	poolConf := ldb.PoolConf{
		MaxIdleCount: 10,
		MaxOpen:      100,
		MaxLifetime:  time.Hour,
		Logger:       newLogger,
	}
	ormConf := ldb.OrmConf{
		TableNamePrefix: "t_",
		PrimaryKeyNames: []string{"id"},
	}

	db := ldb.MustConnect(&pgConf, &poolConf).OrmConf(&ormConf)

Documentation

Index

Constants

View Source
const (
	Eq clauseType = iota
	Neq
	Less
	LessEq
	Greater
	GreaterEq
	Like
	NotLike
	In
	NotIn
	Between
	NotBetween
	IsNull
	IsNotNull
	IsFalse

	PrimaryKeys       // 主键
	FilterPrimaryKeys // 过滤主键

	// Contains 包含
	// pg 独有
	// [1] @< [1,2]
	Contains
)
View Source
const (
	None packType = iota
	Ptr
	Slice
)
View Source
const (
	Invalid atomType = iota
	Atom
	Composite
)
View Source
const (
	LikeAnywhere   likeType = iota // 两边加通配符,匹配任意位置
	LikeEndsWith                   // 左边加通配符,匹配结尾
	LikeStartsWith                 // 右边加通配符,匹配开头
)

Variables

View Source
var (
	ErrNil          = errors.New("nil")
	ErrContainEmpty = errors.New("slice empty")
	ErrNoPkOrUnique = errors.New(" ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification (SQLSTATE 42P10) ")
	ErrNoPk         = errors.New("no set primary key")
	ErrTypePkArgs   = errors.New("type of args is err")
	ErrNeedMultiPk  = errors.New("need multi primary key")
	ErrNoTableName  = errors.New("no set table name")
)
View Source
var ImpScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
View Source
var ImpValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
View Source
var TableConfCache = map[reflect.Type]TableConfContext{}

Functions

func Count

func Count[T any](db Engine, wb *WhereBuilder, extra ...*ExtraContext) (t int64, err error)

Count

func Delete

func Delete[T any](db Engine, wb *WhereBuilder, extra ...*ExtraContext) (int64, error)

func Exec

func Exec(db Engine, query string, args ...any) (int64, error)

func FieldSetValNil added in v2.16.0

func FieldSetValNil(f reflect.Value, fieldName string, val any) error

func First

func First[T any](db Engine, wb *WhereBuilder, extra ...*ExtraContext) (t *T, err error)

First 根据条件获取第一个

func GetOrInsert

func GetOrInsert[T any](db Engine, wb *WhereBuilder, d *T, extra ...*ExtraContext) (*T, error)

GetOrInsert d insert 的 对象, e 通用设置,select 自定义字段

func Has

func Has[T any](db Engine, wb *WhereBuilder, extra ...*ExtraContext) (t bool, err error)

Has

func HasOrInsert

func HasOrInsert(db Engine, wb *WhereBuilder, d any, extra ...*ExtraContext) (bool, error)

HasOrInsert 根据条件查询是否已存在 如果存在,直接返回true,如果不存在返回false,并直接插入 应用场景:例如添加 用户 时,如果名字已存在,返回名字重复,否者正常添加。 d insert 的 对象, e 通用设置,select 自定义字段

func Insert

func Insert(db Engine, v any, extra ...*ExtraContext) (num int64, err error)

Insert 插入或者根据主键冲突更新

func List

func List[T any](db Engine, wb *WhereBuilder, extra ...*ExtraContext) (list []T, err error)

func ListP

func ListP[T any](db Engine, wb *WhereBuilder, extra ...*ExtraContext) (list []*T, err error)

func Rollback added in v2.14.0

func Rollback[T any](result T)

func StmtExec added in v2.20.1

func StmtExec(db Stmter, args ...any) (int64, error)

func ToAnyList added in v2.11.0

func ToAnyList[T any](v []T) []any

func Transaction added in v2.12.0

func Transaction(db Engine, fn func(tx Engine)) (err error)

func TransactionPanic added in v2.20.1

func TransactionPanic(db Engine, fn func(tx Engine))

func TransactionResult added in v2.20.1

func TransactionResult[T any](db Engine, fn func(tx Engine) T) (res T, err error)

func TransactionResultPanic added in v2.20.1

func TransactionResultPanic[T any](db Engine, fn func(tx Engine) T) (res T)

func Update

func Update(db Engine, dest any, wb *WhereBuilder, extra ...*ExtraContext) (int64, error)

func UpdateByPrimaryKey

func UpdateByPrimaryKey(db Engine, dest any, extra ...*ExtraContext) (int64, error)

Types

type ArgArray

type ArgArray []any

func ArrayOf

func ArrayOf(v ...any) ArgArray

type Clause

type Clause struct {
	Type clauseType
	// contains filtered or unexported fields
}

type ColIndex2FieldNameMap

type ColIndex2FieldNameMap []string

sql返回 row 字段下标 对应的 struct 字段名(""表示不接收该列数据)

type Convert added in v2.16.0

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

func ConvertRegister added in v2.16.0

func ConvertRegister[T any](name string, f func(v T) any) Convert

type ConvertCtx added in v2.16.0

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

func (*ConvertCtx) Add added in v2.16.0

func (c *ConvertCtx) Add(v Convert)

func (ConvertCtx) Get added in v2.16.0

func (c ConvertCtx) Get(name string) (any, ConvertFunc)

func (ConvertCtx) Init added in v2.16.0

func (c ConvertCtx) Init() ConvertCtx

type ConvertFunc added in v2.16.0

type ConvertFunc func(o any) any

type ConvertFuncMap added in v2.16.0

type ConvertFuncMap map[string]ConvertFunc

type ConvertValBoxMap added in v2.16.0

type ConvertValBoxMap map[string]any

type DbConfig

type DbConfig interface {
	// contains filtered or unexported methods
}

type Dialecter

type Dialecter interface {
	// contains filtered or unexported methods
}

*

Dialecter 的实现有两种

MysqlDialect PgDialect

内部属性为 ctx *ormContext 有 ormConf OrmConf

dbConfig DbConfig
baseTokens []baseToken

type DuplicateKey

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

func (*DuplicateKey) DoNothing

func (dk *DuplicateKey) DoNothing() *ExtraContext

func (*DuplicateKey) DoReplace

func (dk *DuplicateKey) DoReplace(set ...*SetContext) *ExtraContext

DoReplace 更新字段未设置时,默认更新所有 有值字段

func (*DuplicateKey) DoUpdate

func (dk *DuplicateKey) DoUpdate(set ...*SetContext) *ExtraContext

DoUpdate 更新字段未设置时,默认更新所有 有值字段

type Engine

type Engine interface {

	//用db开启tx事务
	BeginTx(ctx context.Context, opts *sql.TxOptions) (Engine, error)
	Begin() (Engine, error)

	Commit() error
	Rollback() error

	// 解析 WhereBuilder
	ToWhereSQL(w *WhereBuilder, primaryKeyColumnNames ...string) (string, []any, error)
	// contains filtered or unexported methods
}

func Connect

func Connect(c DbConfig, pc *PoolConf) (Engine, error)

func MustConnect

func MustConnect(c DbConfig, pc *PoolConf) Engine

func MustConnectMock

func MustConnectMock(db *sql.DB, c DbConfig) Engine

type EngineBatch

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

批量操作

type ExtraContext

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

ExtraContext 扩展参数

func E

func E() *ExtraContext

func (*ExtraContext) AllowFullTableOp added in v2.19.3

func (e *ExtraContext) AllowFullTableOp() *ExtraContext

AllowFullTableOp 允许全表操作,默认false不允许全表操作

func (*ExtraContext) Convert added in v2.16.0

func (e *ExtraContext) Convert(c Convert) *ExtraContext

Convert 查询结果转换函数

func (*ExtraContext) GetErr

func (e *ExtraContext) GetErr() error

whenUpdateSet 中的错误已经被上抛到 ExtraContext,所以只用判断 ExtraContext 的 err

func (*ExtraContext) Limit

func (e *ExtraContext) Limit(num int64, condition ...bool) *ExtraContext

func (*ExtraContext) NoRun

func (e *ExtraContext) NoRun() *ExtraContext

func (*ExtraContext) Offset

func (e *ExtraContext) Offset(num int64, condition ...bool) *ExtraContext

func (*ExtraContext) OrderBy

func (e *ExtraContext) OrderBy(name string, condition ...bool) *ExtraContext

func (*ExtraContext) OrderDescBy

func (e *ExtraContext) OrderDescBy(name string, condition ...bool) *ExtraContext

func (*ExtraContext) ReturnType

func (e *ExtraContext) ReturnType(typ return_type.ReturnType) *ExtraContext

func (*ExtraContext) Select

func (e *ExtraContext) Select(name ...string) *ExtraContext

Select select 的 字段名,覆盖根据结构体生成的字段列表

func (*ExtraContext) Set

func (e *ExtraContext) Set(name string, value any) *ExtraContext

func (*ExtraContext) SetExpression

func (e *ExtraContext) SetExpression(name string, expression string) *ExtraContext

自定义表达式 SetExpression("name", "substr(time('now'), 12)") // sqlite 设置时分秒

func (*ExtraContext) SetIncrement

func (e *ExtraContext) SetIncrement(name string, num any) *ExtraContext

自增,自减

func (*ExtraContext) SetNow

func (e *ExtraContext) SetNow(name string) *ExtraContext

func (*ExtraContext) SetNull

func (e *ExtraContext) SetNull(name string) *ExtraContext

func (*ExtraContext) ShowSql

func (e *ExtraContext) ShowSql() *ExtraContext

func (*ExtraContext) SkipSoftDelete

func (e *ExtraContext) SkipSoftDelete() *ExtraContext

SkipSoftDelete 跳过软删除

func (*ExtraContext) TableName

func (e *ExtraContext) TableName(name string) *ExtraContext

func (*ExtraContext) WhenDuplicateKey

func (e *ExtraContext) WhenDuplicateKey(name ...string) *DuplicateKey

WhenDuplicateKey 唯一索引冲突,设置索引字段列表; Mysql 不用设置,如果设置了也会直接忽略 Postgresql 必须设置,如果没有设置,则为主键字段

type Index

type Index struct {
	Name      string   // 索引名称
	Unique    bool     // 是否唯一
	Columns   []string // 索引列
	IndexType string   // 索引类型
	Comment   string   // 索引注释
}

type Logger

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

func (*Logger) Fatalln

func (l *Logger) Fatalln(msg string, v ...any)

func (*Logger) Panicln

func (l *Logger) Panicln(msg string, v ...any)

func (*Logger) Println

func (l *Logger) Println(msg string, v ...any)

type MysqlConf

type MysqlConf struct {
	Host     string
	Port     string
	DbName   string
	User     string
	Password string
	Other    string
	Version  MysqlVersion
}

type MysqlDialect

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

type MysqlVersion

type MysqlVersion int
const (
	MysqlVersionLast MysqlVersion = iota
	MysqlVersion5    MysqlVersion = iota

	MysqlVersion8_0_19
	MysqlVersion8_0_20
	MysqlVersion8Last
)

type NativeQueryContext

type NativeQueryContext[T any] struct {
	// contains filtered or unexported fields
}

func NativeQuery added in v2.17.0

func NativeQuery[T any](db Engine, query string, args ...any) *NativeQueryContext[T]

func (*NativeQueryContext[T]) Convert added in v2.17.0

func (q *NativeQueryContext[T]) Convert(c Convert) *NativeQueryContext[T]

func (*NativeQueryContext[T]) List added in v2.17.0

func (q *NativeQueryContext[T]) List() ([]T, error)

func (*NativeQueryContext[T]) ListP added in v2.17.0

func (q *NativeQueryContext[T]) ListP() ([]*T, error)

func (*NativeQueryContext[T]) One added in v2.17.0

func (q *NativeQueryContext[T]) One() (t *T, err error)

func (*NativeQueryContext[T]) ScanList

func (q *NativeQueryContext[T]) ScanList(dest any) (num int64, err error)

func (*NativeQueryContext[T]) ScanOne

func (q *NativeQueryContext[T]) ScanOne(dest any) (num int64, err error)

type OrmConf

type OrmConf struct {
	//po生成文件目录
	PoDir string
	//是否覆盖,默认true
	IsFileOverride bool

	//作者
	Author string
	//是否开启ActiveRecord模式,默认false
	IsActiveRecord bool

	IdType int

	//表名
	//TableNameFun >  tag > TableNamePrefix
	TableNamePrefix string
	TableNameFun    func(t reflect.Value, dest any) string

	//主键 默认为id
	PrimaryKeyNames   []string
	PrimaryKeyNameFun func(v reflect.Value, dest any) []string

	//多租户
	TenantIdFieldName    string                      //多租户的  租户字段名 空字符串极为不启用多租户
	TenantIdValueFun     func() any                  //租户的id值,获取函数
	TenantIgnoreTableFun func(tableName string) bool //该表是否忽略多租户,true忽略该表,即没有多租户
	// contains filtered or unexported fields
}

type PackTyp

type PackTyp struct {
	Typ       packType
	Base      reflect.Value
	SliceBase reflect.Value
}

type PageConfig

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

type PageResult

type PageResult[T any] struct {
	List      []T   `json:"list"`      // 结果
	PageSize  int64 `json:"pageSize"`  // 每页大小
	PageIndex int64 `json:"pageIndex"` // 当前页码
	Total     int64 `json:"total"`     // 总数
	PageNum   int64 `json:"totalPage"` // 总页数
	HasMore   bool  `json:"hasMore"`   // 是否有更多
}

type PageResultP added in v2.18.0

type PageResultP[T any] struct {
	List      []*T  `json:"list"`      // 结果
	PageSize  int64 `json:"pageSize"`  // 每页大小
	PageIndex int64 `json:"pageIndex"` // 当前页码
	Total     int64 `json:"total"`     // 总数
	PageNum   int64 `json:"totalPage"` // 总页数
	HasMore   bool  `json:"hasMore"`   // 是否有更多
}

type PgConf

type PgConf struct {
	Host     string
	Port     string
	DbName   string
	User     string
	Password string
	Other    string
}

type PgDialect

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

type PoolConf

type PoolConf struct {
	MaxIdleCount int           // zero means defaultMaxIdleConns; negative means 0
	MaxOpen      int           // <= 0 means unlimited
	MaxLifetime  time.Duration // maximum amount of time a connection may be reused
	MaxIdleTime  time.Duration // maximum amount of time a connection may be idle before being closed

	Logger *log.Logger
}

type RollbackWithResult added in v2.14.0

type RollbackWithResult[T any] struct {
	Result T
}

type SetContext

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

func Set

func Set() *SetContext

func (*SetContext) Field

func (s *SetContext) Field(name ...string) *SetContext

func (*SetContext) Map

func (s *SetContext) Map(v map[string]any) *SetContext

func (*SetContext) Model

func (s *SetContext) Model(v any) *SetContext

这里不对 model 进行解析 在 initColumnsValueSet 中解析

func (*SetContext) Set

func (s *SetContext) Set(name string, value any) *SetContext

func (*SetContext) SetExpression

func (s *SetContext) SetExpression(name string, expression string) *SetContext

自定义表达式 SetExpression("name", "substr(time('now'), 12)") // sqlite 设置时分秒

func (*SetContext) SetIncrement

func (s *SetContext) SetIncrement(name string, num any) *SetContext

自增,自减

func (*SetContext) SetNull

func (s *SetContext) SetNull(name string) *SetContext

type SqlBuilder

type SqlBuilder[T any] struct {
	// contains filtered or unexported fields
}

func QueryBuild

func QueryBuild[T any](db Engine) *SqlBuilder[T]

func (*SqlBuilder[T]) AppendArg

func (b *SqlBuilder[T]) AppendArg(arg any, conditions ...bool) *SqlBuilder[T]

添加一个 arg,多个断言

func (*SqlBuilder[T]) AppendArgs

func (b *SqlBuilder[T]) AppendArgs(args ...any) *SqlBuilder[T]

添加 多个参数

func (*SqlBuilder[T]) AppendSql

func (b *SqlBuilder[T]) AppendSql(sql string) *SqlBuilder[T]

添加sql语句

func (*SqlBuilder[T]) Arg

func (b *SqlBuilder[T]) Arg(arg any, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) Args

func (b *SqlBuilder[T]) Args(args ...any) *SqlBuilder[T]

func (*SqlBuilder[T]) Between

func (b *SqlBuilder[T]) Between(whereStr string, begin, end any, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) BetweenDateTimeOfDate

func (b *SqlBuilder[T]) BetweenDateTimeOfDate(whereStr string, dateBegin, dateEnd *types.LocalDate, condition ...bool) *SqlBuilder[T]

BetweenDateTimeOfDate 用 Date类型,去查询 DateTime 字段

func (*SqlBuilder[T]) BoolWhere

func (b *SqlBuilder[T]) BoolWhere(condition bool, whereStr string, args ...any) *SqlBuilder[T]

func (*SqlBuilder[T]) BoolWhereIn added in v2.19.2

func (b *SqlBuilder[T]) BoolWhereIn(condition bool, whereStr string, args ...any) *SqlBuilder[T]

func (*SqlBuilder[T]) BoolWhereSqlIn added in v2.19.2

func (b *SqlBuilder[T]) BoolWhereSqlIn(condition bool, whereStr string, args ...any) *SqlBuilder[T]

BoolWhereSqlIn in ? 当参数列表长度为0时,为 1=0 false条件

func (*SqlBuilder[T]) Convert added in v2.16.0

func (b *SqlBuilder[T]) Convert(c Convert, conditions ...bool) *SqlBuilder[T]

Convert 查询结果转换函数

func (*SqlBuilder[T]) CountField

func (b *SqlBuilder[T]) CountField(field string, conditions ...bool) *SqlBuilder[T]

CountField 自定义count字段

func (*SqlBuilder[T]) FakerTotalNum

func (b *SqlBuilder[T]) FakerTotalNum(num int64, conditions ...bool) *SqlBuilder[T]

FakerTotalNum 分页时,直接使用 fakeTotalNum,不再查询实际总数

func (*SqlBuilder[T]) From

func (b *SqlBuilder[T]) From(name string) *SqlBuilder[T]

from 表名 状态从 selectNoSet 变成 selectSet

func (*SqlBuilder[T]) Join

func (b *SqlBuilder[T]) Join(name string, condition ...bool) *SqlBuilder[T]

join 联表

func (*SqlBuilder[T]) LeftJoin

func (b *SqlBuilder[T]) LeftJoin(name string, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) Like

func (b *SqlBuilder[T]) Like(key *string, fields ...string) *SqlBuilder[T]

func (*SqlBuilder[T]) LikeLeft

func (b *SqlBuilder[T]) LikeLeft(key *string, fields ...string) *SqlBuilder[T]

func (*SqlBuilder[T]) LikeRight

func (b *SqlBuilder[T]) LikeRight(key *string, fields ...string) *SqlBuilder[T]

func (*SqlBuilder[T]) Limit

func (b *SqlBuilder[T]) Limit(num int64, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) List added in v2.18.0

func (b *SqlBuilder[T]) List() (list []T, err error)

func (*SqlBuilder[T]) ListP added in v2.18.0

func (b *SqlBuilder[T]) ListP() (list []*T, err error)

func (*SqlBuilder[T]) ListPage added in v2.19.0

func (b *SqlBuilder[T]) ListPage() (dto PageResult[T], err error)

ListPage 查询分页

func (*SqlBuilder[T]) ListPageP added in v2.19.0

func (b *SqlBuilder[T]) ListPageP() (dto PageResultP[T], err error)

ListPageP 查询分页

func (*SqlBuilder[T]) Native

func (b *SqlBuilder[T]) Native(sql string, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) NoGetList

func (b *SqlBuilder[T]) NoGetList(conditions ...bool) *SqlBuilder[T]

NoGetList 分页时,只查询数量,不返回数据列表

func (*SqlBuilder[T]) NoRun

func (b *SqlBuilder[T]) NoRun(conditions ...bool) *SqlBuilder[T]

不执行

func (*SqlBuilder[T]) Offset

func (b *SqlBuilder[T]) Offset(num int64, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) One added in v2.19.0

func (b *SqlBuilder[T]) One() (t *T, err error)

func (*SqlBuilder[T]) OrderBy

func (b *SqlBuilder[T]) OrderBy(name string, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) OrderDescBy

func (b *SqlBuilder[T]) OrderDescBy(name string, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) Page

func (b *SqlBuilder[T]) Page(pageIndex int64, pageSize int64) *SqlBuilder[T]

func (*SqlBuilder[T]) RightJoin

func (b *SqlBuilder[T]) RightJoin(name string, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) ScanList

func (b *SqlBuilder[T]) ScanList(dest *[]T) (rowsNum int64, err error)

func (*SqlBuilder[T]) ScanListP added in v2.19.0

func (b *SqlBuilder[T]) ScanListP(dest *[]*T) (rowsNum int64, err error)

func (*SqlBuilder[T]) ScanOne

func (b *SqlBuilder[T]) ScanOne(dest any) (rowsNum int64, err error)

func (*SqlBuilder[T]) ScanPage

func (b *SqlBuilder[T]) ScanPage(dest *[]T) (dto PageResult[T], err error)

ListPage 查询分页

func (*SqlBuilder[T]) ScanPageP added in v2.19.0

func (b *SqlBuilder[T]) ScanPageP(dest *[]*T) (dto PageResultP[T], err error)

ListPage 查询分页

func (*SqlBuilder[T]) Select

func (b *SqlBuilder[T]) Select(arg string, condition ...bool) *SqlBuilder[T]

添加一个 select 字段,多个断言

func (*SqlBuilder[T]) SelectModel

func (b *SqlBuilder[T]) SelectModel(v any, condition ...bool) *SqlBuilder[T]

添加 多个 select 字段,从 model中

func (*SqlBuilder[T]) ShowSql

func (b *SqlBuilder[T]) ShowSql(conditions ...bool) *SqlBuilder[T]

显示sql

func (*SqlBuilder[T]) Where

func (b *SqlBuilder[T]) Where(whereStr string, condition ...bool) *SqlBuilder[T]

func (*SqlBuilder[T]) WhereBuilder

func (b *SqlBuilder[T]) WhereBuilder(w *WhereBuilder) *SqlBuilder[T]

func (*SqlBuilder[T]) WhereIn

func (b *SqlBuilder[T]) WhereIn(whereStr string, args ...any) *SqlBuilder[T]

func (*SqlBuilder[T]) WhereSqlIn

func (b *SqlBuilder[T]) WhereSqlIn(whereStr string, args ...any) *SqlBuilder[T]

WhereSqlIn in ? 当参数列表长度为0时,为 1=0 false条件

type StmtQueryContext added in v2.17.0

type StmtQueryContext[T any] struct {
	// contains filtered or unexported fields
}

func StmtQuery added in v2.17.0

func StmtQuery[T any](db Stmter, args ...any) *StmtQueryContext[T]

func (*StmtQueryContext[T]) Convert added in v2.17.0

func (q *StmtQueryContext[T]) Convert(c Convert) *StmtQueryContext[T]

func (*StmtQueryContext[T]) List added in v2.17.0

func (q *StmtQueryContext[T]) List() ([]T, error)

func (*StmtQueryContext[T]) ListP added in v2.17.0

func (q *StmtQueryContext[T]) ListP() ([]*T, error)

func (*StmtQueryContext[T]) One added in v2.17.0

func (q *StmtQueryContext[T]) One() (*T, error)

func (*StmtQueryContext[T]) ScanList added in v2.19.0

func (q *StmtQueryContext[T]) ScanList(dest *[]T) (int64, error)

func (*StmtQueryContext[T]) ScanListP added in v2.19.0

func (q *StmtQueryContext[T]) ScanListP(dest *[]T) (int64, error)

func (*StmtQueryContext[T]) ScanOne added in v2.19.0

func (q *StmtQueryContext[T]) ScanOne(dest *T) (int64, error)

type Stmter

type Stmter interface {
	// contains filtered or unexported methods
}

func Prepare

func Prepare(db Engine, query string) (Stmter, error)

type StructValidFieldValueMap

type StructValidFieldValueMap map[string]any

type TableConfContext added in v2.19.0

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

func TableConf

func TableConf(name string) *TableConfContext

func (*TableConfContext) AutoColumn added in v2.19.0

func (c *TableConfContext) AutoColumn(name ...string) *TableConfContext

AutoColumn 会在数据库自动生成的字段 例如: 自增字段、虚拟列、计算列、默认值,等 在insert时,可以设置返回这些字段

func (*TableConfContext) PrimaryKeys added in v2.19.0

func (c *TableConfContext) PrimaryKeys(name ...string) *TableConfContext

PrimaryKeys 设置主键字段,多个字段为复合主键

func (*TableConfContext) Table added in v2.19.0

func (c *TableConfContext) Table(name string) *TableConfContext

Table 设置表名

type WhereBuilder

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

func W

func W() *WhereBuilder

func (*WhereBuilder) And

func (w *WhereBuilder) And(wb *WhereBuilder, condition ...bool) *WhereBuilder

func (*WhereBuilder) Between

func (w *WhereBuilder) Between(query string, arg1, arg2 any, condition ...bool) *WhereBuilder
Between

双闭区间 [a, b], x >= a AND x <= b 时间类型数据不要用 Between

func (*WhereBuilder) BetweenDateTimeOfDate

func (w *WhereBuilder) BetweenDateTimeOfDate(query string, dateBegin, dateEnd *types.LocalDate, condition ...bool) *WhereBuilder

BetweenDateTimeOfDate 用 Date类型,去查询 DateTime 字段

func (*WhereBuilder) BoolIn

func (w *WhereBuilder) BoolIn(condition bool, field string, args ...any) *WhereBuilder

BoolIn IN (?)

func (*WhereBuilder) BoolLikeAny

func (w *WhereBuilder) BoolLikeAny(condition bool, key *string, columns ...string) *WhereBuilder

BoolLikeAny 多个字段,任意一个字段满足 LIKE ?

func (*WhereBuilder) BoolLikeLeftAny

func (w *WhereBuilder) BoolLikeLeftAny(condition bool, key *string, columns ...string) *WhereBuilder

func (*WhereBuilder) BoolLikeRightAny

func (w *WhereBuilder) BoolLikeRightAny(condition bool, key *string, columns ...string) *WhereBuilder

func (*WhereBuilder) BoolNotIn

func (w *WhereBuilder) BoolNotIn(condition bool, field string, args ...any) *WhereBuilder

BoolNotIn NOT IN (?)

func (*WhereBuilder) Contains

func (w *WhereBuilder) Contains(field string, arg any, condition ...bool) *WhereBuilder

Contains pg 独有 [1] @< [1,2]

func (*WhereBuilder) Eq

func (w *WhereBuilder) Eq(field string, arg any, condition ...bool) *WhereBuilder

Eq x = ?

func (*WhereBuilder) FilterPrimaryKey

func (w *WhereBuilder) FilterPrimaryKey(args ...any) *WhereBuilder

func (*WhereBuilder) Gt

func (w *WhereBuilder) Gt(field string, arg any, condition ...bool) *WhereBuilder

Gt x > a

func (*WhereBuilder) Gte

func (w *WhereBuilder) Gte(field string, arg any, condition ...bool) *WhereBuilder

Gte x >= a

func (*WhereBuilder) In

func (w *WhereBuilder) In(field string, args ...any) *WhereBuilder

In IN (?)

func (WhereBuilder) Invalid

func (w WhereBuilder) Invalid() bool

func (*WhereBuilder) IsFalse

func (w *WhereBuilder) IsFalse(field string, condition ...bool) *WhereBuilder

IsFalse x IS FALSE

func (*WhereBuilder) IsNotNull

func (w *WhereBuilder) IsNotNull(field string, condition ...bool) *WhereBuilder

IsNotNull x IS NOT NULL

func (*WhereBuilder) IsNull

func (w *WhereBuilder) IsNull(field string, condition ...bool) *WhereBuilder

IsNull x IS NULL

func (*WhereBuilder) Like

func (w *WhereBuilder) Like(query string, arg string, condition ...bool) *WhereBuilder

Like LIKE ?

func (*WhereBuilder) LikeAny

func (w *WhereBuilder) LikeAny(key *string, columns ...string) *WhereBuilder

LikeAny 多个字段,任意一个字段满足 LIKE ?

func (*WhereBuilder) LikeLeft

func (w *WhereBuilder) LikeLeft(query string, arg string, condition ...bool) *WhereBuilder

func (*WhereBuilder) LikeLeftAny

func (w *WhereBuilder) LikeLeftAny(key *string, columns ...string) *WhereBuilder

LikeLeftAny 多个字段,任意一个字段满足 LIKE ?

func (*WhereBuilder) LikeLeftP

func (w *WhereBuilder) LikeLeftP(query string, arg *string, condition ...bool) *WhereBuilder

LikeLeftP LIKE %?

func (*WhereBuilder) LikeP

func (w *WhereBuilder) LikeP(query string, arg *string, condition ...bool) *WhereBuilder

LikeP LIKE %?%

func (*WhereBuilder) LikeRight

func (w *WhereBuilder) LikeRight(query string, arg string, condition ...bool) *WhereBuilder

func (*WhereBuilder) LikeRightAny

func (w *WhereBuilder) LikeRightAny(key *string, columns ...string) *WhereBuilder

LikeRightAny 多个字段,任意一个字段满足 LIKE ?

func (*WhereBuilder) LikeRightP

func (w *WhereBuilder) LikeRightP(query string, arg *string, condition ...bool) *WhereBuilder

LikeRightP LIKE ?%

func (*WhereBuilder) Lt

func (w *WhereBuilder) Lt(field string, arg any, condition ...bool) *WhereBuilder

Lt x < a

func (*WhereBuilder) Lte

func (w *WhereBuilder) Lte(field string, arg any, condition ...bool) *WhereBuilder

Lte x <= a

func (*WhereBuilder) Map

func (w *WhereBuilder) Map(v any, condition ...bool) *WhereBuilder

func (*WhereBuilder) Model

func (w *WhereBuilder) Model(v any, condition ...bool) *WhereBuilder

过滤 软删除

func (*WhereBuilder) NoLike

func (w *WhereBuilder) NoLike(query string, arg string, condition ...bool) *WhereBuilder

func (*WhereBuilder) NoLikeLeft

func (w *WhereBuilder) NoLikeLeft(query string, arg string, condition ...bool) *WhereBuilder

func (*WhereBuilder) NoLikeLeftP

func (w *WhereBuilder) NoLikeLeftP(query string, arg *string, condition ...bool) *WhereBuilder

func (*WhereBuilder) NoLikeP

func (w *WhereBuilder) NoLikeP(query string, arg *string, condition ...bool) *WhereBuilder

NoLikeP NOT LIKE %?%

func (*WhereBuilder) NoLikeRight

func (w *WhereBuilder) NoLikeRight(query string, arg string, condition ...bool) *WhereBuilder

func (*WhereBuilder) NoLikeRightP

func (w *WhereBuilder) NoLikeRightP(query string, arg *string, condition ...bool) *WhereBuilder

func (*WhereBuilder) Not

func (w *WhereBuilder) Not(condition ...bool) *WhereBuilder

func (*WhereBuilder) NotBetween

func (w *WhereBuilder) NotBetween(query string, arg1, arg2 any, condition ...bool) *WhereBuilder

NotBetween 落在 [a, b] 双闭区间外的记录,即只保留满足 x < a 或 x > b 的数据

func (*WhereBuilder) NotEq

func (w *WhereBuilder) NotEq(field string, arg any, condition ...bool) *WhereBuilder

NotEq x <> ?

func (*WhereBuilder) NotIn

func (w *WhereBuilder) NotIn(field string, args ...any) *WhereBuilder

NotIn NOT IN (?)

func (*WhereBuilder) Or

func (w *WhereBuilder) Or(wb *WhereBuilder, condition ...bool) *WhereBuilder

func (*WhereBuilder) PrimaryKey

func (w *WhereBuilder) PrimaryKey(args ...any) *WhereBuilder

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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