Documentation
¶
Overview ¶
Package sqlx is a set of the simple, flexible and powerful SQL builders with zero-config.
Index ¶
- Constants
- Variables
- func BindToMapBool[M ~map[K]bool, K comparable](rows Rows, initcap int) (M, error)
- func BindToMapEmptyStruct[M ~map[K]struct{}, K comparable](rows Rows, initcap int) (M, error)
- func BindToMapKV[M ~map[K]V, K comparable, V any](rows Rows, initcap int) (m M, err error)
- func BuildOp(ab *ArgsBuilder, op op.Op) string
- func BuildOper(ab *ArgsBuilder, op op.Oper) string
- func CheckErrNoRows(err error) (exist bool, e error)
- func Count(field string) string
- func CountDistinct(field string) string
- func DecodeMap[M ~map[string]T, T any](m *M, src any) error
- func DecodeStrings[S ~[]string](s *S, src any, sep string) error
- func EncodeMap[M ~map[string]T, T any](m M) (string, error)
- func RegisterDialect(dialect Dialect, force bool)
- func RegisterOpBuilder(op string, builder OpBuilder)
- func ScanColumnsToStruct(scan func(...any) error, columns []string, s any) (err error)
- func ScanRow(scan func(dests ...any) error, dests ...any) error
- func SetConnURLLocation(connURL string, loc *time.Location) string
- func Sum(field string) string
- func Today() time.Time
- func TryBindToMapBool[M ~map[K]bool, K comparable](rows Rows, err error, initcap int) (m M, e error)
- func TryBindToMapEmptyStruct[M ~map[K]struct{}, K comparable](rows Rows, err error, initcap int) (m M, e error)
- func TryBindToMapKV[M ~map[K]V, K comparable, V any](rows Rows, err error, initcap int) (m M, e error)
- type ArgsBuilder
- type Base
- type Config
- type DB
- func (db *DB) Delete(tables ...string) *DeleteBuilder
- func (db *DB) Exec(query string, args ...any) (r sql.Result, err error)
- func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (r sql.Result, err error)
- func (db *DB) GetDialect() Dialect
- func (db *DB) Insert() *InsertBuilder
- func (db *DB) Intercept(sql string, args []any) (string, []any, error)
- func (db *DB) NewTable(name string) Table
- func (db *DB) Query(query string, args ...any) (rows *sql.Rows, err error)
- func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (rows *sql.Rows, err error)
- func (db *DB) QueryRow(query string, args ...any) *sql.Row
- func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
- func (db *DB) QueryRows(query string, args ...any) (Rows, error)
- func (db *DB) QueryRowsContext(ctx context.Context, query string, args ...any) (rows Rows, err error)
- func (db *DB) QueryRowx(query string, args ...any) Row
- func (db *DB) QueryRowxContext(ctx context.Context, query string, args ...any) Row
- func (db *DB) Reset(other *DB)
- func (db *DB) Select(column string) *SelectBuilder
- func (db *DB) SelectAlias(column, alias string) *SelectBuilder
- func (db *DB) SelectStruct(s any) *SelectBuilder
- func (db *DB) SelectStructWithTable(s any, table string) *SelectBuilder
- func (db *DB) Selects(columns ...string) *SelectBuilder
- func (db *DB) Update(table ...string) *UpdateBuilder
- type DeleteBuilder
- func (b *DeleteBuilder) Build() (sql string, args *ArgsBuilder)
- func (b *DeleteBuilder) Comment(comment string) *DeleteBuilder
- func (b *DeleteBuilder) Exec() (sql.Result, error)
- func (b *DeleteBuilder) ExecContext(ctx context.Context) (sql.Result, error)
- func (b *DeleteBuilder) From(table string, alias ...string) *DeleteBuilder
- func (b *DeleteBuilder) FromAlias(table string, alias string) *DeleteBuilder
- func (b *DeleteBuilder) JoinFull(table, alias string, ons ...JoinOn) *DeleteBuilder
- func (b *DeleteBuilder) JoinFullOuter(table, alias string, ons ...JoinOn) *DeleteBuilder
- func (b *DeleteBuilder) JoinLeft(table, alias string, ons ...JoinOn) *DeleteBuilder
- func (b *DeleteBuilder) JoinLeftOuter(table, alias string, ons ...JoinOn) *DeleteBuilder
- func (b *DeleteBuilder) JoinRight(table, alias string, ons ...JoinOn) *DeleteBuilder
- func (b *DeleteBuilder) JoinRightOuter(table, alias string, ons ...JoinOn) *DeleteBuilder
- func (b *DeleteBuilder) SetDB(db *DB) *DeleteBuilder
- func (b *DeleteBuilder) String() string
- func (b *DeleteBuilder) Table(table string) *DeleteBuilder
- func (b *DeleteBuilder) Where(andConditions ...op.Condition) *DeleteBuilder
- func (b *DeleteBuilder) WhereNamedArgs(andArgs ...sql.NamedArg) *DeleteBuilder
- type Dialect
- type Executor
- type InsertBuilder
- func (b *InsertBuilder) Build() (sql string, args *ArgsBuilder)
- func (b *InsertBuilder) Columns(columns ...string) *InsertBuilder
- func (b *InsertBuilder) Comment(comment string) *InsertBuilder
- func (b *InsertBuilder) Exec() (sql.Result, error)
- func (b *InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error)
- func (b *InsertBuilder) IgnoreInto(table string) *InsertBuilder
- func (b *InsertBuilder) Into(table string) *InsertBuilder
- func (b *InsertBuilder) NamedValues(nvs ...sql.NamedArg) *InsertBuilder
- func (b *InsertBuilder) Ops(ops ...op.Op) *InsertBuilder
- func (b *InsertBuilder) ReplaceInto(table string) *InsertBuilder
- func (b *InsertBuilder) SetDB(db *DB) *InsertBuilder
- func (b *InsertBuilder) String() string
- func (b *InsertBuilder) Struct(s any) *InsertBuilder
- func (b *InsertBuilder) Values(values ...any) *InsertBuilder
- type Interceptor
- type InterceptorFunc
- type Interceptors
- type JoinOn
- type Map
- type OpBuilder
- type OpBuilderFunc
- type Opener
- type Oper
- func (o Oper[T]) Add(obj T) (err error)
- func (o Oper[T]) AddContext(ctx context.Context, obj T) (err error)
- func (o Oper[T]) AddContextWithId(ctx context.Context, obj T) (id int64, err error)
- func (o Oper[T]) AddWithId(obj T) (id int64, err error)
- func (o Oper[T]) Count(conds ...op.Condition) (total int, err error)
- func (o Oper[T]) CountContext(ctx context.Context, conds ...op.Condition) (total int, err error)
- func (o Oper[T]) CountDistinct(field string, conds ...op.Condition) (total int, err error)
- func (o Oper[T]) CountDistinctContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)
- func (o Oper[T]) Delete(conds ...op.Condition) (err error)
- func (o Oper[T]) DeleteById(id int64) error
- func (o Oper[T]) DeleteContext(ctx context.Context, conds ...op.Condition) error
- func (o Oper[T]) Exist(conds ...op.Condition) (exist bool, err error)
- func (o Oper[T]) ExistContext(ctx context.Context, conds ...op.Condition) (exist bool, err error)
- func (o Oper[T]) Get(sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)
- func (o Oper[T]) GetById(id int64) (v T, ok bool, err error)
- func (o Oper[T]) GetContext(ctx context.Context, sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)
- func (o Oper[T]) GetRow(ctx context.Context, columns any, sort op.Sorter, conds ...op.Condition) Row
- func (o Oper[T]) GetRowContext(ctx context.Context, columns any, sort op.Sorter, conds ...op.Condition) Row
- func (o Oper[T]) GetRows(columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (Rows, error)
- func (o Oper[T]) GetRowsContext(ctx context.Context, columns any, sort op.Sorter, page op.Paginator, ...) (rows Rows, err error)
- func (o Oper[T]) Gets(sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)
- func (o Oper[T]) GetsContext(ctx context.Context, sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)
- func (o Oper[T]) MakeSlice(cap int64) []T
- func (o Oper[T]) Query(page, pageSize int64, conds ...op.Condition) ([]T, error)
- func (o Oper[T]) QueryContext(ctx context.Context, page, pageSize int64, conds ...op.Condition) ([]T, error)
- func (o Oper[T]) Select(columns any, conds ...op.Condition) *SelectBuilder
- func (o Oper[T]) SoftCount(conds ...op.Condition) (total int, err error)
- func (o Oper[T]) SoftCountContext(ctx context.Context, conds ...op.Condition) (total int, err error)
- func (o Oper[T]) SoftCountDistinct(field string, conds ...op.Condition) (total int, err error)
- func (o Oper[T]) SoftCountDistinctContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)
- func (o Oper[T]) SoftDelete(conds ...op.Condition) error
- func (o Oper[T]) SoftDeleteById(id int64) error
- func (o Oper[T]) SoftDeleteContext(ctx context.Context, conds ...op.Condition) error
- func (o Oper[T]) SoftExist(conds ...op.Condition) (exist bool, err error)
- func (o Oper[T]) SoftExistContext(ctx context.Context, conds ...op.Condition) (exist bool, err error)
- func (o Oper[T]) SoftGet(sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)
- func (o Oper[T]) SoftGetById(id int64) (v T, ok bool, err error)
- func (o Oper[T]) SoftGetContext(ctx context.Context, sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)
- func (o Oper[T]) SoftGetRows(columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (Rows, error)
- func (o Oper[T]) SoftGetRowsContext(ctx context.Context, columns any, sort op.Sorter, page op.Paginator, ...) (Rows, error)
- func (o Oper[T]) SoftGets(sort op.Sorter, page op.Paginator, conds ...op.Condition) ([]T, error)
- func (o Oper[T]) SoftGetsContext(ctx context.Context, sort op.Sorter, page op.Paginator, conds ...op.Condition) ([]T, error)
- func (o Oper[T]) SoftQuery(page, pageSize int64, conds ...op.Condition) ([]T, error)
- func (o Oper[T]) SoftQueryContext(ctx context.Context, page, pageSize int64, conds ...op.Condition) ([]T, error)
- func (o Oper[T]) SoftSelect(columns any, conds ...op.Condition) *SelectBuilder
- func (o Oper[T]) SoftSum(field string, conds ...op.Condition) (total int, err error)
- func (o Oper[T]) SoftSumContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)
- func (o Oper[T]) SoftUpdate(updater op.Updater, conds ...op.Condition) (err error)
- func (o Oper[T]) SoftUpdateById(id int64, updaters ...op.Updater) error
- func (o Oper[T]) SoftUpdateContext(ctx context.Context, updater op.Updater, conds ...op.Condition) error
- func (o Oper[T]) Sum(field string, conds ...op.Condition) (int, error)
- func (o Oper[T]) SumContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)
- func (o Oper[T]) Update(updater op.Updater, conds ...op.Condition) error
- func (o Oper[T]) UpdateById(id int64, updaters ...op.Updater) error
- func (o Oper[T]) UpdateContext(ctx context.Context, updater op.Updater, conds ...op.Condition) error
- func (o Oper[T]) WithDB(db *DB) Oper[T]
- func (o Oper[T]) WithSoftCondition(softcond op.Condition) Oper[T]
- func (o Oper[T]) WithSoftDeleteUpdater(softDeleteUpdater func(context.Context) op.Updater) Oper[T]
- func (o Oper[T]) WithTable(table Table) Oper[T]
- type Operation
- func (o Operation[T]) Add(obj T) (err error)
- func (o Operation[T]) AddContext(ctx context.Context, obj T) (err error)
- func (o Operation[T]) AddContextWithId(ctx context.Context, obj T) (id int64, err error)
- func (o Operation[T]) AddWithId(obj T) (id int64, err error)
- func (o Operation[T]) Count(conds ...op.Condition) (total int, err error)
- func (o Operation[T]) CountDistinct(field string, conds ...op.Condition) (total int, err error)
- func (o Operation[T]) DeleteById(id int64) error
- func (o Operation[T]) DisableById(id int64) (err error)
- func (o Operation[T]) EnableById(id int64) (err error)
- func (o Operation[T]) Exist(conds ...op.Condition) (exist bool, err error)
- func (o Operation[T]) Get(conds ...op.Condition) (obj T, ok bool, err error)
- func (o Operation[T]) GetById(id int64) (v T, ok bool, err error)
- func (o Operation[T]) GetContext(ctx context.Context, conds ...op.Condition) (obj T, ok bool, err error)
- func (o Operation[T]) Gets(sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)
- func (o Operation[T]) GetsContext(ctx context.Context, sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)
- func (o Operation[T]) MakeSlice(cap int64) []T
- func (o Operation[T]) Query(page, pageSize int64, conds ...op.Condition) ([]T, error)
- func (o Operation[T]) Remove(conds ...op.Condition) (err error)
- func (o Operation[T]) RemoveContext(ctx context.Context, conds ...op.Condition) (err error)
- func (o Operation[T]) Update(updater op.Updater, conds ...op.Condition) error
- func (o Operation[T]) UpdateById(id int64, updaters ...op.Updater) error
- func (o Operation[T]) UpdateContext(ctx context.Context, updater op.Updater, conds ...op.Condition) error
- func (o Operation[T]) UpdateRemove(conds ...op.Condition) (err error)
- func (o Operation[T]) UpdateRemoveContext(ctx context.Context, conds ...op.Condition) (err error)
- func (o Operation[T]) WithDB(db *DB) Operation[T]
- func (o Operation[T]) WithSoftDeleteUpdater(softDeleteUpdater func(context.Context) op.Updater) Operation[T]
- func (o Operation[T]) WithTable(table Table) Operation[T]
- type Order
- type Row
- type Rows
- func (r Rows) BindSlice(slice any) (err error)
- func (r Rows) Scan(dests ...any) (err error)
- func (r Rows) ScanSlice(slice any) (err error)
- func (r Rows) ScanStruct(s any) (err error)
- func (r Rows) ScanStructWithColumns(s any, columns ...string) (err error)
- func (r Rows) TryBindSlice(slice any, err error) error
- type SelectBuilder
- func (b *SelectBuilder) BindRow(dest ...any) (bool, error)
- func (b *SelectBuilder) BindRowContext(c context.Context, dest ...any) (bool, error)
- func (b *SelectBuilder) BindRowStruct(dest any) (bool, error)
- func (b *SelectBuilder) BindRowStructContext(c context.Context, dest any) (bool, error)
- func (b *SelectBuilder) BindRows(slice any) error
- func (b *SelectBuilder) BindRowsContext(ctx context.Context, slice any) error
- func (b *SelectBuilder) Build() (sql string, args *ArgsBuilder)
- func (b *SelectBuilder) Comment(comment string) *SelectBuilder
- func (b *SelectBuilder) Distinct() *SelectBuilder
- func (b *SelectBuilder) From(table string) *SelectBuilder
- func (b *SelectBuilder) FromAlias(table, alias string) *SelectBuilder
- func (b *SelectBuilder) Froms(tables ...string) *SelectBuilder
- func (b *SelectBuilder) GroupBy(columns ...string) *SelectBuilder
- func (b *SelectBuilder) Having(exprs ...string) *SelectBuilder
- func (b *SelectBuilder) Join(table, alias string, ons ...JoinOn) *SelectBuilder
- func (b *SelectBuilder) JoinFull(table, alias string, ons ...JoinOn) *SelectBuilder
- func (b *SelectBuilder) JoinFullOuter(table, alias string, ons ...JoinOn) *SelectBuilder
- func (b *SelectBuilder) JoinLeft(table, alias string, ons ...JoinOn) *SelectBuilder
- func (b *SelectBuilder) JoinLeftOuter(table, alias string, ons ...JoinOn) *SelectBuilder
- func (b *SelectBuilder) JoinRight(table, alias string, ons ...JoinOn) *SelectBuilder
- func (b *SelectBuilder) JoinRightOuter(table, alias string, ons ...JoinOn) *SelectBuilder
- func (b *SelectBuilder) Limit(limit int64) *SelectBuilder
- func (b *SelectBuilder) Offset(offset int64) *SelectBuilder
- func (b *SelectBuilder) OrderBy(column string, order Order) *SelectBuilder
- func (b *SelectBuilder) OrderByAsc(column string) *SelectBuilder
- func (b *SelectBuilder) OrderByDesc(column string) *SelectBuilder
- func (b *SelectBuilder) Paginate(pageNum, pageSize int64) *SelectBuilder
- func (b *SelectBuilder) Paginator(page op.Paginator) *SelectBuilder
- func (b *SelectBuilder) Query() (Rows, error)
- func (b *SelectBuilder) QueryContext(ctx context.Context) (Rows, error)
- func (b *SelectBuilder) QueryRow() Row
- func (b *SelectBuilder) QueryRowContext(ctx context.Context) Row
- func (b *SelectBuilder) Select(column string) *SelectBuilder
- func (b *SelectBuilder) SelectAlias(column, alias string) *SelectBuilder
- func (b *SelectBuilder) SelectCount(field string) *SelectBuilder
- func (b *SelectBuilder) SelectCountDistinct(field string) *SelectBuilder
- func (b *SelectBuilder) SelectStruct(s any) *SelectBuilder
- func (b *SelectBuilder) SelectStructWithTable(s any, table string) *SelectBuilder
- func (b *SelectBuilder) SelectedColumns() []string
- func (b *SelectBuilder) SelectedFullColumns() []string
- func (b *SelectBuilder) Selects(columns ...string) *SelectBuilder
- func (b *SelectBuilder) SetDB(db *DB) *SelectBuilder
- func (b *SelectBuilder) Sort(sorts ...op.Sorter) *SelectBuilder
- func (b *SelectBuilder) String() string
- func (b *SelectBuilder) Sum(field string) *SelectBuilder
- func (b *SelectBuilder) Where(andConditions ...op.Condition) *SelectBuilder
- func (b *SelectBuilder) WhereNamedArgs(andArgs ...sql.NamedArg) *SelectBuilder
- type SqlCollector
- func (c *SqlCollector) Intercept(sql string, args []any) (string, []any, error)
- func (c *SqlCollector) SetEnableFunc(enablef func() bool) *SqlCollector
- func (c *SqlCollector) SetEnabled(enabled bool) *SqlCollector
- func (c *SqlCollector) SetFilterFunc(filterf func(sql string) bool) *SqlCollector
- func (c *SqlCollector) Sqls() []string
- type Strings
- type Table
- func (t Table) DeleteFrom(conds ...op.Condition) *DeleteBuilder
- func (t Table) GetDB() *DB
- func (t Table) InsertInto() *InsertBuilder
- func (t Table) Select(column string) *SelectBuilder
- func (t Table) SelectAlias(column, alias string) *SelectBuilder
- func (t Table) SelectStruct(s any) *SelectBuilder
- func (t Table) SelectStructWithTable(s any, table string) *SelectBuilder
- func (t Table) Selects(columns ...string) *SelectBuilder
- func (t *Table) SetDB(db *DB)
- func (t Table) String() string
- func (t Table) Update(updaters ...op.Updater) *UpdateBuilder
- func (t Table) WithDB(db *DB) Table
- type Time
- type UpdateBuilder
- func (b *UpdateBuilder) Build() (sql string, args *ArgsBuilder)
- func (b *UpdateBuilder) Comment(comment string) *UpdateBuilder
- func (b *UpdateBuilder) Exec() (sql.Result, error)
- func (b *UpdateBuilder) ExecContext(ctx context.Context) (sql.Result, error)
- func (b *UpdateBuilder) From(table string, alias ...string) *UpdateBuilder
- func (b *UpdateBuilder) FromAlias(table string, alias string) *UpdateBuilder
- func (b *UpdateBuilder) JoinFull(table, alias string, ons ...JoinOn) *UpdateBuilder
- func (b *UpdateBuilder) JoinFullOuter(table, alias string, ons ...JoinOn) *UpdateBuilder
- func (b *UpdateBuilder) JoinLeft(table, alias string, ons ...JoinOn) *UpdateBuilder
- func (b *UpdateBuilder) JoinLeftOuter(table, alias string, ons ...JoinOn) *UpdateBuilder
- func (b *UpdateBuilder) JoinRight(table, alias string, ons ...JoinOn) *UpdateBuilder
- func (b *UpdateBuilder) JoinRightOuter(table, alias string, ons ...JoinOn) *UpdateBuilder
- func (b *UpdateBuilder) Set(updaters ...op.Updater) *UpdateBuilder
- func (b *UpdateBuilder) SetDB(db *DB) *UpdateBuilder
- func (b *UpdateBuilder) SetNamedArg(args ...sql.NamedArg) *UpdateBuilder
- func (b *UpdateBuilder) String() string
- func (b *UpdateBuilder) Table(table string) *UpdateBuilder
- func (b *UpdateBuilder) TableAlias(table string, alias string) *UpdateBuilder
- func (b *UpdateBuilder) Where(andConditions ...op.Condition) *UpdateBuilder
- func (b *UpdateBuilder) WhereNamedArgs(andArgs ...sql.NamedArg) *UpdateBuilder
Examples ¶
Constants ¶
const ( // DateZero is the ZERO of the sql date. DateZero = "0000-00-00" // TimeZero is the ZERO of the sql time. TimeZero = "00:00:00" // DateTimeZero is the ZERO of the sql datetime. DateTimeZero = "0000-00-00 00:00:00" )
const SliceSep = ","
SliceSep is used to combine a string slice to a string.
Variables ¶
var DefaultArgsCap = 32
DefaultArgsCap is the default capacity to be allocated for ArgsBuilder.
var DefaultBufferCap = 256
DefaultBufferCap is the default capacity to be allocated for buffer from pool.
var DefaultConfigs = []Config{MaxOpenConns(0), ConnMaxIdleTime(time.Minute * 5)}
DefaultConfigs is the default configs.
var DefaultDB = new(DB)
DefaultDB is the default global DB.
var DefaultDeletedAt = op.Key("deleted_at")
var DefaultDialect = MySQL
DefaultDialect is the default dialect.
var DefaultSliceCap = 16
var DefaultSqlCollector = NewSqlCollector()
DefaultSqlCollector is the default sql collector.
var Sep = "_"
Sep is the separator by the select struct.
Functions ¶
func BindToMapBool ¶ added in v0.35.0
func BindToMapBool[M ~map[K]bool, K comparable](rows Rows, initcap int) (M, error)
BindToMapBool scans one column as key, and insert it with the value true into m.
NOTICE: It will close the rows.
func BindToMapEmptyStruct ¶ added in v0.35.0
func BindToMapEmptyStruct[M ~map[K]struct{}, K comparable](rows Rows, initcap int) (M, error)
BindToMapEmptyStruct scans one column as key, and insert it with the value struct{}{} into m.
NOTICE: It will close the rows.
func BindToMapKV ¶ added in v0.35.0
func BindToMapKV[M ~map[K]V, K comparable, V any](rows Rows, initcap int) (m M, err error)
BindToMapKV scans two columns as key and value, and inserts them into m.
NOTICE: It will close the rows.
func BuildOp ¶ added in v0.27.0
func BuildOp(ab *ArgsBuilder, op op.Op) string
BuildOp builds the operation.
func BuildOper ¶ added in v0.27.0
func BuildOper(ab *ArgsBuilder, op op.Oper) string
BuildOper is equal to BuildOp(ab, op.Operation()).
func CheckErrNoRows ¶
CheckErrNoRows extracts the error sql.ErrNoRows as the bool, which returns
- (true, nil) if err is equal to nil
- (false, nil) if err is equal to sql.ErrNoRows
- (false, err) if err is equal to others
func CountDistinct ¶ added in v0.30.0
CountDistinct returns a COUNT(DISTINCT field).
func DecodeStrings ¶ added in v0.39.0
DecodeStrings decodes a string slice from string or []byte.
func RegisterDialect ¶
RegisterDialect registers the Dialect with the name.
If the name has been registered, it will panic. But you can set force to true to ignore it.
func RegisterOpBuilder ¶ added in v0.27.0
RegisterOpBuilder registers the operation builder.
func ScanColumnsToStruct ¶
ScanColumnsToStruct scans the columns into the fields of the struct s, which supports the tag named "sql" to modify the field name.
If the value of the tag is "-", however, the field will be ignored. If the tag contains the attribute "notpropagate", for the embeded struct, do not scan the fields of the embeded struct.
func ScanRow ¶
ScanRow uses the function scan to scan the sql row into dests, which may be used as a proxy of the function sql.Row.Scan or sql.Rows.Scan.
If the dest value is the basic builtin types as follow, it will be wrapped to support the sql NULL and the converting from other types.
*time.Duration: string: time.ParseDuration(src) []byte: time.ParseDuration(string(src)) int64: time.Duration(src) * time.Millisecond float64: time.Duration(src * float64(time.Second)) *time.Time: int64: time.Unix(src, 0).In(Location) float64: time.Unix(Integer, Fraction).In(Location) string: time.ParseInLocation(DatetimeLayout, src, Location)) []byte: time.ParseInLocation(DatetimeLayout, string(src), Location)) time.Time: src *bool: bool: src int64: src!=0 float64: src!=0 string: strconv.ParseBool(src) []byte: len(src)==1: src[0] != '\x00' len(src)!=1: strconv.ParseBool(string(src)) *string: string: src []byte: string(src) bool: "true" or "false" int64: strconv.FormatInt(src, 10) float64: strconv.FormatFloat(src, 'f', -1, 64) time.Time: src.In(Location).Format(DatetimeLayout) *float32, *float64: bool: true=>1, false=>0 int64: floatXX(src) float64: floatXX(src) string: strconv.ParseFloat(src, 64) []byte: strconv.ParseFloat(string(src), 64) *int, *int8, *int16, *int32, *int64: bool: true=>1, false=>0 int64: intXX(src) float64: intXX(src) string: strconv.ParseInt(src, 10, 64) []byte: strconv.ParseInt(string(src), 10, 64) time.Time: src.Unix() only for int/int64 *uint, *uint8, *uint16, *uint32, *uint64: bool: true=>1, false=>0 int64: uintXX(src) float64: uintXX(src) string: strconv.ParseUint(src, 10, 64) []byte: strconv.ParseUint(string(src), 10, 64) time.Time: src.Unix() only for uint/uint64
func SetConnURLLocation ¶
SetConnURLLocation sets the argument "loc" in the connection url if missing.
If loc is nil, use Location instead.
func TryBindToMapBool ¶ added in v0.35.0
func TryBindToMapBool[M ~map[K]bool, K comparable](rows Rows, err error, initcap int) (m M, e error)
TryBindToMapBool is the same as BindToMapBool, but calls it only if err==nil.
func TryBindToMapEmptyStruct ¶ added in v0.35.0
func TryBindToMapEmptyStruct[M ~map[K]struct{}, K comparable](rows Rows, err error, initcap int) (m M, e error)
TryBindToMapEmptyStruct is the same as BindToMapEmptyStruct, but calls it only if err==nil.
func TryBindToMapKV ¶ added in v0.35.0
func TryBindToMapKV[M ~map[K]V, K comparable, V any](rows Rows, err error, initcap int) (m M, e error)
TryBindToMapKV is the same as BindToMapKV, but calls it only if err==nil.
Types ¶
type ArgsBuilder ¶
type ArgsBuilder struct { Dialect // contains filtered or unexported fields }
ArgsBuilder is used to build the arguments.
func GetArgsBuilderFromPool ¶ added in v0.34.0
func GetArgsBuilderFromPool(dialect Dialect) *ArgsBuilder
GetArgsBuilderFromPool acquires an ArgsBuilder with the dialect from pool.
func (*ArgsBuilder) Add ¶
func (a *ArgsBuilder) Add(arg any) (placeholder string)
Add appends the argument and returns the its placeholder.
If arg is the type of sql.NamedArg, it will use @arg.Name as the placeholder and arg.Value as the value.
func (*ArgsBuilder) Args ¶
func (a *ArgsBuilder) Args() (args []any)
Args returns the added arguments.
func (*ArgsBuilder) Release ¶ added in v0.34.0
func (a *ArgsBuilder) Release()
Release puts itself into the pool if it is acquired from the pool.
func (*ArgsBuilder) Reset ¶ added in v0.34.0
func (a *ArgsBuilder) Reset()
Reset resets the args to empty.
func (*ArgsBuilder) WithDialect ¶ added in v0.34.0
func (a *ArgsBuilder) WithDialect(dialect Dialect) *ArgsBuilder
WithDialect sets the dialect and returns itself.
type Base ¶
type Base struct { Id int64 `sql:"id,omitempty" json:",omitempty"` CreatedAt time.Time `sql:"created_at,omitempty"` UpdatedAt time.Time `sql:"updated_at,omitempty"` DeletedAt time.Time `sql:"deleted_at,omitempty" json:"-"` }
Base is the common columns of the sql table.
type Config ¶
Config is used to configure the DB.
func ConnMaxIdleTime ¶
ConnMaxIdleTime returns a Config to set the maximum idle time of the connection.
func ConnMaxLifetime ¶
ConnMaxLifetime returns a Config to set the maximum lifetime of the connection.
func MaxIdleConns ¶
MaxIdleConns returns a Config to set the maximum number of the idle connection.
func MaxOpenConns ¶
MaxOpenConns returns a Config to set the maximum number of the open connection.
If maxnum is equal to 0, it is runtime.NumCPU()*2 by default.
type DB ¶
type DB struct { Dialect Executor Interceptor }
DB is the wrapper of the sql.DB.
func Open ¶
Open opens a database specified by its database driver name and a driver-specific data source name,
func (*DB) Delete ¶
func (db *DB) Delete(tables ...string) *DeleteBuilder
Delete returns a DELETE SQL builder.
func (*DB) Exec ¶ added in v0.26.0
Exec is equal to db.ExecContext(context.Background(), query, args...).
func (*DB) ExecContext ¶
ExecContext executes the sql statement.
func (*DB) GetDialect ¶ added in v0.26.0
GetDialect returns the dialect of the db.
If not set, return DefaultDialect instead.
func (*DB) Query ¶ added in v0.26.0
Query is equal to db.QueryContext(context.Background(), query, args...).
func (*DB) QueryContext ¶
func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (rows *sql.Rows, err error)
QueryContext executes the query sql statement.
func (*DB) QueryRow ¶ added in v0.26.0
QueryRow is equal to db.QueryRowContext(context.Background(), query, args...)
func (*DB) QueryRowContext ¶
QueryRowContext executes the row query sql statement.
func (*DB) QueryRows ¶ added in v0.32.0
QueryRows executes the query sql statement and returns Rows instead of *sql.Rows.
func (*DB) QueryRowsContext ¶ added in v0.32.0
func (db *DB) QueryRowsContext(ctx context.Context, query string, args ...any) (rows Rows, err error)
QueryRowsContext executes the query sql statement and returns Rows instead of *sql.Rows.
func (*DB) QueryRowx ¶ added in v0.32.0
QueryRowx executes the row query sql statement and returns Row instead of *sql.Row.
func (*DB) QueryRowxContext ¶ added in v0.32.0
QueryRowxContext executes the row query sql statement and returns Row instead of *sql.Row.
func (*DB) Select ¶
func (db *DB) Select(column string) *SelectBuilder
Select is equal todb.SelectAlias(column, "").
func (*DB) SelectAlias ¶ added in v0.27.0
func (db *DB) SelectAlias(column, alias string) *SelectBuilder
SelectAlias is equal to SelectAlias(column, alias).
func (*DB) SelectStruct ¶
func (db *DB) SelectStruct(s any) *SelectBuilder
SelectStruct is equal to db.SelectStructWithTable(s, "").
func (*DB) SelectStructWithTable ¶ added in v0.27.0
func (db *DB) SelectStructWithTable(s any, table string) *SelectBuilder
SelectStructWithTable is equal to SelectStructWithTable(s, table...).
func (*DB) Selects ¶
func (db *DB) Selects(columns ...string) *SelectBuilder
Selects is equal to db.Select(columns[0]).Select(columns[1])...
func (*DB) Update ¶
func (db *DB) Update(table ...string) *UpdateBuilder
Update returns a UPDATE SQL builder.
type DeleteBuilder ¶
type DeleteBuilder struct {
// contains filtered or unexported fields
}
DeleteBuilder is used to build the DELETE statement.
Example ¶
// No Where delete1 := Delete().From("table") // With Where delete2 := Delete().From("table"). Where( op.Greater("c1", 123), op.IsNotNull("c2"), ). Where( op.Or( op.Less("c3", 456), op.In("c4", []string{"a", "b"}), ), ) sql1, args1 := delete1.Build() // Use the default dialect. sql2, args2 := delete2.Build() // Use the PostgreSQL dialect. fmt.Println(sql1) fmt.Println(args1.Args()) fmt.Println(sql2) fmt.Println(args2.Args())
Output: DELETE FROM `table` [] DELETE FROM `table` WHERE (`c1`>? AND `c2` IS NOT NULL AND (`c3`<? OR `c4` IN (?, ?))) [123 456 a b]
func NewDeleteBuilder ¶
func NewDeleteBuilder(tables ...string) *DeleteBuilder
NewDeleteBuilder returns a new DELETE builder.
func (*DeleteBuilder) Build ¶
func (b *DeleteBuilder) Build() (sql string, args *ArgsBuilder)
Build builds the DELETE FROM TABLE sql statement.
func (*DeleteBuilder) Comment ¶ added in v0.37.0
func (b *DeleteBuilder) Comment(comment string) *DeleteBuilder
Comment set the comment, which will be appended to the end of the built SQL statement.
func (*DeleteBuilder) Exec ¶
func (b *DeleteBuilder) Exec() (sql.Result, error)
Exec builds the sql and executes it by *sql.DB.
func (*DeleteBuilder) ExecContext ¶
ExecContext builds the sql and executes it by *sql.DB.
func (*DeleteBuilder) From ¶
func (b *DeleteBuilder) From(table string, alias ...string) *DeleteBuilder
From is equal to b.FromAlias(table, "").
func (*DeleteBuilder) FromAlias ¶ added in v0.27.0
func (b *DeleteBuilder) FromAlias(table string, alias string) *DeleteBuilder
From appends the "FROM table AS alias" statement.
If alias is empty, use "FROM table" instead.
func (*DeleteBuilder) JoinFull ¶
func (b *DeleteBuilder) JoinFull(table, alias string, ons ...JoinOn) *DeleteBuilder
JoinFull appends the "FULL JOIN table ON on..." statement.
func (*DeleteBuilder) JoinFullOuter ¶
func (b *DeleteBuilder) JoinFullOuter(table, alias string, ons ...JoinOn) *DeleteBuilder
JoinFullOuter appends the "FULL OUTER JOIN table ON on..." statement.
func (*DeleteBuilder) JoinLeft ¶
func (b *DeleteBuilder) JoinLeft(table, alias string, ons ...JoinOn) *DeleteBuilder
JoinLeft appends the "LEFT JOIN table ON on..." statement.
func (*DeleteBuilder) JoinLeftOuter ¶
func (b *DeleteBuilder) JoinLeftOuter(table, alias string, ons ...JoinOn) *DeleteBuilder
JoinLeftOuter appends the "LEFT OUTER JOIN table ON on..." statement.
func (*DeleteBuilder) JoinRight ¶
func (b *DeleteBuilder) JoinRight(table, alias string, ons ...JoinOn) *DeleteBuilder
JoinRight appends the "RIGHT JOIN table ON on..." statement.
func (*DeleteBuilder) JoinRightOuter ¶
func (b *DeleteBuilder) JoinRightOuter(table, alias string, ons ...JoinOn) *DeleteBuilder
JoinRightOuter appends the "RIGHT OUTER JOIN table ON on..." statement.
func (*DeleteBuilder) SetDB ¶
func (b *DeleteBuilder) SetDB(db *DB) *DeleteBuilder
SetDB sets the db.
func (*DeleteBuilder) String ¶
func (b *DeleteBuilder) String() string
String is the same as b.Build(), except args.
func (*DeleteBuilder) Table ¶
func (b *DeleteBuilder) Table(table string) *DeleteBuilder
Table appends the table name to delete the rows from it.
func (*DeleteBuilder) Where ¶
func (b *DeleteBuilder) Where(andConditions ...op.Condition) *DeleteBuilder
Where sets the "WHERE" conditions.
func (*DeleteBuilder) WhereNamedArgs ¶
func (b *DeleteBuilder) WhereNamedArgs(andArgs ...sql.NamedArg) *DeleteBuilder
WhereNamedArgs is the same as Where, but uses the NamedArg as the condition.
type Dialect ¶
type Dialect interface { // Name returns the name of the dialect. Name() string // Placeholder returns the format of the ith argument, // such as "?" for MySQL and "$i" for PostgreSQL. // // Notice: i starts with 1. Placeholder(i int) string // Quote returns the quotation format of sql string, // such as `s` for MySQL and "s" for PostgreSQL. Quote(s string) string // LimitOffset returns the LIMIT OFFSET statement, // such as "LIMIT n" or "LIMIT n OFFSET m" for MySQL and PostgreSQL. LimitOffset(limit, offset int64) string }
Dialect represents a dialect of the SQL.
var ( MySQL Dialect = dialect{mysqlDialect} Sqlite3 Dialect = dialect{sqlite3Dialect} Postgres Dialect = dialect{pqDialect} )
Predefine some dialects.
func GetDialect ¶
GetDialect returns the dialect named name. Return nil instead if not exist.
type Executor ¶
type Executor interface { io.Closer ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row }
Executor is used to execute the sql statement.
type InsertBuilder ¶
type InsertBuilder struct {
// contains filtered or unexported fields
}
InsertBuilder is used to build the INSERT statement.
Example ¶
// Single Value insert1 := Insert().Into("table").Columns("c1", "c2", "c3"). Values("v1", "v2", "v3") // Many Values insert2 := Insert().Into("table").Columns("c1", "c2", "c3"). Values("v1", "v2", "v3"). Values("v4", "v5", "v6"). Values("v7", "v8", "v9") // No Value, which will build a single value placeholder. insert3 := Insert().Into("table").Columns("c1", "c2", "c3") // No Column insert4 := Insert().Into("table").Values("v1", "v2", "v3") insert5 := Insert().Into("table").Values("v11", "v12").Values("v21", "v22") sql1, args1 := insert1.SetDB(&DB{Dialect: Postgres}).Build() // Use the PostgreSQL dialect. sql2, args2 := insert2.SetDB(&DB{Dialect: Postgres}).Build() // Use the PostgreSQL dialect. sql3, args3 := insert3.Build() // Use the default dialect. sql4, args4 := insert4.Build() // Use the default dialect. sql5, args5 := insert5.Build() // Use the default dialect. fmt.Println(sql1) fmt.Println(args1.Args()) fmt.Println(sql2) fmt.Println(args2.Args()) fmt.Println(sql3) fmt.Println(args3.Args()) fmt.Println(sql4) fmt.Println(args4.Args()) fmt.Println(sql5) fmt.Println(args5.Args())
Output: INSERT INTO "table" ("c1", "c2", "c3") VALUES ($1, $2, $3) [v1 v2 v3] INSERT INTO "table" ("c1", "c2", "c3") VALUES ($1, $2, $3), ($4, $5, $6), ($7, $8, $9) [v1 v2 v3 v4 v5 v6 v7 v8 v9] INSERT INTO `table` (`c1`, `c2`, `c3`) VALUES (?, ?, ?) [] INSERT INTO `table` VALUES (?, ?, ?) [v1 v2 v3] INSERT INTO `table` VALUES (?, ?), (?, ?) [v11 v12 v21 v22]
func NewInsertBuilder ¶
func NewInsertBuilder() *InsertBuilder
NewInsertBuilder returns a new INSERT builder.
func (*InsertBuilder) Build ¶
func (b *InsertBuilder) Build() (sql string, args *ArgsBuilder)
Build builds the INSERT INTO TABLE sql statement.
func (*InsertBuilder) Columns ¶
func (b *InsertBuilder) Columns(columns ...string) *InsertBuilder
Columns sets the inserted columns.
func (*InsertBuilder) Comment ¶ added in v0.37.0
func (b *InsertBuilder) Comment(comment string) *InsertBuilder
Comment set the comment, which will be appended to the end of the built SQL statement.
func (*InsertBuilder) Exec ¶
func (b *InsertBuilder) Exec() (sql.Result, error)
Exec builds the sql and executes it by *sql.DB.
func (*InsertBuilder) ExecContext ¶
ExecContext builds the sql and executes it by *sql.DB.
func (*InsertBuilder) IgnoreInto ¶
func (b *InsertBuilder) IgnoreInto(table string) *InsertBuilder
IgnoreInto sets the table name with "INSERT IGNORE INTO".
func (*InsertBuilder) Into ¶
func (b *InsertBuilder) Into(table string) *InsertBuilder
Into sets the table name with "INSERT INTO".
func (*InsertBuilder) NamedValues ¶
func (b *InsertBuilder) NamedValues(nvs ...sql.NamedArg) *InsertBuilder
NamedValues is the same as Values. But it will set it if the columns are not set.
Example ¶
v1 := sql.Named("column1", "value1") v2 := sql.Named("column2", "value2") v3 := sql.Named("column3", "value3") insert := Insert().Into("table").NamedValues(v1, v2, v3) sql, args := insert.Build() fmt.Println(sql) fmt.Println(args.Args())
Output: INSERT INTO `table` (`column1`, `column2`, `column3`) VALUES (?, ?, ?) [value1 value2 value3]
func (*InsertBuilder) Ops ¶ added in v0.27.0
func (b *InsertBuilder) Ops(ops ...op.Op) *InsertBuilder
Ops is the same as Values. But it will set it if the columns are not set.
func (*InsertBuilder) ReplaceInto ¶
func (b *InsertBuilder) ReplaceInto(table string) *InsertBuilder
ReplaceInto sets the table name with "REPLACE INTO".
REPLACE INTO is a MySQL extension to the SQL standard.
func (*InsertBuilder) SetDB ¶
func (b *InsertBuilder) SetDB(db *DB) *InsertBuilder
SetDB sets the db.
func (*InsertBuilder) String ¶
func (b *InsertBuilder) String() string
String is the same as b.Build(), except args.
func (*InsertBuilder) Struct ¶
func (b *InsertBuilder) Struct(s any) *InsertBuilder
Struct is the same as NamedValues, but extracts the fields of the struct as the named values to be inserted, which supports the tag named "sql" to modify the column name.
- If the value of the tag is "-", however, the field will be ignored.
- If the tag value contains "omitempty", the ZERO field will be ignored.
- If the tag contains the attribute "notpropagate", for the embeded struct, do not scan the fields of the embeded struct.
Example ¶
type S struct { DefaultField string ModifiedField string `sql:"field"` ZeroField string `sql:",omitempty"` IgnoredField string `sql:"-"` } s := S{DefaultField: "v1", IgnoredField: "v2"} insert := Insert().Into("table").Struct(s) sql, args := insert.Build() fmt.Println(sql) fmt.Println(args.Args())
Output: INSERT INTO `table` (`DefaultField`, `field`) VALUES (?, ?) [v1 ]
func (*InsertBuilder) Values ¶
func (b *InsertBuilder) Values(values ...any) *InsertBuilder
Values appends the inserted values.
type Interceptor ¶
Interceptor is used to intercept the executed sql statement and arguments and return a new one.
type InterceptorFunc ¶ added in v0.26.0
InterceptorFunc is an interceptor function.
type Interceptors ¶ added in v0.36.0
type Interceptors []Interceptor
Interceptors is a set of Interceptors.
type Map ¶ added in v0.39.0
Map is a map value type, which is encoded to a string or decoded from a []byte or string.
type OpBuilder ¶ added in v0.27.0
type OpBuilder interface {
Build(*ArgsBuilder, op.Op) string
}
OpBuilder is an operation builder to build a sql statement based on op.
func GetOpBuilder ¶ added in v0.27.0
GetOpBuilder returns the op builder by the op.
Return nil instead if no the op builder.
type OpBuilderFunc ¶ added in v0.27.0
type OpBuilderFunc func(ab *ArgsBuilder, op op.Op) string
OpBuilderFunc is a operation build function.
func (OpBuilderFunc) Build ¶ added in v0.27.0
func (f OpBuilderFunc) Build(ab *ArgsBuilder, op op.Op) string
Build implements the interface OpBuilder.
type Oper ¶ added in v0.34.0
type Oper[T any] struct { Table Table // SoftCondition is used by the method SoftXxxx as the WHERE condition. // // Default: op.IsNotDeletedCond SoftCondition op.Condition // SoftDeleteUpdater is used by SoftDelete to delete the records. // // Default: op.KeyDeletedAt.Set(time.Now()) SoftDeleteUpdater func(context.Context) op.Updater }
Oper is used to collect a set of SQL DML & DQL operations based on a table.
func NewOperWithTable ¶ added in v0.34.0
NewOperWithTable returns a new Oper with the table.
func (Oper[T]) AddContext ¶ added in v0.34.0
AddContext inserts the struct as the record into the sql table.
func (Oper[T]) AddContextWithId ¶ added in v0.34.0
AddContextWithId is the same as AddContext, but also returns the inserted id.
func (Oper[T]) AddWithId ¶ added in v0.34.0
AddWithId is equal to o.AddContextWithId(context.Background(), obj).
func (Oper[T]) Count ¶ added in v0.34.0
Count is equal to o.CountContext(context.Background(), conds...).
func (Oper[T]) CountContext ¶ added in v0.35.0
CountContext is used to count the number of records by the condition.
func (Oper[T]) CountDistinct ¶ added in v0.34.0
CountDistinct is equal to o.CountDistinctContext(context.Background(), field, conds...).
func (Oper[T]) CountDistinctContext ¶ added in v0.35.0
func (o Oper[T]) CountDistinctContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)
CountDistinctContext is the same as Count, but excluding the same field records.
func (Oper[T]) Delete ¶ added in v0.34.0
Delete is equal to o.DeleteContext(context.Background(), conds...).
func (Oper[T]) DeleteById ¶ added in v0.36.0
DeleteById is equal to o.Delete(op.KeyId.Eq(id)).
func (Oper[T]) DeleteContext ¶ added in v0.34.0
DeleteContext executes a DELETE statement to delete the records from table.
func (Oper[T]) Exist ¶ added in v0.34.0
Exist is equal to o.ExistContext(context.Background(), conds...).
func (Oper[T]) ExistContext ¶ added in v0.35.0
ExistContext is used to check whether the records qualified by the conditions exist.
func (Oper[T]) Get ¶ added in v0.34.0
Get is equal to o.GetContext(context.Background(), sort, conds...).
func (Oper[T]) GetContext ¶ added in v0.34.0
func (o Oper[T]) GetContext(ctx context.Context, sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)
GetContext just queries a first record from table.
func (Oper[T]) GetRow ¶ added in v0.36.0
func (o Oper[T]) GetRow(ctx context.Context, columns any, sort op.Sorter, conds ...op.Condition) Row
GetRow is equal to o.GetRowContext(ctx, columns, sort, conds...).
func (Oper[T]) GetRowContext ¶ added in v0.36.0
func (o Oper[T]) GetRowContext(ctx context.Context, columns any, sort op.Sorter, conds ...op.Condition) Row
GetRowContext builds a SELECT statement and returns a Row.
func (Oper[T]) GetRows ¶ added in v0.35.0
func (o Oper[T]) GetRows(columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (Rows, error)
GetRows is equal to o.GetRowsContext(context.Background(), columns, sort, page, conds...).
func (Oper[T]) GetRowsContext ¶ added in v0.35.0
func (o Oper[T]) GetRowsContext(ctx context.Context, columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (rows Rows, err error)
GetRowsContext builds a SELECT statement and returns a Rows.
func (Oper[T]) Gets ¶ added in v0.34.0
func (o Oper[T]) Gets(sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)
Gets is equal to o.GetsContext(context.Background(), sort, page, conds...).
func (Oper[T]) GetsContext ¶ added in v0.34.0
func (o Oper[T]) GetsContext(ctx context.Context, sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)
GetsContext queries a set of results from table.
Any of sort, page and conds is equal to nil.
func (Oper[T]) MakeSlice ¶ added in v0.34.0
MakeSlice makes a slice with the cap.
If cap is equal to 0, use DefaultSliceCap instead.
func (Oper[T]) Query ¶ added in v0.36.0
Query is equal to o.QueryContext(context.Background(), page, pageSize, conds...).
func (Oper[T]) QueryContext ¶ added in v0.36.0
func (o Oper[T]) QueryContext(ctx context.Context, page, pageSize int64, conds ...op.Condition) ([]T, error)
QueryContext is a simplified GetsContext, which is equal to
o.GetsContext(ctx, op.KeyId.OrderDesc(), op.Paginate(page, pageSize), conds...)
page starts with 1. And if page or pageSize is less than 1, ignore the pagination.
func (Oper[T]) Select ¶ added in v0.36.0
func (o Oper[T]) Select(columns any, conds ...op.Condition) *SelectBuilder
Select returns a SELECT builder, which sets the selected columns and the where condtions.
columns supports one of types as follow:
string []string struct
func (Oper[T]) SoftCount ¶ added in v0.34.0
SoftCount is equal to o.SoftCountContext(context.Background(), conds...).
func (Oper[T]) SoftCountContext ¶ added in v0.36.0
func (o Oper[T]) SoftCountContext(ctx context.Context, conds ...op.Condition) (total int, err error)
SoftCountContext is the same as CountContext, but appending SoftCondition into the conditions.
func (Oper[T]) SoftCountDistinct ¶ added in v0.34.0
SoftCountDistinct is equal to o.SoftCountDistinctContext(context.Background(), field, conds...).
func (Oper[T]) SoftCountDistinctContext ¶ added in v0.36.0
func (o Oper[T]) SoftCountDistinctContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)
SoftCountDistinctContext is the same as CountDistinctContext, but appending SoftCondition into the conditions.
func (Oper[T]) SoftDelete ¶ added in v0.34.0
SoftDelete is equal to o.SoftDeleteContext(context.Background(), conds...).
func (Oper[T]) SoftDeleteById ¶ added in v0.34.0
SoftDeleteById is equal to o.SoftDelete(op.KeyId.Eq(id)).
func (Oper[T]) SoftDeleteContext ¶ added in v0.34.0
SoftDeleteContext soft deletes the records from the table, which only marks the records deleted.
func (Oper[T]) SoftExist ¶ added in v0.34.0
SoftExist is equal to o.SoftExistContext(context.Background(), conds... ).
func (Oper[T]) SoftExistContext ¶ added in v0.36.0
func (o Oper[T]) SoftExistContext(ctx context.Context, conds ...op.Condition) (exist bool, err error)
SoftExistContext is the same as ExistContext, but appending SoftCondition into the conditions.
func (Oper[T]) SoftGet ¶ added in v0.34.0
SoftGet is equal to o.SoftGetContext(context.Background(), sort, conds...).
func (Oper[T]) SoftGetById ¶ added in v0.34.0
SoftGetById is equal to o.SoftGet(nil, op.KeyId.Eq(id)).
func (Oper[T]) SoftGetContext ¶ added in v0.34.0
func (o Oper[T]) SoftGetContext(ctx context.Context, sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)
SoftGetContext is the same as GetContext, but appending SoftCondition into the conditions.
func (Oper[T]) SoftGetRows ¶ added in v0.35.0
func (o Oper[T]) SoftGetRows(columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (Rows, error)
SoftGetRows is equal to o.SoftGetRowsContext(context.Background(), columns, sort, page, conds...).
func (Oper[T]) SoftGetRowsContext ¶ added in v0.35.0
func (o Oper[T]) SoftGetRowsContext(ctx context.Context, columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (Rows, error)
SoftGetRowsContext is the same as GetRowsContext, but appending SoftCondition into the conditions.
func (Oper[T]) SoftGets ¶ added in v0.34.0
SoftGets is equal to o.SoftGetsContext(context.Background(), sort, page, conds...).
func (Oper[T]) SoftGetsContext ¶ added in v0.34.0
func (o Oper[T]) SoftGetsContext(ctx context.Context, sort op.Sorter, page op.Paginator, conds ...op.Condition) ([]T, error)
SoftGetsContext is the same as GetsContext, but appending SoftCondition into the conditions.
func (Oper[T]) SoftQuery ¶ added in v0.34.0
SoftQuery is equal to o.SoftQueryContext(context.Background(), page, pageSize, conds...).
func (Oper[T]) SoftQueryContext ¶ added in v0.36.0
func (o Oper[T]) SoftQueryContext(ctx context.Context, page, pageSize int64, conds ...op.Condition) ([]T, error)
SoftQueryContext is the same as QueryContext, but appending SoftCondition into the conditions.
func (Oper[T]) SoftSelect ¶ added in v0.36.0
func (o Oper[T]) SoftSelect(columns any, conds ...op.Condition) *SelectBuilder
SoftSelect is the same as Select, but appends SoftCondition into the conditions.
func (Oper[T]) SoftSum ¶ added in v0.35.0
SoftSum is equal to o.SoftSumContext(context.Background(), field, conds...).
func (Oper[T]) SoftSumContext ¶ added in v0.36.0
func (o Oper[T]) SoftSumContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)
SoftSumContext is the same as SumContext, but appending SoftCondition into the conditions.
func (Oper[T]) SoftUpdate ¶ added in v0.34.0
SoftUpdate is equal to o.SoftUpdateContext(context.Background(), updater, conds...).
func (Oper[T]) SoftUpdateById ¶ added in v0.34.0
SoftUpdateById is equal to o.SoftUpdate(op.Batch(updaters...), op.KeyId.Eq(id)).
func (Oper[T]) SoftUpdateContext ¶ added in v0.34.0
func (o Oper[T]) SoftUpdateContext(ctx context.Context, updater op.Updater, conds ...op.Condition) error
SoftUpdateContext is the same as UpdateContext, but appending SoftCondition into the conditions.
func (Oper[T]) Sum ¶ added in v0.35.0
Sum is equal to o.SumContext(context.Background(), field, conds...).
func (Oper[T]) SumContext ¶ added in v0.35.0
func (o Oper[T]) SumContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)
SumContext is used to sum the field values of the records by the condition.
func (Oper[T]) Update ¶ added in v0.34.0
Update is equal to o.UpdateContext(context.Background(), updater, conds...).
func (Oper[T]) UpdateById ¶ added in v0.36.0
UpdateById is equal to o.Update(op.Batch(updaters...), op.KeyId.Eq(id)).
func (Oper[T]) UpdateContext ¶ added in v0.34.0
func (o Oper[T]) UpdateContext(ctx context.Context, updater op.Updater, conds ...op.Condition) error
UpdateContext updates the sql table records.
If updater is nil, do nothing.
func (Oper[T]) WithSoftCondition ¶ added in v0.34.0
WithSoftCondition returns a new Oper with the soft condition.
func (Oper[T]) WithSoftDeleteUpdater ¶ added in v0.34.0
WithSoftDeleteUpdater returns a new Oper with the soft delete udpater.
type Operation ¶ added in v0.27.0
type Operation[T any] struct { Table // EnableUpdater is used by Enable to enable the table records. // // Default: op.KeyIsDisabled.Set(0) EnableUpdater op.Updater // DisableUpdater is used by Disable to disable the table records. // // Default: op.KeyIsDisabled.Set(1) DisableUpdater op.Updater // SoftDeleteUpdater is used by DeleteUpdateContext to delete the records. // // Default: DefaultDeletedAt.Set(time.Now()) SoftDeleteUpdater func(context.Context) op.Updater }
Operation is used to manage a set of operations.
DEPRECATED!!! Please use Oper instead.
func NewOperation ¶ added in v0.27.0
NewOperation returns a new operation with the table name.
func NewOperationWithTable ¶ added in v0.27.0
NewOperationWithTable returns a new operation with the table.
func (Operation[T]) AddContext ¶ added in v0.27.0
AddContext inserts the struct as the record into the sql table.
func (Operation[T]) AddContextWithId ¶ added in v0.27.0
AddContextWithId is the same as AddContext, but also returns the inserted id.
func (Operation[T]) AddWithId ¶ added in v0.32.0
AddWithId is equal to o.AddContextWithId(context.Background(), obj).
func (Operation[T]) Count ¶ added in v0.33.0
Count is a simple convenient function to count the number of table records, which is equal to
o.Select(Count("*")).Where(conds...).Where(op.IsNotDeletedCond).BindRow(&total)
func (Operation[T]) CountDistinct ¶ added in v0.33.0
CountDistinct is a simple convenient function to count the number of table records with the distinct field, which is equal to
o.Select(CountDistinct(field)).Where(conds...).Where(op.IsNotDeletedCond).BindRow(&total)
func (Operation[T]) DeleteById ¶ added in v0.33.0
DeleteById is a simple convenient function to delete the table records by the primary key id, which is equal to
o.UpdateRemove(op.KeyId.Eq(id), op.IsNotDeletedCond)
func (Operation[T]) DisableById ¶ added in v0.33.0
DisableById is a simple convenient function to disable a table record by the primary key id, which is equal to
o.Update(o.DisableUpdater, op.KeyId.Eq(id), op.IsNotDeletedCond)
func (Operation[T]) EnableById ¶ added in v0.33.0
EnableById is a simple convenient function to enable a table record by the primary key id, which is equal to
o.Update(o.EnableUpdater, op.KeyId.Eq(id), op.IsNotDeletedCond)
func (Operation[T]) Get ¶ added in v0.27.0
Get is equal to o.GetContext(context.Background(), conds...).
func (Operation[T]) GetById ¶ added in v0.33.0
GetById is a simple convenient function to query a table record by the primary key id, which is equal to
o.Get(op.KeyId.Eq(id), op.IsNotDeletedCond)
func (Operation[T]) GetContext ¶ added in v0.27.0
func (o Operation[T]) GetContext(ctx context.Context, conds ...op.Condition) (obj T, ok bool, err error)
GetContext just queries a result.
func (Operation[T]) Gets ¶ added in v0.27.0
func (o Operation[T]) Gets(sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)
Gets is equal to o.GetsContext(context.Background(), sort, page, conds...).
func (Operation[T]) GetsContext ¶ added in v0.27.0
func (o Operation[T]) GetsContext(ctx context.Context, sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)
GetsContext queyies a set of results.
Any of sort, page and conds is equal to nil.
func (Operation[T]) MakeSlice ¶ added in v0.27.0
MakeSlice makes a slice with the cap.
If cap is equal to 0, use DefaultSliceCap instead.
func (Operation[T]) Query ¶ added in v0.33.0
Query is a simple convenient function to query the table records with the pagination, which is equal to
o.Gets(op.KeyId.OrderDesc(), op.Paginate(page, pageSize), op.And(conds...), op.IsNotDeletedCond)
page starts with 1.
func (Operation[T]) Remove ¶ added in v0.27.0
Remove is equal to o.RemoveContext(context.Background(), conds...).
func (Operation[T]) RemoveContext ¶ added in v0.27.0
RemoveContext deletes some records from the sql table.
func (Operation[T]) Update ¶ added in v0.27.0
Update is equal to o.UpdateContext(context.Background(), updater, conds...).
func (Operation[T]) UpdateById ¶ added in v0.33.0
UpdateById is a simple convenient function to update the table records by the primary key id, which is equal to
o.Update(op.Batch(updaters...), op.KeyId.Eq(id), op.IsNotDeletedCond)
func (Operation[T]) UpdateContext ¶ added in v0.27.0
func (o Operation[T]) UpdateContext(ctx context.Context, updater op.Updater, conds ...op.Condition) error
UpdateContext updates the sql table records.
func (Operation[T]) UpdateRemove ¶ added in v0.27.0
UpdateRemove is equal to o.UpdateRemoveContext(context.Background(), conds...).
func (Operation[T]) UpdateRemoveContext ¶ added in v0.27.0
UpdateRemoveContext is the same as RemoveContext, but uses soft delete instead.
type Row ¶
Row is used to wrap sql.Row.
func (Row) Bind ¶ added in v0.35.0
Bind is the same as Scan, but returns (false, nil) if Scan returns sql.ErrNoRows.
func (Row) BindStruct ¶ added in v0.35.0
Bind is the same as BindStruct, but returns (false, nil) if Scan returns sql.ErrNoRows.
func (Row) Scan ¶
Scan implements the interface sql.Scanner, which is the proxy of sql.Row and supports that the sql value is NULL.
func (Row) ScanStruct ¶
ScanStruct is the same as Scan, but the columns are scanned into the struct s, which uses ScanColumnsToStruct.
type Rows ¶
Rows is used to wrap sql.Rows.
func (Rows) Scan ¶
Scan implements the interface sql.Scanner, which is the proxy of sql.Rows and supports that the sql value is NULL.
func (Rows) ScanStruct ¶
ScanStruct is the same as Scan, but the columns are scanned into the struct s, which uses ScanColumnsToStruct.
func (Rows) ScanStructWithColumns ¶
ScanStructWithColumns is the same as Scan, but the columns are scanned into the struct s by using ScanColumnsToStruct.
type SelectBuilder ¶
type SelectBuilder struct {
// contains filtered or unexported fields
}
SelectBuilder is used to build the SELECT statement.
Example ¶
sel1 := Select("*").From("table").Where(op.Equal("id", 123)).Comment("abc") sel2 := Select("*").FromAlias("table", "alias").Where(op.Equal("id", 123)) sel3 := SelectAlias("id", "c1").SelectAlias("name", "c2").FromAlias("table", "alias").Where(op.Equal("id", 123)) sel4 := Select("A.id").Select("B.name").FromAlias("table1", "A").FromAlias("table2", "B").Where(op.EqualKey("A.id", "B.id")) sql1, args1 := sel1.Build() sql2, args2 := sel2.Build() sql3, args3 := sel3.Build() sql4, args4 := sel4.Build() fmt.Println(sql1) fmt.Println(args1.Args()) fmt.Println(sql2) fmt.Println(args2.Args()) fmt.Println(sql3) fmt.Println(args3.Args()) fmt.Println(sql4) fmt.Println(args4.Args())
Output: SELECT * FROM `table` WHERE `id`=? /* abc */ [123] SELECT * FROM `table` AS `alias` WHERE `id`=? [123] SELECT `id` AS `c1`, `name` AS `c2` FROM `table` AS `alias` WHERE `id`=? [123] SELECT `A`.`id`, `B`.`name` FROM `table1` AS `A`, `table2` AS `B` WHERE `A`.`id`=`B`.`id` []
func NewSelectBuilder ¶
func NewSelectBuilder() *SelectBuilder
NewSelectBuilder returns a new SELECT builder.
func SelectAlias ¶ added in v0.27.0
func SelectAlias(column, alias string) *SelectBuilder
SelectAlias is equal to NewSelectBuilder().SelectAlias(column, alias).
func SelectStruct ¶
func SelectStruct(s any) *SelectBuilder
SelectStruct is equal to SelectStructWithTable(s, "").
func SelectStructWithTable ¶ added in v0.27.0
func SelectStructWithTable(s any, table string) *SelectBuilder
SelectStruct is equal to NewSelectBuilder().SelectStructWithTable(s, table).
func Selects ¶
func Selects(columns ...string) *SelectBuilder
Selects is equal to Select(columns[0]).Select(columns[1])...
func (*SelectBuilder) BindRow ¶
func (b *SelectBuilder) BindRow(dest ...any) (bool, error)
BindRow is equal to b.BindRowContext(context.Background(), dest...).
func (*SelectBuilder) BindRowContext ¶
BindRowContext is convenient function, which is equal to b.QueryRowContext(c).Bind(dest...).
func (*SelectBuilder) BindRowStruct ¶
func (b *SelectBuilder) BindRowStruct(dest any) (bool, error)
BindRowStruct is equal to b.BindRowStructContext(context.Background(), dest).
func (*SelectBuilder) BindRowStructContext ¶
BindRowStructContext is convenient function, which is equal to b.QueryRowContext(c).BindStruct(dest).
func (*SelectBuilder) BindRows ¶
func (b *SelectBuilder) BindRows(slice any) error
BindRows is equal to b.BindRowsContext(context.Background(), slice).
func (*SelectBuilder) BindRowsContext ¶
func (b *SelectBuilder) BindRowsContext(ctx context.Context, slice any) error
BindRowsContext is the same QueryContext, but scans the result set into the slice.
Notice: slice must be a pointer to a slice. And the element of the slice may be a struct or type implemented the interface sql.Scanner.
func (*SelectBuilder) Build ¶
func (b *SelectBuilder) Build() (sql string, args *ArgsBuilder)
Build builds the SELECT sql statement.
func (*SelectBuilder) Comment ¶ added in v0.37.0
func (b *SelectBuilder) Comment(comment string) *SelectBuilder
Comment set the comment, which will be appended to the end of the built SQL statement.
func (*SelectBuilder) Distinct ¶
func (b *SelectBuilder) Distinct() *SelectBuilder
Distinct marks SELECT as DISTINCT.
func (*SelectBuilder) From ¶
func (b *SelectBuilder) From(table string) *SelectBuilder
From is equal to b.FromAlias(table, "").
func (*SelectBuilder) FromAlias ¶ added in v0.27.0
func (b *SelectBuilder) FromAlias(table, alias string) *SelectBuilder
FromAlias appends the FROM table name in SELECT with the alias.
If alias is empty, ignore it.
func (*SelectBuilder) Froms ¶
func (b *SelectBuilder) Froms(tables ...string) *SelectBuilder
Froms is the same as b.From(table0).From(table1)...
func (*SelectBuilder) GroupBy ¶
func (b *SelectBuilder) GroupBy(columns ...string) *SelectBuilder
GroupBy resets the GROUP BY columns.
Example ¶
s := Select("*").From("table").Where(op.Equal("id", 123)).GroupBy("area") sql, args := s.Build() fmt.Println(sql) fmt.Println(args.Args())
Output: SELECT * FROM `table` WHERE `id`=? GROUP BY `area` [123]
func (*SelectBuilder) Having ¶
func (b *SelectBuilder) Having(exprs ...string) *SelectBuilder
Having appends the HAVING expression.
func (*SelectBuilder) Join ¶
func (b *SelectBuilder) Join(table, alias string, ons ...JoinOn) *SelectBuilder
Join appends the "JOIN table ON on..." statement.
Example ¶
s := Select("*").From("table1").Join("table2", "", On("table1.id", "table2.id")). Where(op.Equal("table1.id", 123)).OrderByAsc("table1.time").Limit(10).Offset(100) sql, args := s.Build() fmt.Println(sql) fmt.Println(args.Args())
Output: SELECT * FROM `table1` JOIN `table2` ON `table1`.`id`=`table2`.`id` WHERE `table1`.`id`=? ORDER BY `table1`.`time` ASC LIMIT 10 OFFSET 100 [123]
func (*SelectBuilder) JoinFull ¶
func (b *SelectBuilder) JoinFull(table, alias string, ons ...JoinOn) *SelectBuilder
JoinFull appends the "FULL JOIN table ON on..." statement.
func (*SelectBuilder) JoinFullOuter ¶
func (b *SelectBuilder) JoinFullOuter(table, alias string, ons ...JoinOn) *SelectBuilder
JoinFullOuter appends the "FULL OUTER JOIN table ON on..." statement.
func (*SelectBuilder) JoinLeft ¶
func (b *SelectBuilder) JoinLeft(table, alias string, ons ...JoinOn) *SelectBuilder
JoinLeft appends the "LEFT JOIN table ON on..." statement.
func (*SelectBuilder) JoinLeftOuter ¶
func (b *SelectBuilder) JoinLeftOuter(table, alias string, ons ...JoinOn) *SelectBuilder
JoinLeftOuter appends the "LEFT OUTER JOIN table ON on..." statement.
func (*SelectBuilder) JoinRight ¶
func (b *SelectBuilder) JoinRight(table, alias string, ons ...JoinOn) *SelectBuilder
JoinRight appends the "RIGHT JOIN table ON on..." statement.
func (*SelectBuilder) JoinRightOuter ¶
func (b *SelectBuilder) JoinRightOuter(table, alias string, ons ...JoinOn) *SelectBuilder
JoinRightOuter appends the "RIGHT OUTER JOIN table ON on..." statement.
func (*SelectBuilder) Limit ¶
func (b *SelectBuilder) Limit(limit int64) *SelectBuilder
Limit sets the LIMIT to limit.
Example ¶
s := Select("*").From("table").Where(op.Equal("id", 123)). OrderByAsc("time").Limit(10).Offset(100) sql, args := s.Build() fmt.Println(sql) fmt.Println(args.Args())
Output: SELECT * FROM `table` WHERE `id`=? ORDER BY `time` ASC LIMIT 10 OFFSET 100 [123]
func (*SelectBuilder) Offset ¶
func (b *SelectBuilder) Offset(offset int64) *SelectBuilder
Offset sets the OFFSET to offset.
func (*SelectBuilder) OrderBy ¶
func (b *SelectBuilder) OrderBy(column string, order Order) *SelectBuilder
OrderBy appends the column used by ORDER BY.
Example ¶
s1 := Select("*").From("table").Where(op.Equal("id", 123)).OrderBy("time", Asc) s2 := Select("*").From("table").Where(op.Equal("id", 123)).OrderBy("time", Desc) sql1, args1 := s1.Build() sql2, args2 := s2.Build() fmt.Println(sql1) fmt.Println(args1.Args()) fmt.Println(sql2) fmt.Println(args2.Args())
Output: SELECT * FROM `table` WHERE `id`=? ORDER BY `time` ASC [123] SELECT * FROM `table` WHERE `id`=? ORDER BY `time` DESC [123]
func (*SelectBuilder) OrderByAsc ¶
func (b *SelectBuilder) OrderByAsc(column string) *SelectBuilder
OrderByAsc appends the column used by ORDER BY ASC.
func (*SelectBuilder) OrderByDesc ¶
func (b *SelectBuilder) OrderByDesc(column string) *SelectBuilder
OrderByDesc appends the column used by ORDER BY DESC.
func (*SelectBuilder) Paginate ¶
func (b *SelectBuilder) Paginate(pageNum, pageSize int64) *SelectBuilder
Paginate is equal to b.Limit(pageSize).Offset((pageNum-1) * pageSize).
pageNum starts with 1. If pageNum or pageSize is less than 1, do nothing.
func (*SelectBuilder) Paginator ¶ added in v0.27.0
func (b *SelectBuilder) Paginator(page op.Paginator) *SelectBuilder
Paginator sets the paginator, which is the same as b.Paginate.
func (*SelectBuilder) Query ¶
func (b *SelectBuilder) Query() (Rows, error)
Query builds the sql and executes it.
func (*SelectBuilder) QueryContext ¶
func (b *SelectBuilder) QueryContext(ctx context.Context) (Rows, error)
QueryContext builds the sql and executes it.
func (*SelectBuilder) QueryRow ¶
func (b *SelectBuilder) QueryRow() Row
QueryRow builds the sql and executes it.
func (*SelectBuilder) QueryRowContext ¶
func (b *SelectBuilder) QueryRowContext(ctx context.Context) Row
QueryRowContext builds the sql and executes it.
func (*SelectBuilder) Select ¶
func (b *SelectBuilder) Select(column string) *SelectBuilder
Select appends the selected column in SELECT.
func (*SelectBuilder) SelectAlias ¶ added in v0.27.0
func (b *SelectBuilder) SelectAlias(column, alias string) *SelectBuilder
Select appends the selected column in SELECT with the alias.
If alias is empty, it will be ignored.
func (*SelectBuilder) SelectCount ¶ added in v0.30.0
func (b *SelectBuilder) SelectCount(field string) *SelectBuilder
SelectCount appends the selected COUNT(field) column in SELECT.
func (*SelectBuilder) SelectCountDistinct ¶ added in v0.30.0
func (b *SelectBuilder) SelectCountDistinct(field string) *SelectBuilder
SelectCountDistinct appends the selected COUNT(DISTINCT field) column in SELECT.
func (*SelectBuilder) SelectStruct ¶
func (b *SelectBuilder) SelectStruct(s any) *SelectBuilder
SelectStruct is equal to b.SelectStructWithTable(s, "").
Example ¶
type S struct { DefaultField string ModifiedField string `sql:"field"` IgnoredField string `sql:"-"` } s := S{} sb := SelectStructWithTable(s, "A") columns := sb.SelectedColumns() fmt.Println(columns) err := ScanColumnsToStruct(func(values ...any) error { for i, v := range values { vp := v.(*string) switch i { case 0: *vp = "a" case 1: *vp = "b" default: fmt.Printf("unknown %dth column value\n", i) } } return nil }, columns, &s) if err != nil { fmt.Println(err) } else { fmt.Println(s.DefaultField) fmt.Println(s.ModifiedField) fmt.Println(s.IgnoredField) }
Output: [DefaultField field] a b
func (*SelectBuilder) SelectStructWithTable ¶ added in v0.27.0
func (b *SelectBuilder) SelectStructWithTable(s any, table string) *SelectBuilder
SelectStructWithTable reflects and extracts the fields of the struct as the selected columns, which supports the tag named "sql" to modify the column name.
If the value of the tag is "-", however, the field will be ignored. If the tag contains the attribute "notpropagate", for the embeded struct, do not scan the fields of the embeded struct.
func (*SelectBuilder) SelectedColumns ¶
func (b *SelectBuilder) SelectedColumns() []string
SelectedColumns is the same as SelectedFullColumns, but returns the short names instead.
func (*SelectBuilder) SelectedFullColumns ¶
func (b *SelectBuilder) SelectedFullColumns() []string
SelectedFullColumns returns the full names of the selected columns.
Notice: if the column has the alias, the alias will be returned instead.
func (*SelectBuilder) Selects ¶
func (b *SelectBuilder) Selects(columns ...string) *SelectBuilder
Selects is equal to b.Select(columns[0]).Select(columns[1])...
func (*SelectBuilder) SetDB ¶
func (b *SelectBuilder) SetDB(db *DB) *SelectBuilder
SetDB sets the db.
func (*SelectBuilder) Sort ¶ added in v0.27.0
func (b *SelectBuilder) Sort(sorts ...op.Sorter) *SelectBuilder
Sort appends the sorts.
func (*SelectBuilder) String ¶
func (b *SelectBuilder) String() string
String is the same as b.Build(), except args.
func (*SelectBuilder) Sum ¶ added in v0.31.0
func (b *SelectBuilder) Sum(field string) *SelectBuilder
SelectSum appends the selected SUM(field) column in SELECT.
func (*SelectBuilder) Where ¶
func (b *SelectBuilder) Where(andConditions ...op.Condition) *SelectBuilder
Where sets the WHERE conditions.
func (*SelectBuilder) WhereNamedArgs ¶
func (b *SelectBuilder) WhereNamedArgs(andArgs ...sql.NamedArg) *SelectBuilder
WhereNamedArgs is the same as Where, but uses the NamedArg as the condition.
type SqlCollector ¶ added in v0.36.0
type SqlCollector struct {
// contains filtered or unexported fields
}
SqlCollector is used to collect the executed sqls.
func NewSqlCollector ¶ added in v0.36.0
func NewSqlCollector() *SqlCollector
NewSqlCollector returns a new SqlCollector with enabled==true.
func (*SqlCollector) SetEnableFunc ¶ added in v0.36.0
func (c *SqlCollector) SetEnableFunc(enablef func() bool) *SqlCollector
SetEnableFunc sets whether to collect the executed sql.
It's not thread-safe and should be called after using.
func (*SqlCollector) SetEnabled ¶ added in v0.36.0
func (c *SqlCollector) SetEnabled(enabled bool) *SqlCollector
SetEnabled sets whether to collect the executed sql.
It's thread-safe. But It will have no effect if enablef is set.
func (*SqlCollector) SetFilterFunc ¶ added in v0.36.0
func (c *SqlCollector) SetFilterFunc(filterf func(sql string) bool) *SqlCollector
SetFilterFunc sets a filter function to decide to collect the sql only if filter returns true.
It's not thread-safe and should be called after using.
func (*SqlCollector) Sqls ¶ added in v0.36.0
func (c *SqlCollector) Sqls() []string
Sqls returns the executed sqls.
type Strings ¶ added in v0.39.0
type Strings []string
String is a string slice value type, which is encoded to a string or decoded from a []byte or string.
type Table ¶
Table represents a SQL table.
func (Table) DeleteFrom ¶
func (t Table) DeleteFrom(conds ...op.Condition) *DeleteBuilder
DeleteFrom returns a DELETE FROM builder.
func (Table) InsertInto ¶
func (t Table) InsertInto() *InsertBuilder
InsertInto returns a INSERT INTO builder.
func (Table) Select ¶
func (t Table) Select(column string) *SelectBuilder
Select is equal to t.GetDB().Select(column).
func (Table) SelectAlias ¶ added in v0.27.0
func (t Table) SelectAlias(column, alias string) *SelectBuilder
SelectAlias is equal to t.GetDB().SelectAlias(column, alias).
func (Table) SelectStruct ¶
func (t Table) SelectStruct(s any) *SelectBuilder
SelectStruct is equal to t.GetDB().SelectStructWithTable(s, "").
func (Table) SelectStructWithTable ¶ added in v0.27.0
func (t Table) SelectStructWithTable(s any, table string) *SelectBuilder
SelectStructWithTable is equal to t.GetDB().SelectStructWithTable(s, table).
func (Table) Selects ¶
func (t Table) Selects(columns ...string) *SelectBuilder
Selects is equal to t.GetDB().Selects(columns...).
func (Table) Update ¶
func (t Table) Update(updaters ...op.Updater) *UpdateBuilder
Update returns a UPDATE builder.
type Time ¶
type Time struct { Layout string // If empty, use defaults.TimeFormat instead when formatting time. time.Time }
Time is used to read/write the time.Time from/to DB.
func (Time) MarshalJSON ¶
MarshalJSON implements the interface json.Marshaler.
type UpdateBuilder ¶
type UpdateBuilder struct {
// contains filtered or unexported fields
}
UpdateBuilder is used to build the UPDATE statement.
Example ¶
// No Where update1 := Update().Table("table"). Set(op.Add("c1", 11), op.Sub("c2", 22)). Set(op.Mul("c3", 33), op.Div("c4", 44)) // With Where update2 := Update().Table("table"). Set(op.Set("c1", "v1"), op.Inc("c2"), op.Dec("c3")). Where(op.Equal("c4", "v4"), op.NotEqual("c5", "v5")). Where(op.Like("c6", "v6"), op.NotLike("c7", "v7%")). Where(op.Between("c8", 11, 22)) sql1, args1 := update1.Build() sql2, args2 := update2.SetDB(&DB{Dialect: Postgres}).Build() fmt.Println(sql1) fmt.Println(args1.Args()) fmt.Println(sql2) fmt.Println(args2.Args())
Output: UPDATE `table` SET `c1`=`c1`+?, `c2`=`c2`-?, `c3`=`c3`*?, `c4`=`c4`/? [11 22 33 44] UPDATE "table" SET "c1"=$1, "c2"="c2"+1, "c3"="c3"-1 WHERE ("c4"=$2 AND "c5"<>$3 AND "c6" LIKE $4 AND "c7" NOT LIKE $5 AND "c8" BETWEEN $6 AND $7) [v1 v4 v5 %v6% v7% 11 22]
func NewUpdateBuilder ¶
func NewUpdateBuilder(table ...string) *UpdateBuilder
NewUpdateBuilder returns a new UPDATE builder.
func (*UpdateBuilder) Build ¶
func (b *UpdateBuilder) Build() (sql string, args *ArgsBuilder)
Build builds the "UPDATE" sql statement.
func (*UpdateBuilder) Comment ¶ added in v0.37.0
func (b *UpdateBuilder) Comment(comment string) *UpdateBuilder
Comment set the comment, which will be appended to the end of the built SQL statement.
func (*UpdateBuilder) Exec ¶
func (b *UpdateBuilder) Exec() (sql.Result, error)
Exec builds the sql and executes it by *sql.DB.
func (*UpdateBuilder) ExecContext ¶
ExecContext builds the sql and executes it by *sql.DB.
func (*UpdateBuilder) From ¶
func (b *UpdateBuilder) From(table string, alias ...string) *UpdateBuilder
From is equal to b.FromAlias(table, "").
func (*UpdateBuilder) FromAlias ¶ added in v0.27.0
func (b *UpdateBuilder) FromAlias(table string, alias string) *UpdateBuilder
From appends the "FROM table AS alias" statement.
If alias is empty, use "FROM table" instead.
func (*UpdateBuilder) JoinFull ¶
func (b *UpdateBuilder) JoinFull(table, alias string, ons ...JoinOn) *UpdateBuilder
JoinFull appends the "FULL JOIN table ON on..." statement.
func (*UpdateBuilder) JoinFullOuter ¶
func (b *UpdateBuilder) JoinFullOuter(table, alias string, ons ...JoinOn) *UpdateBuilder
JoinFullOuter appends the "FULL OUTER JOIN table ON on..." statement.
func (*UpdateBuilder) JoinLeft ¶
func (b *UpdateBuilder) JoinLeft(table, alias string, ons ...JoinOn) *UpdateBuilder
JoinLeft appends the "LEFT JOIN table ON on..." statement.
func (*UpdateBuilder) JoinLeftOuter ¶
func (b *UpdateBuilder) JoinLeftOuter(table, alias string, ons ...JoinOn) *UpdateBuilder
JoinLeftOuter appends the "LEFT OUTER JOIN table ON on..." statement.
func (*UpdateBuilder) JoinRight ¶
func (b *UpdateBuilder) JoinRight(table, alias string, ons ...JoinOn) *UpdateBuilder
JoinRight appends the "RIGHT JOIN table ON on..." statement.
func (*UpdateBuilder) JoinRightOuter ¶
func (b *UpdateBuilder) JoinRightOuter(table, alias string, ons ...JoinOn) *UpdateBuilder
JoinRightOuter appends the "RIGHT OUTER JOIN table ON on..." statement.
func (*UpdateBuilder) Set ¶
func (b *UpdateBuilder) Set(updaters ...op.Updater) *UpdateBuilder
Set appends the "SET" statement to setters.
func (*UpdateBuilder) SetDB ¶
func (b *UpdateBuilder) SetDB(db *DB) *UpdateBuilder
SetDB sets the DB to db.
func (*UpdateBuilder) SetNamedArg ¶
func (b *UpdateBuilder) SetNamedArg(args ...sql.NamedArg) *UpdateBuilder
SetNamedArg is the same as Set, but uses the NamedArg as the Setter.
func (*UpdateBuilder) String ¶
func (b *UpdateBuilder) String() string
String is the same as b.Build(), except args.
func (*UpdateBuilder) Table ¶
func (b *UpdateBuilder) Table(table string) *UpdateBuilder
Table is equal to b.TableAlias(table, "")
func (*UpdateBuilder) TableAlias ¶ added in v0.27.0
func (b *UpdateBuilder) TableAlias(table string, alias string) *UpdateBuilder
Table appends the "UPDATE table AS alias" statement.
If alias is empty, use "UPDATE table" instead.
func (*UpdateBuilder) Where ¶
func (b *UpdateBuilder) Where(andConditions ...op.Condition) *UpdateBuilder
Where appends the "WHERE" conditions.
func (*UpdateBuilder) WhereNamedArgs ¶
func (b *UpdateBuilder) WhereNamedArgs(andArgs ...sql.NamedArg) *UpdateBuilder
WhereNamedArgs is the same as Where, but uses the NamedArg as the EQUAL condition.
Source Files
¶
- args.go
- db.go
- dialect.go
- dml.go
- dml_delete.go
- dml_insert.go
- dml_oper.go
- dml_operation.go
- dml_select.go
- dml_select_bind_map.go
- dml_select_bind_row.go
- dml_select_bind_rows.go
- dml_update.go
- doc.go
- executor.go
- interceptor.go
- model.go
- op.go
- op_condition.go
- op_pagination.go
- op_updater.go
- table.go
- utils.go