Documentation
¶
Overview ¶
Package hey is a helper that quickly responds to the results of insert, delete, update, select SQL statements. You can also use hey to quickly build SQL statements.
Index ¶
- Constants
- func ArrayDiscard[V any](values []V, discard func(k int, v V) bool) []V
- func ArrayToArray[V any, W any](values []V, fc func(k int, v V) W) []W
- func ArrayToAssoc[V any, K comparable, W any](values []V, fc func(v V) (K, W)) map[K]W
- func AssocDiscard[K comparable, V any](values map[K]V, discard func(k K, v V) bool) map[K]V
- func AssocToArray[K comparable, V any, W any](values map[K]V, fc func(k K, v V) W) []W
- func AssocToAssoc[K comparable, V any, X comparable, Y any](values map[K]V, fc func(k K, v V) (X, Y)) map[X]Y
- func ConcatString(sss ...string) string
- func DiscardDuplicate[T comparable](discard func(tmp T) bool, dynamic ...T) (result []T)
- func EmptyMaker(maker Maker) bool
- func GetCount(get *Get, countColumns ...string) (count int64, err error)
- func GetCountGet(get *Get, result any, countColumn ...string) (int64, error)
- func GetCountQuery(get *Get, query func(rows *sql.Rows) (err error), countColumn ...string) (int64, error)
- func GetExists(get *Get) (exists bool, err error)
- func GetGet(get *Get, result any) error
- func GetQuery(get *Get, query func(rows *sql.Rows) (err error)) error
- func GetScanAll(get *Get, fc func(rows *sql.Rows) error) error
- func GetScanMap(get *Get) (result []map[string]any, err error)
- func GetScanOne(get *Get, dest ...any) error
- func InGroupValues[T any](values []T, fc func(tmp T) []any) [][]any
- func InValues[T any](values []T, fc func(tmp T) any) []any
- func LastNotEmptyString(sss []string) string
- func MakerScanAll[V any](ctx context.Context, way *Way, maker Maker, ...) ([]*V, error)
- func MakerScanOne[V any](ctx context.Context, way *Way, maker Maker, ...) (*V, error)
- func MergeArray[V any](values ...[]V) []V
- func MergeAssoc[K comparable, V any](values ...map[K]V) map[K]V
- func MustAffectedRows(affectedRows int64, err error) error
- func NullDefaultValue(prepare string, defaultValue string) string
- func ParcelCancelPrepare(prepare string) string
- func ParcelPrepare(prepare string) string
- func RowsScan(rows *sql.Rows, result any, tag string) error
- func ScanAll(rows *sql.Rows, fc func(rows *sql.Rows) error) (err error)
- func ScanMap(rows *sql.Rows) ([]map[string]any, error)
- func ScanOne(rows *sql.Rows, dest ...any) error
- func SqlAlias(name string, alias string) string
- func SqlPrefix(prefix string, name string) string
- func StructInsert(object any, tag string, except []string, allow []string) (fields []string, values [][]any)
- func StructModify(object any, tag string, except ...string) (fields []string, values []any)
- func StructObtain(object any, tag string, except ...string) (fields []string, values []any)
- func StructUpdate(origin any, latest any, tag string, except ...string) (fields []string, values []any)
- type Add
- func (s *Add) Add() (int64, error)
- func (s *Add) AddOne(custom func(addOne AddOneReturnSequenceValue)) (int64, error)
- func (s *Add) ColumnValue(column string, value any) *Add
- func (s *Add) ColumnsValues(columns []string, values [][]any) *Add
- func (s *Add) Comment(comment string) *Add
- func (s *Add) Context(ctx context.Context) *Add
- func (s *Add) Create(create any) *Add
- func (s *Add) Default(add func(add *Add)) *Add
- func (s *Add) ExceptPermit(custom func(except SQLUpsertColumn, permit SQLUpsertColumn)) *Add
- func (s *Add) GetColumns() []string
- func (s *Add) GetContext() context.Context
- func (s *Add) GetValues() [][]any
- func (s *Add) GetWay() *Way
- func (s *Add) MakerValues(values Maker, columns []string) *Add
- func (s *Add) SetWay(way *Way) *Add
- func (s *Add) Table(table string) *Add
- func (s *Add) ToSQL() *SQL
- type AddOneReturnSequenceValue
- type Cache
- func (s *Cache) Del(key string) error
- func (s *Cache) DurationRange(duration time.Duration, minValue int, maxValue int) time.Duration
- func (s *Cache) Exists(key string) (exists bool, err error)
- func (s *Cache) Get(key string) (value []byte, exists bool, err error)
- func (s *Cache) GetBool(key string) (value bool, exists bool, err error)
- func (s *Cache) GetCacher() Cacher
- func (s *Cache) GetFloat(key string) (value float64, exists bool, err error)
- func (s *Cache) GetInt(key string) (value int64, exists bool, err error)
- func (s *Cache) GetString(key string) (value string, exists bool, err error)
- func (s *Cache) GetUnmarshal(key string, value any) (exists bool, err error)
- func (s *Cache) MarshalSet(key string, value any, duration ...time.Duration) error
- func (s *Cache) Set(key string, value []byte, duration ...time.Duration) error
- func (s *Cache) SetBool(key string, value bool, duration ...time.Duration) error
- func (s *Cache) SetCacher(cacher Cacher) *Cache
- func (s *Cache) SetFloat(key string, value float64, duration ...time.Duration) error
- func (s *Cache) SetInt(key string, value int64, duration ...time.Duration) error
- func (s *Cache) SetString(key string, value string, duration ...time.Duration) error
- type CacheMaker
- type Cacher
- type Cfg
- type Debugger
- type Del
- func (s *Del) Comment(comment string) *Del
- func (s *Del) Context(ctx context.Context) *Del
- func (s *Del) Del() (int64, error)
- func (s *Del) Filter(filters ...Filter) *Del
- func (s *Del) GetContext() context.Context
- func (s *Del) GetWay() *Way
- func (s *Del) SQLTable(sqlTable SQLTable) *Del
- func (s *Del) SetWay(way *Way) *Del
- func (s *Del) Table(table string, args ...any) *Del
- func (s *Del) ToSQL() *SQL
- func (s *Del) Where(where func(f Filter)) *Del
- func (s *Del) With(fc func(w SQLWith)) *Del
- type Empty
- type Filter
- type Get
- func (s *Get) Alias(alias string) *Get
- func (s *Get) Asc(column string) *Get
- func (s *Get) Comment(comment string) *Get
- func (s *Get) Context(ctx context.Context) *Get
- func (s *Get) Count(column ...string) (int64, error)
- func (s *Get) CountGet(result any, countColumn ...string) (int64, error)
- func (s *Get) CountQuery(query func(rows *sql.Rows) (err error), countColumn ...string) (int64, error)
- func (s *Get) CountSQL(columns ...string) *SQL
- func (s *Get) Desc(column string) *Get
- func (s *Get) Exists() (bool, error)
- func (s *Get) Filter(filters ...Filter) *Get
- func (s *Get) Get(result any) error
- func (s *Get) GetContext() context.Context
- func (s *Get) GetSelect() SQLSelect
- func (s *Get) GetWay() *Way
- func (s *Get) Group(columns ...string) *Get
- func (s *Get) GroupBy(fc func(g SQLGroupBy)) *Get
- func (s *Get) Having(having func(f Filter)) *Get
- func (s *Get) Join(custom func(join SQLJoin)) *Get
- func (s *Get) Limit(limit int64) *Get
- func (s *Get) Limiter(limiter Limiter) *Get
- func (s *Get) Offset(offset int64) *Get
- func (s *Get) Order(order string, replaces ...map[string]string) *Get
- func (s *Get) OrderBy(fc func(o SQLOrderBy)) *Get
- func (s *Get) Query(query func(rows *sql.Rows) (err error)) error
- func (s *Get) ScanAll(fc func(rows *sql.Rows) error) error
- func (s *Get) ScanMap() ([]map[string]any, error)
- func (s *Get) ScanOne(dest ...any) error
- func (s *Get) Select(columns ...string) *Get
- func (s *Get) SetSelect(sqlSelect SQLSelect) *Get
- func (s *Get) SetWay(way *Way) *Get
- func (s *Get) Subquery(subquery Maker, alias string) *Get
- func (s *Get) Table(table string) *Get
- func (s *Get) ToSQL() *SQL
- func (s *Get) Where(where func(f Filter)) *Get
- func (s *Get) With(fc func(w SQLWith)) *Get
- type Limiter
- type Maker
- func ExceptMaker(elements ...Maker) Maker
- func IntersectMaker(elements ...Maker) Maker
- func JoinMaker(elements []Maker, separators ...string) Maker
- func Makers(elements ...Maker) []Maker
- func ParcelCancelMaker(maker Maker) Maker
- func ParcelMaker(maker Maker) Maker
- func UnionAllMaker(elements ...Maker) Maker
- func UnionMaker(elements ...Maker) Maker
- type Manual
- type MinMaxDuration
- type Mod
- func (s *Mod) ColumnsValues(columns []string, values []any) *Mod
- func (s *Mod) Comment(comment string) *Mod
- func (s *Mod) Compare(old, new any, except ...string) *Mod
- func (s *Mod) Context(ctx context.Context) *Mod
- func (s *Mod) Decr(column string, value any) *Mod
- func (s *Mod) Default(custom func(mod *Mod)) *Mod
- func (s *Mod) ExceptPermit(custom func(except SQLUpsertColumn, permit SQLUpsertColumn)) *Mod
- func (s *Mod) Expr(expr string, args ...any) *Mod
- func (s *Mod) Filter(filters ...Filter) *Mod
- func (s *Mod) GetContext() context.Context
- func (s *Mod) GetUpdateSet() *SQL
- func (s *Mod) GetWay() *Way
- func (s *Mod) Incr(column string, value any) *Mod
- func (s *Mod) Mod() (int64, error)
- func (s *Mod) Set(column string, value any) *Mod
- func (s *Mod) SetWay(way *Way) *Mod
- func (s *Mod) Table(table string, args ...any) *Mod
- func (s *Mod) ToSQL() *SQL
- func (s *Mod) Update(update any) *Mod
- func (s *Mod) Where(where func(f Filter)) *Mod
- func (s *Mod) With(fc func(w SQLWith)) *Mod
- type Quantifier
- type Reader
- type Replace
- type RowsScanMakeSliceLength
- type SQL
- type SQLCase
- type SQLGroupBy
- type SQLInsertOnConflict
- type SQLInsertOnConflictUpdateSet
- type SQLInsertValue
- type SQLJoin
- type SQLJoinAssoc
- type SQLJoinOn
- type SQLLimit
- type SQLOrderBy
- type SQLOrderByLimit
- type SQLSelect
- type SQLTable
- type SQLUpdateSet
- type SQLUpsertColumn
- type SQLWhenThen
- type SQLWindowFuncFrame
- type SQLWith
- type Stmt
- func (s *Stmt) Close() (err error)
- func (s *Stmt) Exec(args ...any) (int64, error)
- func (s *Stmt) ExecContext(ctx context.Context, args ...any) (int64, error)
- func (s *Stmt) Execute(args ...any) (sql.Result, error)
- func (s *Stmt) ExecuteContext(ctx context.Context, args ...any) (sql.Result, error)
- func (s *Stmt) Query(query func(rows *sql.Rows) error, args ...any) error
- func (s *Stmt) QueryContext(ctx context.Context, query func(rows *sql.Rows) error, args ...any) error
- func (s *Stmt) QueryRow(query func(rows *sql.Row) error, args ...any) (err error)
- func (s *Stmt) QueryRowContext(ctx context.Context, query func(rows *sql.Row) error, args ...any) error
- func (s *Stmt) TakeAll(result any, args ...any) error
- func (s *Stmt) TakeAllContext(ctx context.Context, result any, args ...any) error
- type StringMutex
- type TableColumn
- func (s *TableColumn) AVG(column string, aliases ...string) string
- func (s *TableColumn) Adjust(adjust func(column string) string, columns ...string) []string
- func (s *TableColumn) Alias() string
- func (s *TableColumn) Avg(column string, aliases ...string) string
- func (s *TableColumn) Column(column string, aliases ...string) string
- func (s *TableColumn) ColumnAll(columns ...string) []string
- func (s *TableColumn) Count(counts ...string) string
- func (s *TableColumn) MAX(column string, aliases ...string) string
- func (s *TableColumn) MIN(column string, aliases ...string) string
- func (s *TableColumn) Max(column string, aliases ...string) string
- func (s *TableColumn) Min(column string, aliases ...string) string
- func (s *TableColumn) SUM(column string, aliases ...string) string
- func (s *TableColumn) SetAlias(alias string) *TableColumn
- func (s *TableColumn) Sum(column string, aliases ...string) string
- type Way
- func (s *Way) Add(table string) *Add
- func (s *Way) Begin(ctx context.Context, opts ...*sql.TxOptions) (*Way, error)
- func (s *Way) BeginConn(ctx context.Context, conn *sql.Conn, opts ...*sql.TxOptions) (*Way, error)
- func (s *Way) Commit() error
- func (s *Way) Debug(maker Maker) *Way
- func (s *Way) Del(table string) *Del
- func (s *Way) Exec(prepare string, args ...any) (int64, error)
- func (s *Way) ExecContext(ctx context.Context, prepare string, args ...any) (int64, error)
- func (s *Way) Execute(prepare string, args ...any) (sql.Result, error)
- func (s *Way) ExecuteContext(ctx context.Context, prepare string, args ...any) (sql.Result, error)
- func (s *Way) F(filters ...Filter) Filter
- func (s *Way) Get(table ...string) *Get
- func (s *Way) GetCfg() *Cfg
- func (s *Way) GetDatabase() *sql.DB
- func (s *Way) GetLogger() *logger.Logger
- func (s *Way) GetReader() Reader
- func (s *Way) Getter(query func(rows *sql.Rows) error, prepare string, args ...any) error
- func (s *Way) GetterContext(ctx context.Context, query func(rows *sql.Rows) error, prepare string, ...) (err error)
- func (s *Way) IsInTransaction() bool
- func (s *Way) IsRead() bool
- func (s *Way) MakerExec(maker Maker) (int64, error)
- func (s *Way) MakerExecContext(ctx context.Context, maker Maker) (int64, error)
- func (s *Way) MakerExecute(maker Maker) (sql.Result, error)
- func (s *Way) MakerExecuteContext(ctx context.Context, maker Maker) (sql.Result, error)
- func (s *Way) MakerQuery(maker Maker, query func(rows *sql.Rows) error) error
- func (s *Way) MakerQueryContext(ctx context.Context, maker Maker, query func(rows *sql.Rows) error) error
- func (s *Way) MakerQueryRow(maker Maker, query func(row *sql.Row) error) error
- func (s *Way) MakerQueryRowContext(ctx context.Context, maker Maker, query func(row *sql.Row) error) error
- func (s *Way) MakerTakeAll(maker Maker, result any) error
- func (s *Way) MakerTakeAllContext(ctx context.Context, maker Maker, result any) error
- func (s *Way) MakersExec(makers []Maker) (affectedRows int64, err error)
- func (s *Way) MakersExecContext(ctx context.Context, makers []Maker) (affectedRows int64, err error)
- func (s *Way) MakersTakeAll(makers []Maker, results []any) error
- func (s *Way) MakersTakeAllContext(ctx context.Context, makers []Maker, results []any) (err error)
- func (s *Way) Mod(table string) *Mod
- func (s *Way) NewAddOne(prepare string, args ...any) AddOneReturnSequenceValue
- func (s *Way) NewAddOneMaker(insert Maker) AddOneReturnSequenceValue
- func (s *Way) NewInsertOnConflict(prepare string, args ...any) SQLInsertOnConflict
- func (s *Way) NewInsertOnConflictMaker(insert Maker) SQLInsertOnConflict
- func (s *Way) NewOrderByLimit(maker Maker) SQLOrderByLimit
- func (s *Way) Now() time.Time
- func (s *Way) Prepare(prepare string) (*Stmt, error)
- func (s *Way) PrepareContext(ctx context.Context, prepare string) (stmt *Stmt, err error)
- func (s *Way) Query(query func(rows *sql.Rows) error, prepare string, args ...any) error
- func (s *Way) QueryContext(ctx context.Context, query func(rows *sql.Rows) error, prepare string, ...) error
- func (s *Way) QueryRow(query func(row *sql.Row) error, prepare string, args ...any) error
- func (s *Way) QueryRowContext(ctx context.Context, query func(row *sql.Row) error, prepare string, ...) error
- func (s *Way) Read() *Way
- func (s *Way) Replace(key string) string
- func (s *Way) Replaces(keys []string) []string
- func (s *Way) Rollback() error
- func (s *Way) ScanAll(rows *sql.Rows, fc func(rows *sql.Rows) error) error
- func (s *Way) ScanOne(rows *sql.Rows, dest ...any) error
- func (s *Way) SetCfg(cfg *Cfg) *Way
- func (s *Way) SetDatabase(db *sql.DB) *Way
- func (s *Way) SetLogger(l *logger.Logger) *Way
- func (s *Way) SetReader(reader Reader) *Way
- func (s *Way) Setter(prepare string, args ...any) (int64, error)
- func (s *Way) SetterContext(ctx context.Context, prepare string, args ...any) (int64, error)
- func (s *Way) StmtBatchExec(prepare string, lists [][]any) (affectedRows int64, err error)
- func (s *Way) StmtBatchExecContext(ctx context.Context, prepare string, lists [][]any) (affectedRows int64, err error)
- func (s *Way) StmtBatchTakeAll(prepare string, lists [][]any, results []any) error
- func (s *Way) StmtBatchTakeAllContext(ctx context.Context, prepare string, lists [][]any, results []any) (err error)
- func (s *Way) T() *TableColumn
- func (s *Way) TA() *TableColumn
- func (s *Way) TB() *TableColumn
- func (s *Way) TC() *TableColumn
- func (s *Way) TD() *TableColumn
- func (s *Way) TE() *TableColumn
- func (s *Way) TF() *TableColumn
- func (s *Way) TG() *TableColumn
- func (s *Way) TakeAll(result any, prepare string, args ...any) error
- func (s *Way) TakeAllContext(ctx context.Context, result any, prepare string, args ...any) error
- func (s *Way) Transaction(ctx context.Context, fc func(tx *Way) error, opts ...*sql.TxOptions) error
- func (s *Way) TransactionMessage(message string) *Way
- func (s *Way) TransactionNew(ctx context.Context, fc func(tx *Way) error, opts ...*sql.TxOptions) error
- func (s *Way) TransactionRetry(ctx context.Context, retries int, fc func(tx *Way) error, ...) (err error)
- func (s *Way) V(values ...*Way) *Way
- func (s *Way) W(values ...*Way) *Way
- func (s *Way) WindowFunc(alias ...string) *WindowFunc
- type WindowFunc
- func (s *WindowFunc) Alias(alias string) *WindowFunc
- func (s *WindowFunc) Asc(column string) *WindowFunc
- func (s *WindowFunc) Avg(column string) *WindowFunc
- func (s *WindowFunc) Count(columns ...string) *WindowFunc
- func (s *WindowFunc) DenseRank() *WindowFunc
- func (s *WindowFunc) Desc(column string) *WindowFunc
- func (s *WindowFunc) FirstValue(column string) *WindowFunc
- func (s *WindowFunc) Lag(column string, offset int64, defaultValue any) *WindowFunc
- func (s *WindowFunc) LastValue(column string) *WindowFunc
- func (s *WindowFunc) Lead(column string, offset int64, defaultValue any) *WindowFunc
- func (s *WindowFunc) Max(column string) *WindowFunc
- func (s *WindowFunc) Min(column string) *WindowFunc
- func (s *WindowFunc) NTile(buckets int64) *WindowFunc
- func (s *WindowFunc) NthValue(column string, lineNumber int64) *WindowFunc
- func (s *WindowFunc) Partition(column ...string) *WindowFunc
- func (s *WindowFunc) Range(fc func(frame SQLWindowFuncFrame)) *WindowFunc
- func (s *WindowFunc) Rank() *WindowFunc
- func (s *WindowFunc) RowNumber() *WindowFunc
- func (s *WindowFunc) Rows(fc func(frame SQLWindowFuncFrame)) *WindowFunc
- func (s *WindowFunc) Sum(column string) *WindowFunc
- func (s *WindowFunc) ToSQL() *SQL
- func (s *WindowFunc) Window(window string, args ...any) *WindowFunc
Constants ¶
const ( // DefaultTag Mapping of default database column name and struct tag. DefaultTag = "db" // EmptyString Empty string value. EmptyString = "" )
const ( SqlConcat = ", " SqlPoint = "." SqlSpace = " " SqlStar = "*" SqlAs = "AS" SqlAsc = "ASC" SqlDesc = "DESC" SqlUnion = "UNION" SqlUnionAll = "UNION ALL" SqlJoinInner = "INNER JOIN" SqlJoinLeft = "LEFT JOIN" SqlJoinRight = "RIGHT JOIN" SqlJoinFull = "FULL JOIN" SqlJoinCross = "CROSS JOIN" SqlAnd = "AND" SqlOr = "OR" SqlNot = "NOT" SqlNull = "NULL" SqlPlaceholder = "?" SqlEqual = "=" SqlNotEqual = "<>" SqlLessThan = "<" SqlLessThanEqual = "<=" SqlMoreThan = ">" SqlMoreThanEqual = ">=" SqlAll = "ALL" SqlAny = "ANY" SqlLeftSmallBracket = "(" SqlRightSmallBracket = ")" SqlExpect = "EXCEPT" SqlIntersect = "INTERSECT" SqlCoalesce = "COALESCE" SqlDistinct = "DISTINCT" SqlSelect = "SELECT" SqlInsert = "INSERT" SqlUpdate = "UPDATE" SqlDelete = "DELETE" SqlFrom = "FROM" SqlInto = "INTO" SqlValues = "VALUES" SqlSet = "SET" SqlWhere = "WHERE" SqlBetween = "BETWEEN" SqlConflict = "CONFLICT" SqlDo = "DO" SqlExcluded = "EXCLUDED" SqlExists = "EXISTS" SqlGroupBy = "GROUP BY" SqlHaving = "HAVING" SqlIn = "IN" SqlIs = "IS" SqlLike = "LIKE" SqlLimit = "LIMIT" SqlNothing = "NOTHING" SqlOffset = "OFFSET" SqlOn = "ON" SqlOrderBy = "ORDER BY" SqlOver = "OVER" SqlPartitionBy = "PARTITION BY" SqlUsing = "USING" SqlWith = "WITH" SqlCase = "CASE" SqlWhen = "WHEN" SqlThen = "THEN" SqlElse = "ELSE" SqlEnd = "END" SqlRange = "RANGE" SqlRows = "ROWS" )
const ( AliasA = "a" AliasB = "b" AliasC = "c" AliasD = "d" AliasE = "e" AliasF = "f" AliasG = "g" )
const ( // ErrNoRows Error no rows. ErrNoRows = sqlError("hey: no rows") // ErrNoRowsAffected Error no rows affected. ErrNoRowsAffected = sqlError("hey: no rows affected") )
const ( State0 = 0 State1 = 1 StateY = "Y" StateN = "N" StateYes = "YES" StateNo = "NO" StateOn = "ON" StateOff = "OFF" )
const (
DefaultAliasNameCount = "counts"
)
Variables ¶
This section is empty.
Functions ¶
func ArrayDiscard ¶
func ArrayToArray ¶
func ArrayToAssoc ¶
func ArrayToAssoc[V any, K comparable, W any](values []V, fc func(v V) (K, W)) map[K]W
func AssocDiscard ¶
func AssocDiscard[K comparable, V any](values map[K]V, discard func(k K, v V) bool) map[K]V
func AssocToArray ¶
func AssocToArray[K comparable, V any, W any](values map[K]V, fc func(k K, v V) W) []W
func AssocToAssoc ¶
func AssocToAssoc[K comparable, V any, X comparable, Y any](values map[K]V, fc func(k K, v V) (X, Y)) map[X]Y
func DiscardDuplicate ¶
func DiscardDuplicate[T comparable](discard func(tmp T) bool, dynamic ...T) (result []T)
DiscardDuplicate discard duplicate element.
func EmptyMaker ¶
EmptyMaker Check whether the result (SQL statement) of Maker is empty.
func GetCountGet ¶
GetCountGet execute the built SQL statement and scan query results, count + get.
func GetCountQuery ¶
func GetCountQuery(get *Get, query func(rows *sql.Rows) (err error), countColumn ...string) (int64, error)
GetCountQuery execute the built SQL statement and scan query result, count + query.
func GetScanAll ¶
GetScanAll execute the built SQL statement and scan all from the query results.
func GetScanMap ¶
GetScanMap execute the built SQL statement and scan all from the query results.
func GetScanOne ¶
GetScanOne execute the built SQL statement and scan at most once from the query results.
func InGroupValues ¶
InGroupValues Build ( column1, column2, column3 ... ) IN ( ( values[0].attribute1, values[0].attribute2, values[0].attribute3 ... ), ( values[1].attribute1, values[1].attribute2, values[1].attribute3 ... ) ... )
func InValues ¶
InValues Build column IN ( values[0].attributeN, values[1].attributeN, values[2].attributeN ... )
func LastNotEmptyString ¶
LastNotEmptyString get last not empty string, return empty string if it does not exist.
func MakerScanAll ¶
func MakerScanAll[V any](ctx context.Context, way *Way, maker Maker, scan func(rows *sql.Rows, v *V) error) ([]*V, error)
MakerScanAll Rows scan to any struct, based on struct scan data.
func MakerScanOne ¶
func MakerScanOne[V any](ctx context.Context, way *Way, maker Maker, scan func(rows *sql.Rows, v *V) error) (*V, error)
MakerScanOne Rows scan to any struct, based on struct scan data.
func MergeArray ¶
func MergeArray[V any](values ...[]V) []V
func MergeAssoc ¶
func MergeAssoc[K comparable, V any](values ...map[K]V) map[K]V
func MustAffectedRows ¶
MustAffectedRows at least one row is affected.
func NullDefaultValue ¶
NullDefaultValue Use defaultValue to replace NULL values.
func ParcelCancelPrepare ¶
ParcelCancelPrepare Cancel parcel the SQL statement. ( `subquery` ) => `subquery` OR ( ( `subquery` ) ) => ( `subquery` )
func ParcelPrepare ¶
ParcelPrepare Parcel the SQL statement. `subquery` => ( `subquery` )
func RowsScan ¶
RowsScan Scan the query result set into the receiving object. Support type *AnyStruct, **AnyStruct, *[]AnyStruct, *[]*AnyStruct, **[]AnyStruct, **[]*AnyStruct ...
func StructInsert ¶
func StructInsert(object any, tag string, except []string, allow []string) (fields []string, values [][]any)
StructInsert object should be one of struct{}, *struct{}, []struct, []*struct{}, *[]struct{}, *[]*struct{}. get fields and values based on struct tag.
func StructModify ¶
StructModify object should be one of anyStruct, *anyStruct get the fields and values that need to be modified.
func StructObtain ¶
StructObtain object should be one of anyStruct, *anyStruct for get all fields and values.
Types ¶
type Add ¶
type Add struct {
// contains filtered or unexported fields
}
Add for INSERT.
func (*Add) AddOne ¶
func (s *Add) AddOne(custom func(addOne AddOneReturnSequenceValue)) (int64, error)
AddOne execute the built SQL statement, return the sequence value of the data.
func (*Add) ColumnValue ¶
ColumnValue append column-value for insert one or more rows.
func (*Add) ColumnsValues ¶
ColumnsValues set columns and values.
func (*Add) Create ¶
Create value of creation should be one of struct{}, *struct{}, map[string]any, []struct, []*struct{}, *[]struct{}, *[]*struct{}.
func (*Add) ExceptPermit ¶
func (s *Add) ExceptPermit(custom func(except SQLUpsertColumn, permit SQLUpsertColumn)) *Add
ExceptPermit Set a list of columns that are not allowed to be inserted and a list of columns that are only allowed to be inserted.
func (*Add) MakerValues ¶
MakerValues values is a query SQL statement.
type AddOneReturnSequenceValue ¶
type AddOneReturnSequenceValue interface {
Maker
// Context Custom context.
Context(ctx context.Context) AddOneReturnSequenceValue
// Prepare You may need to modify the SQL statement to be executed.
Prepare(prepare func(tmp *SQL)) AddOneReturnSequenceValue
// Execute Customize the method to return the sequence value of inserted data.
Execute(execute func(ctx context.Context, stmt *Stmt, args ...any) (sequenceValue int64, err error)) AddOneReturnSequenceValue
// AddOne Insert a record and return the sequence value of the data (usually an auto-incrementing id value).
AddOne() (int64, error)
}
AddOneReturnSequenceValue Insert a record and return the sequence value of the data (usually an auto-incrementing id value).
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache Read and write data in cache.
func (*Cache) DurationRange ¶
DurationRange Get a random Duration between minValue*duration and maxValue*duration.
func (*Cache) GetUnmarshal ¶
GetUnmarshal Read cached data from the cache and deserialize cached data.
func (*Cache) MarshalSet ¶
MarshalSet Serialize cache data and write the serialized data to the cache.
type CacheMaker ¶
type CacheMaker interface {
// GetCacheKey Use prepare and args to calculate the hash value as the cache key.
GetCacheKey() (string, error)
// UseCacheKey Custom build cache key.
UseCacheKey(cacheKey func(maker Maker) (string, error)) CacheMaker
// Reset For reset maker and it's related property values.
Reset(maker ...Maker) CacheMaker
// Get For get value from cache.
Get() (value []byte, exists bool, err error)
// Set For set value to cache.
Set(value []byte, duration ...time.Duration) error
// Del Delete data in the cache based on cache key.
Del() error
// Exists Check whether the cache key exists.
Exists() (exists bool, err error)
// GetUnmarshal Query data and unmarshal data.
GetUnmarshal(value any) (exists bool, err error)
// MarshalSet Marshal data and set data.
MarshalSet(value any, duration ...time.Duration) error
// GetString Get string type value.
GetString() (string, bool, error)
// SetString Set string type value.
SetString(value string, duration ...time.Duration) error
// GetFloat Get float64 type value.
GetFloat() (float64, bool, error)
// SetFloat Set float64 type value.
SetFloat(value float64, duration ...time.Duration) error
// GetInt Get int64 type value.
GetInt() (int64, bool, error)
// SetInt Set int64 type value.
SetInt(value int64, duration ...time.Duration) error
// GetBool Get boolean type value.
GetBool() (bool, bool, error)
// SetBool Set boolean type value.
SetBool(value bool, duration ...time.Duration) error
}
CacheMaker Cache SQL statement related data, including but not limited to cache query data.
func NewCacheMaker ¶
func NewCacheMaker(cache *Cache, maker Maker) CacheMaker
NewCacheMaker Create a new CacheMaker object.
type Cacher ¶
type Cacher interface {
// Key Customize cache key processing before reading and writing cache.
Key(key string) string
// Get Reading data from the cache.
Get(key string) (value []byte, exists bool, err error)
// Set Writing data to the cache.
Set(key string, value []byte, duration ...time.Duration) error
// Del Deleting data from the cache.
Del(key string) error
// Exists Check if a certain data exists in the cache.
Exists(key string) (exists bool, err error)
// Marshal Serialize cache data.
Marshal(v any) ([]byte, error)
// Unmarshal Deserialize cache data.
Unmarshal(data []byte, v any) error
}
Cacher Objects that implement cache.
type Cfg ¶
type Cfg struct {
// Debugger Debug output SQL script.
Debugger Debugger
// Manual For handling different types of databases.
Manual *Manual
// Scan Scan data into structure.
Scan func(rows *sql.Rows, result any, tag string) error
// TransactionOptions Start transaction.
TransactionOptions *sql.TxOptions
// ScanTag Scan data to tag mapping on structure.
ScanTag string
// TransactionMaxDuration Maximum transaction execution time.
TransactionMaxDuration time.Duration
// WarnDuration SQL execution time warning threshold.
WarnDuration time.Duration
// DeleteMustUseWhere Deletion of data must be filtered using conditions.
DeleteMustUseWhere bool
// UpdateMustUseWhere Updated data must be filtered using conditions.
UpdateMustUseWhere bool
}
Cfg Configure of Way.
type Debugger ¶
type Debugger interface {
// Debug Output SQL script to the specified output stream.
Debug(maker Maker) Debugger
GetLogger() *logger.Logger
SetLogger(log *logger.Logger) Debugger
}
Debugger Debug output SQL script.
func NewDebugger ¶
func NewDebugger() Debugger
type Del ¶
type Del struct {
// contains filtered or unexported fields
}
Del for DELETE.
type Filter ¶
type Filter interface {
Maker
// Clean Clear the existing conditional filtering of the current object.
Clean() Filter
// Num Number of conditions used.
Num() int
// Empty Is the current object an empty object?
Empty() bool
// Not Negate the result of the current conditional filter object. Multiple negations are allowed.
Not() Filter
// And Use logical operator `AND` to combine custom conditions.
And(prepare string, args ...any) Filter
// Or Use logical operator `OR` to combine custom conditions.
Or(prepare string, args ...any) Filter
// Group Add a new condition group, which is connected by the `AND` logical operator by default.
Group(group func(f Filter)) Filter
// OrGroup Add a new condition group, which is connected by the `OR` logical operator by default.
OrGroup(group func(f Filter)) Filter
// Use Implement import a set of conditional filter objects into the current object.
Use(filters ...Filter) Filter
// New Create a new conditional filter object based on a set of conditional filter objects.
New(filters ...Filter) Filter
// Equal Implement conditional filtering: column = value .
Equal(column string, value any, usingNull ...bool) Filter
// LessThan Implement conditional filtering: column < value .
LessThan(column string, value any) Filter
// LessThanEqual Implement conditional filtering: column <= value .
LessThanEqual(column string, value any) Filter
// MoreThan Implement conditional filtering: column > value.
MoreThan(column string, value any) Filter
// MoreThanEqual Implement conditional filtering: column >= value .
MoreThanEqual(column string, value any) Filter
// Between Implement conditional filtering: column BETWEEN value1 AND value2 .
Between(column string, start any, end any) Filter
// In Implement conditional filtering: column IN ( value1, value2, value3... ) .
In(column string, values ...any) Filter
// InQuery Implement conditional filtering: column IN (subquery).
InQuery(column string, subquery Maker) Filter
// Exists Implement conditional filtering: EXISTS (subquery) .
Exists(subquery Maker) Filter
// Like Implement conditional filtering: column LIKE value.
Like(column string, value any) Filter
// IsNull Implement conditional filtering: column IS NULL .
IsNull(column string) Filter
// InGroup Implement conditional filtering: ( column1, column2, column3... ) IN ( ( value1, value2, value3... ), ( value21, value22, value23... )... ) .
InGroup(columns []string, values ...[]any) Filter
// InGroupQuery Implement conditional filtering: ( column1, column2, column3... ) IN ( subquery ) .
InGroupQuery(columns []string, subquery Maker) Filter
// NotEqual Implement conditional filtering: column <> value .
NotEqual(column string, value any, notUsingNull ...bool) Filter
// NotBetween Implement conditional filtering: column NOT BETWEEN value1 AND value2 .
NotBetween(column string, start any, end any) Filter
// NotIn Implement conditional filtering: column NOT IN ( value1, value2, value3... ) .
NotIn(column string, values ...any) Filter
// NotInGroup Implement conditional filtering: ( column1, column2, column3... ) NOT IN ( ( value1, value2, value3... ), ( value21, value22, value23... )... ) .
NotInGroup(columns []string, values ...[]any) Filter
// NotLike Implement conditional filtering: column NOT LIKE value .
NotLike(column string, value any) Filter
// IsNotNull Implement conditional filtering: column IS NOT NULL .
IsNotNull(column string) Filter
// AllQuantifier Implement conditional filtering: column {=||<>||>||>=||<||<=} ALL ( subquery ) .
AllQuantifier(fc func(q Quantifier)) Filter
// AnyQuantifier Implement conditional filtering: column {=||<>||>||>=||<||<=} ANY ( subquery ) .
AnyQuantifier(fc func(q Quantifier)) Filter
// GetWay For get *Way.
GetWay() *Way
// SetWay For set *Way.
SetWay(way *Way) Filter
// Compare Implement conditional filtering: column1 {=||<>||>||>=||<||<=} column2 .
Compare(column1 string, compare string, column2 string, args ...any) Filter
// CompareEqual Implement conditional filtering: column1 = column2 .
CompareEqual(column1 string, column2 string, args ...any) Filter
// CompareNotEqual Implement conditional filtering: column1 <> column2 .
CompareNotEqual(column1 string, column2 string, args ...any) Filter
// CompareMoreThan Implement conditional filtering: column1 > column2 .
CompareMoreThan(column1 string, column2 string, args ...any) Filter
// CompareMoreThanEqual Implement conditional filtering: column1 >= column2 .
CompareMoreThanEqual(column1 string, column2 string, args ...any) Filter
// CompareLessThan Implement conditional filtering: column1 < column2.
CompareLessThan(column1 string, column2 string, args ...any) Filter
// CompareLessThanEqual Implement conditional filtering: column1 <= column2 .
CompareLessThanEqual(column1 string, column2 string, args ...any) Filter
}
Filter Implement SQL statement conditional filtering (general conditional filtering).
func ParcelFilter ¶
ParcelFilter Parcel the SQL filter statement. `SQL_FILTER_STATEMENT` => ( `SQL_FILTER_STATEMENT` )
type Get ¶
type Get struct {
// contains filtered or unexported fields
}
Get for SELECT.
func (*Get) Alias ¶
Alias for table alias name, remember to call the current method when the table is a SQL statement.
func (*Get) CountGet ¶
CountGet execute the built SQL statement and scan query result, count and get.
func (*Get) CountQuery ¶
func (s *Get) CountQuery(query func(rows *sql.Rows) (err error), countColumn ...string) (int64, error)
CountQuery execute the built SQL statement and scan query results, count + query.
func (*Get) GroupBy ¶
func (s *Get) GroupBy(fc func(g SQLGroupBy)) *Get
GroupBy set group expression.
func (*Get) Order ¶
Order set the column sorting list in batches through regular expressions according to the request parameter value.
func (*Get) ScanOne ¶
ScanOne execute the built SQL statement and scan at most once from the query results.
type Maker ¶
type Maker interface {
ToSQL() *SQL
}
Maker Construct an SQL statement, which may contain placeholders and their placeholder parameter lists.
func ExceptMaker ¶
ExceptMaker MakerA, MakerB ... => ( ( QUERY_A ) EXCEPT ( QUERY_B ) ... )
func IntersectMaker ¶
IntersectMaker MakerA, MakerB ... => ( ( QUERY_A ) INTERSECT ( QUERY_B ) ... )
func ParcelCancelMaker ¶
ParcelCancelMaker Cancel parcel the SQL statement. ( `subquery` ) => `subquery` OR ( ( `subquery` ) ) => ( `subquery` )
func ParcelMaker ¶
ParcelMaker Parcel the SQL statement. `subquery` => ( `subquery` )
func UnionAllMaker ¶
UnionAllMaker MakerA, MakerB, MakerC ... => ( ( QUERY_A ) UNION ALL ( QUERY_B ) UNION ALL ( QUERY_C ) ... )
func UnionMaker ¶
UnionMaker MakerA, MakerB, MakerC ... => ( ( QUERY_A ) UNION ( QUERY_B ) UNION ( QUERY_C ) ... )
type Manual ¶
type Manual struct {
// Prepare to adjust the SQL statement format to meet the current database SQL statement format.
Prepare func(prepare string) string
// Replace Helpers for handling different types of databases.
Replace Replace
}
Manual For handling different types of databases.
func Postgresql ¶
func Postgresql() *Manual
type MinMaxDuration ¶
type MinMaxDuration struct {
// contains filtered or unexported fields
}
func NewMinMaxDuration ¶
func NewMinMaxDuration(duration time.Duration, minValue int, maxValue int) *MinMaxDuration
NewMinMaxDuration The minimum value of all values should be granter than 0, unless you want to cache permanently.
func (*MinMaxDuration) Get ¶
func (s *MinMaxDuration) Get() time.Duration
type Mod ¶
type Mod struct {
// contains filtered or unexported fields
}
Mod for UPDATE.
func (*Mod) ColumnsValues ¶
ColumnsValues SET column = value by slice, require len(columns) == len(values).
func (*Mod) Compare ¶
Compare For compare old and new to automatically calculate the need to update columns.
func (*Mod) ExceptPermit ¶
func (s *Mod) ExceptPermit(custom func(except SQLUpsertColumn, permit SQLUpsertColumn)) *Mod
ExceptPermit Set a list of columns that are not allowed to be updated and a list of columns that are only allowed to be updated.
type Quantifier ¶
type Quantifier interface {
GetQuantifier() string
SetQuantifier(quantifierString string) Quantifier
Equal(column string, subquery Maker) Quantifier
NotEqual(column string, subquery Maker) Quantifier
LessThan(column string, subquery Maker) Quantifier
LessThanEqual(column string, subquery Maker) Quantifier
MoreThan(column string, subquery Maker) Quantifier
MoreThanEqual(column string, subquery Maker) Quantifier
}
Quantifier Implement the filter condition: column {=||<>||>||>=||<||<=} [QUANTIFIER ]( subquery ) . QUANTIFIER is usually one of ALL, ANY, SOME ... or EmptyString.
type Reader ¶
type Reader interface {
// Read Get an object for read.
Read() *Way
}
Reader Separate read and write, when you distinguish between reading and writing, please do not use the same object for both reading and writing.
type Replace ¶
type Replace interface {
Get(key string) string
Set(key string, value string) Replace
Del(key string) Replace
Map() map[string]string
Use(mapping map[string]string) Replace
// Gets Batch getting.
Gets(keys []string) []string
// Sets Batch setting.
Sets(mapping map[string]string) Replace
}
Replace For replacement identifiers in SQL statements. Replace by default, concurrent reads and writes are not safe. If you need concurrent read and write security, you can implement Replace by yourself.
func NewReplace ¶
func NewReplace() Replace
type RowsScanMakeSliceLength ¶
type RowsScanMakeSliceLength string
const (
MakerScanAllMakeSliceLength RowsScanMakeSliceLength = "maker_scan_all_make_slice_length"
)
type SQL ¶
type SQL struct {
// Prepare SQL statement.
Prepare string
// Args SQL statement corresponding parameter lists.
Args []any
}
func MakerGetCount ¶
MakerGetCount Build count query. SELECT COUNT(*) AS count FROM ( [WITH xxx] SELECT xxx FROM xxx [INNER JOIN xxx ON xxx] [WHERE xxx] [GROUP BY xxx [HAVING xxx]] ) AS a SELECT COUNT(*) AS count FROM ( query1 UNION [ALL] query2 [UNION [ALL] ...] ) AS a
func MakerGetSQL ¶
MakerGetSQL Build a complete query. [WITH xxx] SELECT xxx FROM xxx [INNER JOIN xxx ON xxx] [WHERE xxx] [GROUP BY xxx [HAVING xxx]] [ORDER BY xxx] [LIMIT xxx [OFFSET xxx]]
func MakerGetTable ¶
MakerGetTable Build query table (without ORDER BY, LIMIT, OFFSET). [WITH xxx] SELECT xxx FROM xxx [INNER JOIN xxx ON xxx] [WHERE xxx] [GROUP BY xxx [HAVING xxx]]
type SQLCase ¶
type SQLCase interface {
Maker
V(value string) string
Alias(alias string) SQLCase
Case(values ...any) SQLCase
When(fc func(w SQLWhenThen)) SQLCase
Else(values ...any) SQLCase
}
SQLCase Implementing SQL CASE.
func NewSQLCase ¶
type SQLGroupBy ¶
type SQLGroupBy interface {
Empty
Maker
Column(columns ...string) SQLGroupBy
Group(prepare string, args ...any) SQLGroupBy
GroupMaker(maker Maker) SQLGroupBy
Having(having func(having Filter)) SQLGroupBy
}
SQLGroupBy Constructing query groups.
func NewSQLGroupBy ¶
func NewSQLGroupBy(way *Way) SQLGroupBy
type SQLInsertOnConflict ¶
type SQLInsertOnConflict interface {
// OnConflict The column causing the conflict, such as a unique key or primary key, which can be a single column or multiple columns.
OnConflict(onConflicts ...string) SQLInsertOnConflict
// Do The SQL statement that needs to be executed when a data conflict occurs. By default, nothing is done.
Do(prepare string, args ...any) SQLInsertOnConflict
// DoUpdateSet SQL update statements executed when data conflicts occur.
DoUpdateSet(fc func(u SQLInsertOnConflictUpdateSet)) SQLInsertOnConflict
// ToSQL The SQL statement and its parameter list that are finally executed.
ToSQL() *SQL
// SQLInsertOnConflict Executes the SQL statement constructed by the current object.
SQLInsertOnConflict() (int64, error)
}
SQLInsertOnConflict Implement the following SQL statement: INSERT INTO ... ON CONFLICT (column_a[, column_b, column_c...]) DO NOTHING /* If a conflict occurs, the insert operation is ignored. */ INSERT INTO ... ON CONFLICT (column_a[, column_b, column_c...]) DO UPDATE SET column1 = EXCLUDED.column1, column2 = EXCLUDED.column2, column3 = EXCLUDED.column3, column4 = 'fixed value' ... /* If a conflict occurs, the existing row is updated with the new value */
func NewSQLInsertOnConflict ¶
func NewSQLInsertOnConflict(way *Way, insertPrepare string, insertArgs ...any) SQLInsertOnConflict
type SQLInsertOnConflictUpdateSet ¶
type SQLInsertOnConflictUpdateSet interface {
SQLUpdateSet
// Excluded Construct the update expression column1 = EXCLUDED.column1, column2 = EXCLUDED.column2, column3 = EXCLUDED.column3 ...
// This is how the `new` data is accessed that causes the conflict.
Excluded(columns ...string) SQLInsertOnConflictUpdateSet
}
SQLInsertOnConflictUpdateSet Implement the following SQL statement: INSERT INTO ... ON CONFLICT ( column_a[, column_b, column_c...] ) DO UPDATE SET column1 = EXCLUDED.column1, column2 = EXCLUDED.column2, column3 = EXCLUDED.column3, column4 = 'fixed value' ...
func NewSQLInsertOnConflictUpdateSet ¶
func NewSQLInsertOnConflictUpdateSet(way *Way) SQLInsertOnConflictUpdateSet
type SQLInsertValue ¶
type SQLInsertValue interface {
Empty
Maker
SetSubquery(subquery Maker) SQLInsertValue
SetValues(values ...[]any) SQLInsertValue
Set(index int, value any) SQLInsertValue
Del(indexes ...int) SQLInsertValue
LenValues() int
GetValues() [][]any
}
SQLInsertValue Constructing insert values.
func NewSQLInsertValue ¶
func NewSQLInsertValue() SQLInsertValue
type SQLJoin ¶
type SQLJoin interface {
Maker
GetMaster() SQLTable
SetMaster(master SQLTable) SQLJoin
NewTable(table string, alias string, args ...any) SQLTable
NewSubquery(subquery Maker, alias string) SQLTable
On(onList ...func(o SQLJoinOn, leftAlias string, rightAlias string)) SQLJoinAssoc
Using(columns ...string) SQLJoinAssoc
OnEqual(leftColumn string, rightColumn string) SQLJoinAssoc
Join(joinTypeString string, leftTable SQLTable, rightTable SQLTable, on SQLJoinAssoc) SQLJoin
InnerJoin(leftTable SQLTable, rightTable SQLTable, on SQLJoinAssoc) SQLJoin
LeftJoin(leftTable SQLTable, rightTable SQLTable, on SQLJoinAssoc) SQLJoin
RightJoin(leftTable SQLTable, rightTable SQLTable, on SQLJoinAssoc) SQLJoin
// Queries Get query columns.
Queries() SQLSelect
// TableColumn Build *TableColumn based on SQLTable.
TableColumn(table SQLTable) *TableColumn
// TableSelect Add the queried column list based on the table's alias prefix.
TableSelect(table SQLTable, columns ...string) []string
// TableSelectAliases Add the queried column list based on the table's alias prefix, support setting the query column alias.
TableSelectAliases(table SQLTable, aliases map[string]string, columns ...string) []string
// SelectGroupsColumns Add the queried column list based on the table's alias prefix.
SelectGroupsColumns(columns ...[]string) SQLJoin
// SelectTableColumnAlias Batch set multiple columns of the specified table and set aliases for all columns.
SelectTableColumnAlias(table SQLTable, columnAndColumnAlias ...string) SQLJoin
}
SQLJoin Constructing multi-table join queries.
func NewSQLJoin ¶
type SQLJoinAssoc ¶
SQLJoinAssoc Constructing conditions for join queries.
type SQLJoinOn ¶
type SQLJoinOn interface {
Maker
// Equal Use equal value JOIN ON condition.
Equal(leftAlias string, leftColumn string, rightAlias string, rightColumn string) SQLJoinOn
// Filter Append custom conditions to the ON statement or use custom conditions on the ON statement to associate tables.
Filter(fc func(f Filter)) SQLJoinOn
// Using Use USING instead of ON.
Using(using ...string) SQLJoinOn
}
type SQLLimit ¶
type SQLLimit interface {
Empty
Maker
Limit(limit int64) SQLLimit
Offset(offset int64) SQLLimit
Page(page int64, limit ...int64) SQLLimit
}
SQLLimit Constructing query limits.
func NewSQLLimit ¶
func NewSQLLimit() SQLLimit
type SQLOrderBy ¶
type SQLOrderBy interface {
Empty
Maker
Use(columns ...string) SQLOrderBy
Asc(columns ...string) SQLOrderBy
Desc(columns ...string) SQLOrderBy
}
SQLOrderBy Constructing query orders.
func NewSQLOrderBy ¶
func NewSQLOrderBy(way *Way) SQLOrderBy
type SQLOrderByLimit ¶
type SQLOrderByLimit interface {
Maker
// OrderBy Custom ORDER BY
OrderBy(fc func(o SQLOrderBy)) SQLOrderByLimit
// Asc ORDER BY column ASC
Asc(column string) SQLOrderByLimit
// Desc ORDER BY column DSC
Desc(column string) SQLOrderByLimit
// Order Custom ORDER BY parsed-string
Order(order string, replaces ...map[string]string) SQLOrderByLimit
// Limit LIMIT n
Limit(limit int64) SQLOrderByLimit
// Offset OFFSET n
Offset(offset int64) SQLOrderByLimit
// Limiter LIMIT + OFFSET
Limiter(limiter Limiter) SQLOrderByLimit
// Page LIMIT + OFFSET
Page(page int64, limit ...int64) SQLOrderByLimit
}
SQLOrderByLimit Construct the ORDER BY and LIMIT clauses or append the ORDER BY and LIMIT clauses to the end of the SQL statement.
func NewSQLOrderByLimit ¶
func NewSQLOrderByLimit(way *Way, maker Maker) SQLOrderByLimit
type SQLSelect ¶
type SQLSelect interface {
Empty
Maker
Distinct() SQLSelect
Index(column string) int
Exists(column string) bool
Add(column string, args ...any) SQLSelect
AddAll(columns ...string) SQLSelect
AddMaker(makers ...Maker) SQLSelect
DelAll(columns ...string) SQLSelect
Len() int
Get() ([]string, map[int][]any)
Set(columns []string, columnsArgs map[int][]any) SQLSelect
Use(sqlSelect ...SQLSelect) SQLSelect
// Queried Get all columns of the query results.
Queried(excepts ...string) []string
}
SQLSelect Used to build the list of columns to be queried.
func NewSQLSelect ¶
type SQLTable ¶
type SQLTable interface {
Empty
Maker
// Alias Setting aliases for script statements.
Alias(alias string) SQLTable
// GetAlias Getting aliases for script statements.
GetAlias() string
}
SQLTable Used to construct expressions that can use table aliases and their corresponding parameter lists.
func NewSQLTable ¶
func NewSQLTableGet ¶
type SQLUpdateSet ¶
type SQLUpdateSet interface {
Empty
Maker
Update(update string, args ...any) SQLUpdateSet
Set(column string, value any) SQLUpdateSet
Decr(column string, decr any) SQLUpdateSet
Incr(column string, incr any) SQLUpdateSet
SetMap(columnValue map[string]any) SQLUpdateSet
SetSlice(columns []string, values []any) SQLUpdateSet
Len() int
GetUpdate() (updates []string, args [][]any)
UpdateIndex(prepare string) int
UpdateExists(prepare string) bool
}
SQLUpdateSet Constructing update sets.
func NewSQLUpdateSet ¶
func NewSQLUpdateSet(way *Way) SQLUpdateSet
type SQLUpsertColumn ¶
type SQLUpsertColumn interface {
Empty
Maker
Add(columns ...string) SQLUpsertColumn
Del(columns ...string) SQLUpsertColumn
DelUseIndex(indexes ...int) SQLUpsertColumn
ColumnIndex(column string) int
ColumnExists(column string) bool
Len() int
SetColumns(columns []string) SQLUpsertColumn
GetColumns() []string
GetColumnsMap() map[string]*struct{}
}
SQLUpsertColumn Constructing insert columns.
func NewSQLUpsertColumn ¶
func NewSQLUpsertColumn(way *Way) SQLUpsertColumn
type SQLWhenThen ¶
type SQLWhenThen interface {
Maker
V(value string) string
When(values ...any) SQLWhenThen
Then(values ...any) SQLWhenThen
}
SQLWhenThen Store multiple pairs of WHEN xxx THEN xxx.
type SQLWindowFuncFrame ¶
type SQLWindowFuncFrame interface {
Maker
// Prepare Add SQL statement fragment.
Prepare(prepare string, args ...any) SQLWindowFuncFrame
// UnboundedPreceding Start of partition.
UnboundedPreceding() SQLWindowFuncFrame
// NPreceding First n rows.
NPreceding(n int) SQLWindowFuncFrame
// CurrentRow Current row.
CurrentRow() SQLWindowFuncFrame
// NFollowing After n rows.
NFollowing(n int) SQLWindowFuncFrame
// UnboundedFollowing End of partition.
UnboundedFollowing() SQLWindowFuncFrame
// Maker Custom SQL statement.
Maker(maker Maker) SQLWindowFuncFrame
}
SQLWindowFuncFrame Define a window based on a start and end, the end position can be omitted and SQL defaults to the current row. Allows independent use of custom SQL statements and parameters as values for ROWS or RANGE statements.
func NewSQLWindowFuncFrame ¶
func NewSQLWindowFuncFrame(frame string) SQLWindowFuncFrame
type SQLWith ¶
type SQLWith interface {
Empty
Maker
// Recursive Recursion or cancellation of recursion.
Recursive() SQLWith
// Set Setting common table expression.
Set(alias string, maker Maker, columns ...string) SQLWith
// Del Removing common table expression.
Del(alias string) SQLWith
}
SQLWith CTE: Common Table Expression.
func NewSQLWith ¶
func NewSQLWith() SQLWith
type Stmt ¶
type Stmt struct {
// contains filtered or unexported fields
}
Stmt Prepare a handle.
func (*Stmt) Exec ¶
Exec -> Execute prepared, that can be called repeatedly, return number of rows affected.
func (*Stmt) ExecContext ¶
ExecContext -> Execute prepared, that can be called repeatedly, return number of rows affected.
func (*Stmt) ExecuteContext ¶
ExecuteContext -> Execute prepared, that can be called repeatedly.
func (*Stmt) QueryContext ¶
func (s *Stmt) QueryContext(ctx context.Context, query func(rows *sql.Rows) error, args ...any) error
QueryContext -> Query prepared, that can be called repeatedly.
func (*Stmt) QueryRowContext ¶
func (s *Stmt) QueryRowContext(ctx context.Context, query func(rows *sql.Row) error, args ...any) error
QueryRowContext -> Query prepared, that can be called repeatedly.
type StringMutex ¶
type StringMutex struct {
// contains filtered or unexported fields
}
StringMutex maps string keys to a fixed set of sync.Mutex locks using hashing.
func NewStringMutex ¶
func NewStringMutex(length int) *StringMutex
NewStringMutex creates a new StringMutex with the specified number of mutexes. If length is invalid (< 1 or > math.MaxUint16), it defaults to 256.
type TableColumn ¶
type TableColumn struct {
// contains filtered or unexported fields
}
func NewTableColumn ¶
func NewTableColumn(way *Way, aliases ...string) *TableColumn
func (*TableColumn) AVG ¶
func (s *TableColumn) AVG(column string, aliases ...string) string
AVG COALESCE(AVG(column) ,0)[ AS column_alias_name]
func (*TableColumn) Adjust ¶
func (s *TableColumn) Adjust(adjust func(column string) string, columns ...string) []string
Adjust Batch adjust columns.
func (*TableColumn) Avg ¶
func (s *TableColumn) Avg(column string, aliases ...string) string
Avg AVG(column[, alias])
func (*TableColumn) Column ¶
func (s *TableColumn) Column(column string, aliases ...string) string
Column Add table name prefix to single column name, allowing column alias to be set.
func (*TableColumn) ColumnAll ¶
func (s *TableColumn) ColumnAll(columns ...string) []string
ColumnAll Add table name prefix to column names in batches.
func (*TableColumn) Count ¶
func (s *TableColumn) Count(counts ...string) string
Count Example Count(): COUNT(*) AS `counts` Count("total"): COUNT(*) AS `total` Count("1", "total"): COUNT(1) AS `total` Count("id", "counts"): COUNT(`id`) AS `counts`
func (*TableColumn) MAX ¶
func (s *TableColumn) MAX(column string, aliases ...string) string
MAX COALESCE(MAX(column) ,0)[ AS column_alias_name]
func (*TableColumn) MIN ¶
func (s *TableColumn) MIN(column string, aliases ...string) string
MIN COALESCE(MIN(column) ,0)[ AS column_alias_name]
func (*TableColumn) Max ¶
func (s *TableColumn) Max(column string, aliases ...string) string
Max MAX(column[, alias])
func (*TableColumn) Min ¶
func (s *TableColumn) Min(column string, aliases ...string) string
Min MIN(column[, alias])
func (*TableColumn) SUM ¶
func (s *TableColumn) SUM(column string, aliases ...string) string
SUM COALESCE(SUM(column) ,0)[ AS column_alias_name]
func (*TableColumn) SetAlias ¶
func (s *TableColumn) SetAlias(alias string) *TableColumn
SetAlias Set the alias name value.
type Way ¶
type Way struct {
// contains filtered or unexported fields
}
Way Quick insert, delete, update, select helper.
func (*Way) ExecContext ¶
ExecContext -> Execute the execute sql statement.
func (*Way) ExecuteContext ¶
ExecuteContext -> Execute the execute sql statement.
func (*Way) GetDatabase ¶
func (*Way) GetterContext ¶
func (s *Way) GetterContext(ctx context.Context, query func(rows *sql.Rows) error, prepare string, args ...any) (err error)
GetterContext -> Execute the query SQL statement with args, no prepared is used.
func (*Way) IsInTransaction ¶
IsInTransaction -> Is the transaction currently in progress?
func (*Way) MakerExecContext ¶
MakerExecContext Execute a DML statement through the Maker interface.
func (*Way) MakerExecute ¶
MakerExecute Execute a DML statement through the Maker interface.
func (*Way) MakerExecuteContext ¶
MakerExecuteContext Execute a DML statement through the Maker interface.
func (*Way) MakerQuery ¶
MakerQuery Execute a DQL statement through the Maker interface.
func (*Way) MakerQueryContext ¶
func (s *Way) MakerQueryContext(ctx context.Context, maker Maker, query func(rows *sql.Rows) error) error
MakerQueryContext Execute a DQL statement through the Maker interface.
func (*Way) MakerQueryRow ¶
MakerQueryRow Execute a DQL statement through the Maker interface.
func (*Way) MakerQueryRowContext ¶
func (s *Way) MakerQueryRowContext(ctx context.Context, maker Maker, query func(row *sql.Row) error) error
MakerQueryRowContext Execute a DQL statement through the Maker interface.
func (*Way) MakerTakeAll ¶
MakerTakeAll Execute a DQL statement through the Maker interface.
func (*Way) MakerTakeAllContext ¶
MakerTakeAllContext Execute a DQL statement through the Maker interface.
func (*Way) MakersExec ¶
MakersExec Execute multiple DML statements.
func (*Way) MakersExecContext ¶
func (s *Way) MakersExecContext(ctx context.Context, makers []Maker) (affectedRows int64, err error)
MakersExecContext Execute multiple DML statements.
func (*Way) MakersTakeAll ¶
MakersTakeAll Execute multiple DQL statements.
func (*Way) MakersTakeAllContext ¶
MakersTakeAllContext Execute multiple DQL statements.
func (*Way) NewAddOne ¶
func (s *Way) NewAddOne(prepare string, args ...any) AddOneReturnSequenceValue
NewAddOne Insert one and get the last insert sequence value.
func (*Way) NewAddOneMaker ¶
func (s *Way) NewAddOneMaker(insert Maker) AddOneReturnSequenceValue
NewAddOneMaker Insert one and get the last insert sequence value.
func (*Way) NewInsertOnConflict ¶
func (s *Way) NewInsertOnConflict(prepare string, args ...any) SQLInsertOnConflict
NewInsertOnConflict Update if exists, insert if not.
func (*Way) NewInsertOnConflictMaker ¶
func (s *Way) NewInsertOnConflictMaker(insert Maker) SQLInsertOnConflict
NewInsertOnConflictMaker Update if exists, insert if not.
func (*Way) NewOrderByLimit ¶
func (s *Way) NewOrderByLimit(maker Maker) SQLOrderByLimit
NewOrderByLimit Append ORDER BY and LIMIT clauses to the SQL statement.
func (*Way) PrepareContext ¶
PrepareContext -> Prepare SQL statement, remember to call *Stmt.Close().
func (*Way) QueryContext ¶
func (s *Way) QueryContext(ctx context.Context, query func(rows *sql.Rows) error, prepare string, args ...any) error
QueryContext -> Execute the query sql statement.
func (*Way) QueryRow ¶
QueryRow -> Execute SQL statement and return row data, usually INSERT, UPDATE, DELETE.
func (*Way) QueryRowContext ¶
func (s *Way) QueryRowContext(ctx context.Context, query func(row *sql.Row) error, prepare string, args ...any) error
QueryRowContext -> Execute SQL statement and return row data, usually INSERT, UPDATE, DELETE.
func (*Way) SetterContext ¶
SetterContext -> Execute the execute SQL statement with args, no prepared is used.
func (*Way) StmtBatchExec ¶
StmtBatchExec Executing a DML statement multiple times using the same prepared statement.
func (*Way) StmtBatchExecContext ¶
func (s *Way) StmtBatchExecContext(ctx context.Context, prepare string, lists [][]any) (affectedRows int64, err error)
StmtBatchExecContext Executing a DML statement multiple times using the same prepared statement.
func (*Way) StmtBatchTakeAll ¶
StmtBatchTakeAll Executing a DQL statement multiple times using the same prepared statement.
func (*Way) StmtBatchTakeAllContext ¶
func (s *Way) StmtBatchTakeAllContext(ctx context.Context, prepare string, lists [][]any, results []any) (err error)
StmtBatchTakeAllContext Executing a DQL statement multiple times using the same prepared statement.
func (*Way) TakeAllContext ¶
TakeAllContext -> Query prepared and get all query results, through the mapping of column names and struct tags.
func (*Way) Transaction ¶
func (s *Way) Transaction(ctx context.Context, fc func(tx *Way) error, opts ...*sql.TxOptions) error
Transaction -> Atomically executes a set of SQL statements. If a transaction has been opened, the opened transaction instance will be used.
func (*Way) TransactionMessage ¶
TransactionMessage -> Set the prompt for the current transaction, can only be set once.
func (*Way) TransactionNew ¶
func (s *Way) TransactionNew(ctx context.Context, fc func(tx *Way) error, opts ...*sql.TxOptions) error
TransactionNew -> Starts a new transaction and executes a set of SQL statements atomically. Does not care whether the current transaction instance is open.
func (*Way) TransactionRetry ¶
func (s *Way) TransactionRetry(ctx context.Context, retries int, fc func(tx *Way) error, opts ...*sql.TxOptions) (err error)
TransactionRetry Starts a new transaction and executes a set of SQL statements atomically. Does not care whether the current transaction instance is open.
func (*Way) W ¶
W -> The specified transaction object is used first, otherwise the current object is used.
func (*Way) WindowFunc ¶
func (s *Way) WindowFunc(alias ...string) *WindowFunc
WindowFunc New a window function object.
type WindowFunc ¶
type WindowFunc struct {
// contains filtered or unexported fields
}
WindowFunc SQL window function.
func NewWindowFunc ¶
func NewWindowFunc(way *Way, aliases ...string) *WindowFunc
func (*WindowFunc) Alias ¶
func (s *WindowFunc) Alias(alias string) *WindowFunc
Alias Set the alias of the column that uses the window function.
func (*WindowFunc) Asc ¶
func (s *WindowFunc) Asc(column string) *WindowFunc
Asc Define the sorting within the partition so that the window function is calculated in order.
func (*WindowFunc) Avg ¶
func (s *WindowFunc) Avg(column string) *WindowFunc
Avg AVG() Returns the average of all rows in the window.
func (*WindowFunc) Count ¶
func (s *WindowFunc) Count(columns ...string) *WindowFunc
Count COUNT() Returns the number of rows in the window.
func (*WindowFunc) DenseRank ¶
func (s *WindowFunc) DenseRank() *WindowFunc
DenseRank DENSE_RANK() Similar to RANK(), but does not skip rankings.
func (*WindowFunc) Desc ¶
func (s *WindowFunc) Desc(column string) *WindowFunc
Desc Define the sorting within the partition so that the window function is calculated in descending order.
func (*WindowFunc) FirstValue ¶
func (s *WindowFunc) FirstValue(column string) *WindowFunc
FirstValue FIRST_VALUE() Returns the value of the first row in the window.
func (*WindowFunc) Lag ¶
func (s *WindowFunc) Lag(column string, offset int64, defaultValue any) *WindowFunc
Lag LAG() Returns the value of the row before the current row.
func (*WindowFunc) LastValue ¶
func (s *WindowFunc) LastValue(column string) *WindowFunc
LastValue LAST_VALUE() Returns the value of the last row in the window.
func (*WindowFunc) Lead ¶
func (s *WindowFunc) Lead(column string, offset int64, defaultValue any) *WindowFunc
Lead LEAD() Returns the value of a row after the current row.
func (*WindowFunc) Max ¶
func (s *WindowFunc) Max(column string) *WindowFunc
Max MAX() Returns the maximum value within the window.
func (*WindowFunc) Min ¶
func (s *WindowFunc) Min(column string) *WindowFunc
Min MIN() Returns the minimum value within the window.
func (*WindowFunc) NTile ¶
func (s *WindowFunc) NTile(buckets int64) *WindowFunc
NTile N-TILE Divide the rows in the window into n buckets and assign a bucket number to each row.
func (*WindowFunc) NthValue ¶
func (s *WindowFunc) NthValue(column string, lineNumber int64) *WindowFunc
NthValue NTH_VALUE() The Nth value can be returned according to the specified order. This is very useful when you need to get data at a specific position.
func (*WindowFunc) Partition ¶
func (s *WindowFunc) Partition(column ...string) *WindowFunc
Partition The OVER clause defines window partitions so that the window function is calculated independently in each partition.
func (*WindowFunc) Range ¶
func (s *WindowFunc) Range(fc func(frame SQLWindowFuncFrame)) *WindowFunc
Range Define the window based on the physical row number, accurately control the number of rows (such as the first 2 rows and the last 3 rows).
func (*WindowFunc) Rank ¶
func (s *WindowFunc) Rank() *WindowFunc
Rank RANK() Assign a rank to each row, if there are duplicate values, the rank is skipped.
func (*WindowFunc) RowNumber ¶
func (s *WindowFunc) RowNumber() *WindowFunc
RowNumber ROW_NUMBER() Assign a unique serial number to each row, in the order specified, starting with 1.
func (*WindowFunc) Rows ¶
func (s *WindowFunc) Rows(fc func(frame SQLWindowFuncFrame)) *WindowFunc
Rows Defines a window based on a range of values, including all rows with the same ORDER BY column value; suitable for handling scenarios with equal values (such as time ranges).
func (*WindowFunc) Sum ¶
func (s *WindowFunc) Sum(column string) *WindowFunc
Sum SUM() Returns the sum of all rows in the window.
func (*WindowFunc) ToSQL ¶
func (s *WindowFunc) ToSQL() *SQL
func (*WindowFunc) Window ¶
func (s *WindowFunc) Window(window string, args ...any) *WindowFunc
Window Using custom function. for example: CUME_DIST(), PERCENT_RANK(), PERCENTILE_CONT(), PERCENTILE_DISC()...