Documentation
¶
Index ¶
- Constants
- func AnyAny[T any](slice []T) []any
- func DiscardDuplicate[T comparable](discard func(tmp T) bool, dynamic ...T) (result []T)
- func DropTable(ctx context.Context, db *sql.DB, tables ...string) error
- func ExecuteScript(ctx context.Context, db *sql.DB, execute string, args ...any) error
- func InGroupValues[T any](values []T, fx func(tmp T) []any) [][]any
- func InValues[T any](values []T, fx func(tmp T) any) []any
- func JoinString(elems ...string) string
- 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 MapDiscard[K comparable, V any](values map[K]V, discard func(k K, v V) bool) map[K]V
- func MapToMap[K comparable, V any, X comparable, Y any](values map[K]V, fx func(k K, v V) (X, Y)) map[X]Y
- func MapToSlice[K comparable, V any, W any](values map[K]V, fx func(k K, v V) W) []W
- func MergeMap[K comparable, V any](values ...map[K]V) map[K]V
- func MergeSlice[V any](values ...[]V) []V
- func NamingCamel(value string) string
- func NamingPascal(value string) string
- func NamingUnderline(value string) string
- func ObjectModify(object any, tag string, except ...string) (columns []string, values []any)
- func ObjectObtain(object any, tag string, except ...string) (columns []string, values []any)
- func ParcelCancelPrepare(prepare string) string
- func ParcelPrepare(prepare string) string
- func Prefix(prefix string, name string) string
- func QuickScan(rows *sql.Rows, ...) ([]map[string]any, error)
- func RowsScan(rows *sql.Rows, result any, tag string) error
- func SQLBlockComment(comment string) string
- func SQLToString(script *SQL) string
- func SliceDiscard[V any](values []V, discard func(k int, v V) bool) []V
- func SliceToMap[V any, K comparable, W any](values []V, fx func(v V) (K, W)) map[K]W
- func SliceToSlice[V any, W any](values []V, fx func(k int, v V) W) []W
- func StructUpdate(origin any, latest any, tag string, except ...string) (columns []string, values []any)
- func TruncateTable(ctx context.Context, db *sql.DB, tables ...string) error
- func VarcharValue(value string) string
- type AdjustColumnAnyValue
- type CategoryInsert
- type Complex
- type Config
- type Err
- type ExtractFilter
- type Filter
- type Limiter
- type MakeSQL
- type Maker
- type Manual
- type Map
- type MapScanner
- type Multi
- type MyTrack
- type MyTrackType
- type Option
- type Quantifier
- type Reader
- type Replacer
- type RowsScanMakeSliceLength
- type Run
- type SQL
- func AnyToSQL(i any) *SQL
- func Avg(values ...any) *SQL
- func CloneSQL(src *SQL) *SQL
- func Coalesce(values ...any) *SQL
- func Count(values ...any) *SQL
- func ExceptAllSQL(scripts ...*SQL) *SQL
- func ExceptSQL(scripts ...*SQL) *SQL
- func FuncSQL(funcName string, funcArgs ...any) *SQL
- func IntersectAllSQL(scripts ...*SQL) *SQL
- func IntersectSQL(scripts ...*SQL) *SQL
- func JoinMaker(elems []Maker, sep string) *SQL
- func JoinSQL(elems []any, sep string) *SQL
- func JoinSQLComma(values ...any) *SQL
- func JoinSQLCommaSpace(values ...any) *SQL
- func JoinSQLEmpty(values ...any) *SQL
- func JoinSQLSemicolon(values ...any) *SQL
- func JoinSQLSpace(values ...any) *SQL
- func Max(values ...any) *SQL
- func Min(values ...any) *SQL
- func NewEmptySQL() *SQL
- func NewSQL(prepare string, args ...any) *SQL
- func ParcelCancelSQL(script *SQL) *SQL
- func ParcelSQL(script *SQL) *SQL
- func SliceDataToTableSQL(columns []string, rows func() [][]any, concat func(values ...*SQL) *SQL) *SQL
- func Sum(values ...any) *SQL
- func UnionAllSQL(scripts ...*SQL) *SQL
- func UnionSQL(scripts ...*SQL) *SQL
- type SQLAlias
- type SQLCase
- type SQLGroupBy
- type SQLInsert
- type SQLJoin
- type SQLJoinOn
- type SQLLabel
- type SQLLimit
- type SQLOnConflict
- type SQLOnConflictUpdateSet
- type SQLOrderBy
- type SQLReturning
- type SQLSelect
- type SQLUpdateSet
- type SQLValues
- type SQLWindow
- type SQLWindowFuncFrame
- type SQLWindowFuncOver
- type SQLWith
- type Stmt
- func (s *Stmt) Close() (err error)
- func (s *Stmt) Exec(ctx context.Context, args ...any) (sql.Result, error)
- func (s *Stmt) Execute(ctx context.Context, args ...any) (int64, error)
- func (s *Stmt) Query(ctx context.Context, query func(rows *sql.Rows) error, args ...any) (err error)
- func (s *Stmt) QueryRow(ctx context.Context, query func(row *sql.Row) error, args ...any) error
- func (s *Stmt) Scan(ctx context.Context, result any, args ...any) error
- type Table
- func (s *Table) Alias(alias string) *Table
- func (s *Table) Asc(columns ...string) *Table
- func (s *Table) Count(ctx context.Context, counts ...string) (int64, error)
- func (s *Table) CountScan(ctx context.Context, result any, counts ...string) (count int64, err error)
- func (s *Table) Create(ctx context.Context, create any) (int64, error)
- func (s *Table) Delete(ctx context.Context) (int64, error)
- func (s *Table) DeleteCreate(ctx context.Context, create any, where func(f Filter)) (deleteAffectedRows int64, insertResult int64, err error)
- func (s *Table) Desc(columns ...string) *Table
- func (s *Table) Distinct() *Table
- func (s *Table) F(makers ...Maker) Filter
- func (s *Table) Group(groups ...any) *Table
- func (s *Table) GroupFunc(fx func(g SQLGroupBy)) *Table
- func (s *Table) Having(values ...Maker) *Table
- func (s *Table) HavingFunc(fx func(h Filter)) *Table
- func (s *Table) InnerJoin(fx func(join SQLJoin) (SQLAlias, SQLJoinOn)) *Table
- func (s *Table) Insert(ctx context.Context) (int64, error)
- func (s *Table) InsertFunc(fx func(i SQLInsert)) *Table
- func (s *Table) JoinFunc(fx func(join SQLJoin)) *Table
- func (s *Table) LabelFunc(fx func(l SQLLabel)) *Table
- func (s *Table) Labels(labels ...string) *Table
- func (s *Table) LeftJoin(fx func(join SQLJoin) (SQLAlias, SQLJoinOn)) *Table
- func (s *Table) Limit(limit int64) *Table
- func (s *Table) LimitFunc(fx func(o SQLLimit)) *Table
- func (s *Table) Limiter(limiter Limiter) *Table
- func (s *Table) MapScan(ctx context.Context, adjusts ...AdjustColumnAnyValue) ([]map[string]any, error)
- func (s *Table) Modify(ctx context.Context, modify any) (int64, error)
- func (s *Table) Offset(offset int64) *Table
- func (s *Table) OrderFunc(fx func(o SQLOrderBy)) *Table
- func (s *Table) OrderString(order *string) *Table
- func (s *Table) Page(page int64, pageSize ...int64) *Table
- func (s *Table) Query(ctx context.Context, query func(rows *sql.Rows) error) error
- func (s *Table) QueryExists(ctx context.Context, exists ...func(script *SQL)) (bool, error)
- func (s *Table) RightJoin(fx func(join SQLJoin) (SQLAlias, SQLJoinOn)) *Table
- func (s *Table) Scan(ctx context.Context, result any) error
- func (s *Table) Select(columns ...any) *Table
- func (s *Table) SelectFunc(fx func(q SQLSelect)) *Table
- func (s *Table) Table(table any) *Table
- func (s *Table) TableFunc(fx func(t SQLAlias)) *Table
- func (s *Table) ToCount(counts ...string) *SQL
- func (s *Table) ToDelete() *SQL
- func (s *Table) ToEmpty() *Table
- func (s *Table) ToExists(exists ...func(script *SQL)) *SQL
- func (s *Table) ToInsert() *SQL
- func (s *Table) ToSelect() *SQL
- func (s *Table) ToUpdate() *SQL
- func (s *Table) Update(ctx context.Context) (int64, error)
- func (s *Table) UpdateFunc(fx func(f Filter, u SQLUpdateSet)) *Table
- func (s *Table) Upsert(ctx context.Context, upsert any, where func(f Filter)) (updateAffectedRows int64, insertResult int64, err error)
- func (s *Table) UpsertFunc(upsert any, where func(f Filter)) *Table
- func (s *Table) V() *Way
- func (s *Table) W(way *Way)
- func (s *Table) Where(values ...Maker) *Table
- func (s *Table) WhereFunc(fx func(f Filter)) *Table
- func (s *Table) Window(alias string, maker func(o SQLWindowFuncOver)) *Table
- func (s *Table) WindowFunc(fx func(w SQLWindow)) *Table
- func (s *Table) With(alias string, maker Maker, columns ...string) *Table
- func (s *Table) WithFunc(fx func(w SQLWith)) *Table
- type TableColumn
- type TableNamer
- type TimeFilter
- type ToEmpty
- type Track
- type V
- type W
- type Way
- func (s *Way) Alias(script any, aliases ...string) SQLAlias
- 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) Case() SQLCase
- func (s *Way) Commit() error
- func (s *Way) Config() *Config
- func (s *Way) Database() *sql.DB
- func (s *Way) Debug(maker Maker) *Way
- func (s *Way) Exec(ctx context.Context, maker Maker) (result sql.Result, err error)
- func (s *Way) Execute(ctx context.Context, maker Maker) (affectedRows int64, err error)
- func (s *Way) F(values ...Maker) Filter
- func (s *Way) Func(funcName string, funcArgs ...any) *SQL
- func (s *Way) IsInTransaction() bool
- func (s *Way) IsRead() bool
- func (s *Way) MapScan(ctx context.Context, maker Maker, adjusts ...AdjustColumnAnyValue) (result []map[string]any, err error)
- func (s *Way) Multi() Multi
- func (s *Way) MultiExecute(ctx context.Context, makers []Maker) (affectedRows int64, err error)
- func (s *Way) MultiStmtExecute(ctx context.Context, prepare string, argsQueue <-chan []any) (affectedRows int64, err error)
- func (s *Way) MultiStmtQuery(ctx context.Context, prepare string, argsQueue <-chan []any, ...) (err error)
- func (s *Way) NewExtractFilter(filter Filter) ExtractFilter
- func (s *Way) NewTimeFilter(filter Filter) TimeFilter
- func (s *Way) Now() time.Time
- func (s *Way) Prepare(ctx context.Context, query string) (stmt *Stmt, err error)
- func (s *Way) Query(ctx context.Context, maker Maker, query func(rows *sql.Rows) error) (err error)
- func (s *Way) QueryExists(ctx context.Context, maker Maker) (bool, error)
- func (s *Way) QueryRow(ctx context.Context, maker Maker, query func(row *sql.Row) error) (err error)
- func (s *Way) Read() *Way
- func (s *Way) Reader() Reader
- func (s *Way) Replace(key string) string
- func (s *Way) ReplaceAll(keys []string) []string
- func (s *Way) Rollback() error
- func (s *Way) RowScan(dest ...any) func(row *sql.Row) error
- func (s *Way) RowsScan(result any) func(rows *sql.Rows) error
- func (s *Way) Scan(ctx context.Context, maker Maker, result any) error
- func (s *Way) T(tableName ...string) TableColumn
- func (s *Way) Table(table any) *Table
- func (s *Way) Track() Track
- func (s *Way) Transaction(ctx context.Context, fx func(tx *Way) error, opts ...*sql.TxOptions) error
- func (s *Way) TransactionMessage(message string) *Way
- func (s *Way) TransactionNew(ctx context.Context, fx func(tx *Way) error, opts ...*sql.TxOptions) error
- func (s *Way) TransactionRetry(ctx context.Context, retries int, fx func(tx *Way) error, ...) (err error)
- func (s *Way) W(way *Way) *Way
- func (s *Way) WindowFunc(alias string) *WindowFunc
- type WindowFunc
- func (s *WindowFunc) Alias(alias string) *WindowFunc
- func (s *WindowFunc) Avg(column string) *WindowFunc
- func (s *WindowFunc) Count(columns ...string) *WindowFunc
- func (s *WindowFunc) CumeDist() *WindowFunc
- func (s *WindowFunc) DenseRank() *WindowFunc
- func (s *WindowFunc) FirstValue(column string) *WindowFunc
- func (s *WindowFunc) Lag(column string, args ...any) *WindowFunc
- func (s *WindowFunc) LastValue(column string) *WindowFunc
- func (s *WindowFunc) Lead(column string, args ...any) *WindowFunc
- func (s *WindowFunc) Max(column string) *WindowFunc
- func (s *WindowFunc) Min(column string) *WindowFunc
- func (s *WindowFunc) NTile(buckets int64, args ...any) *WindowFunc
- func (s *WindowFunc) NthValue(column string, args ...any) *WindowFunc
- func (s *WindowFunc) Over(prepare string, args ...any) *WindowFunc
- func (s *WindowFunc) OverFunc(fx func(o SQLWindowFuncOver)) *WindowFunc
- func (s *WindowFunc) PercentRank() *WindowFunc
- func (s *WindowFunc) Rank() *WindowFunc
- func (s *WindowFunc) RowNumber() *WindowFunc
- func (s *WindowFunc) Sum(column string) *WindowFunc
- func (s *WindowFunc) ToSQL() *SQL
- func (s *WindowFunc) WindowFunc(funcName string, funcArgs ...any) *WindowFunc
Constants ¶
const ( // ErrEmptySqlStatement Error empty sql statement. ErrEmptySqlStatement = Err("hey: empty sql statement") // ErrNoRowsAffected Error no rows affected. ErrNoRowsAffected = Err("hey: no rows affected") // ErrNoWhereCondition Error no where condition. ErrNoWhereCondition = Err("hey: no where condition") // ErrTransactionIsNil Error transaction is nil. ErrTransactionIsNil = Err("hey: transaction is nil") // ErrDatabaseIsNil Error database is nil. ErrDatabaseIsNil = Err("hey: database is nil") // ErrMethodNotImplemented Error method not implemented. ErrMethodNotImplemented = Err("hey: method not implemented") // ErrInvalidMaker Error invalid maker. ErrInvalidMaker = Err("hey: invalid maker") // ErrUnexpectedParameterValue Error unexpected parameter value. ErrUnexpectedParameterValue = Err("hey: unexpected parameter value") )
const ( DefaultTag = "db" TableMethodName = "Table" )
Variables ¶
This section is empty.
Functions ¶
func DiscardDuplicate ¶
func DiscardDuplicate[T comparable](discard func(tmp T) bool, dynamic ...T) (result []T)
DiscardDuplicate Slice member deduplication.
func DropTable ¶
DropTable DROP TABLE. Data is priceless! You should back up your data before calling this function unless you are very sure what you are doing.
func ExecuteScript ¶
ExecuteScript Execute SQL script; Data is invaluable, please use this method with caution.
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 JoinString ¶
JoinString Concatenate multiple strings in sequence.
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. Scan a piece of data, don't forget to use LIMIT 1 in your SQL statement.
func MapDiscard ¶
func MapDiscard[K comparable, V any](values map[K]V, discard func(k K, v V) bool) map[K]V
MapDiscard Remove some elements from the map; the deletion criteria are determined by `discard`.
func MapToMap ¶
func MapToMap[K comparable, V any, X comparable, Y any](values map[K]V, fx func(k K, v V) (X, Y)) map[X]Y
MapToMap Create a map based on another map.
func MapToSlice ¶
func MapToSlice[K comparable, V any, W any](values map[K]V, fx func(k K, v V) W) []W
MapToSlice Create a slice using a custom function and map.
func MergeMap ¶
func MergeMap[K comparable, V any](values ...map[K]V) map[K]V
MergeMap Combine multiple maps of the same type into one map.
func MergeSlice ¶
func MergeSlice[V any](values ...[]V) []V
MergeSlice Combine multiple slices of the same type into one slice.
func NamingUnderline ¶
NamingUnderline Naming underline case.
func ObjectModify ¶
ObjectModify Object should be one of map[string]any, anyStruct, *anyStruct get the columns and values that need to be modified. Friendly reminder: When using a struct type as the data update carrier, only data with non-nil values will be updated.
func ObjectObtain ¶
ObjectObtain Object should be one of map[string]any, anyStruct, *anyStruct for get all columns and values.
func ParcelCancelPrepare ¶
ParcelCancelPrepare Cancel parcel the SQL statement. ( `subquery` ) => `subquery` OR ( ( `subquery` ) ) => ( `subquery` )
func ParcelPrepare ¶
ParcelPrepare Parcel the SQL statement. `subquery` => ( `subquery` )
func QuickScan ¶
func QuickScan( rows *sql.Rows, adjustColumnValue func(columnTypes []*sql.ColumnType, results []map[string]any) error, ) ([]map[string]any, error)
QuickScan Quickly scan query results into []map[string]any.
func RowsScan ¶
RowsScan Scan the query result set into the receiving object. Support type *AnyStruct, **AnyStruct, *[]AnyStruct, *[]*AnyStruct, **[]AnyStruct, **[]*AnyStruct, *[]int, *[]float64, *[]string ...
func SQLBlockComment ¶
SQLBlockComment SQL statement block comment.
func SQLToString ¶
SQLToString Use parameter values to replace placeholders in SQL statements and build a visual SQL script. Warning: Binary byte slice will be converted to hexadecimal strings.
func SliceDiscard ¶
SliceDiscard Delete some elements from a slice; the deletion criteria are determined by `discard`.
func SliceToMap ¶
func SliceToMap[V any, K comparable, W any](values []V, fx func(v V) (K, W)) map[K]W
SliceToMap Create a map using a custom function and slice.
func SliceToSlice ¶
SliceToSlice Create a slice from another slice.
func StructUpdate ¶
func StructUpdate(origin any, latest any, tag string, except ...string) (columns []string, values []any)
StructUpdate Compare origin and latest for update.
func TruncateTable ¶
TruncateTable TRUNCATE TABLE. Data is priceless! You should back up your data before calling this function unless you are very sure what you are doing.
func VarcharValue ¶
VarcharValue Convert a go string to a SQL string.
Types ¶
type AdjustColumnAnyValue ¶
type AdjustColumnAnyValue func(columnTypes []*sql.ColumnType, results []map[string]any) error
type CategoryInsert ¶
type CategoryInsert int8
const ( CategoryInsertUnknown CategoryInsert = iota // Unexpected parameter value. CategoryInsertOne // Insert only one piece of data. CategoryInsertAll // Insert multiple pieces of data (could be just one piece of data). )
func ObjectInsert ¶
func ObjectInsert(object any, tag string, except []string, allow []string) (columns []string, values [][]any, category CategoryInsert)
ObjectInsert Object should be one of map[string]any, []map[string]any, struct{}, *struct{}, []struct, []*struct{}, *[]struct{}, *[]*struct{}. Friendly reminder: When using a struct type as the data insertion carrier, its data will be used as long as the corresponding tag exists, even if its value is nil.
type Complex ¶
type Complex interface {
// Upsert Update or insert data.
Upsert(ctx context.Context) (updateAffectedRows int64, insertResult int64, err error)
// DeleteCreate Delete data first, then insert data.
DeleteCreate(ctx context.Context) (deleteAffectedRows int64, insertResult int64, err error)
}
Complex Execute a set of SQL statements within a transaction.
type Config ¶
type Config struct {
// Manual For handling different types of databases.
Manual Manual
// TxOptions Start transaction options.
TxOptions *sql.TxOptions
// MapScanner Custom MapScan, cannot be set to nil.
MapScanner MapScanner
// RowsScan For scanning data into structure, cannot be set to nil.
RowsScan func(rows *sql.Rows, result any, tag string) error
// NewSQLLabel Create SQLLabel, cannot be set to nil.
NewSQLLabel func(way *Way) SQLLabel
// NewSQLWith Create SQLWith, cannot be set to nil.
NewSQLWith func(way *Way) SQLWith
// NewSQLSelect Create SQLSelect, cannot be set to nil.
NewSQLSelect func(way *Way) SQLSelect
// NewSQLTable Create SQLAlias, cannot be set to nil.
NewSQLTable func(way *Way, table any) SQLAlias
// NewSQLJoin Create SQLJoin, cannot be set to nil.
NewSQLJoin func(way *Way, query SQLSelect) SQLJoin
// NewSQLJoinOn Create SQLJoinOn, cannot be set to nil.
NewSQLJoinOn func(way *Way) SQLJoinOn
// NewSQLFilter Create Filter, cannot be set to nil.
NewSQLFilter func(way *Way) Filter
// NewSQLGroupBy Create SQLGroupBy, cannot be set to nil.
NewSQLGroupBy func(way *Way) SQLGroupBy
// NewSQLWindow Create SQLWindow, cannot be set to nil.
NewSQLWindow func(way *Way) SQLWindow
// NewSQLOrderBy Create SQLOrderBy, cannot be set to nil.
NewSQLOrderBy func(way *Way) SQLOrderBy
// NewSQLLimit Create SQLLimit, cannot be set to nil.
NewSQLLimit func(way *Way) SQLLimit
// NewSQLInsert Create SQLInsert, cannot be set to nil.
NewSQLInsert func(way *Way) SQLInsert
// NewSQLValues Create SQLValues, cannot be set to nil.
NewSQLValues func(way *Way) SQLValues
// NewSQLReturning Create SQLReturning, cannot be set to nil.
NewSQLReturning func(way *Way, insert Maker) SQLReturning
// NewSQLOnConflict Create SQLOnConflict, cannot be set to nil.
NewSQLOnConflict func(way *Way, insert Maker) SQLOnConflict
// NewSQLOnConflictUpdateSet Create SQLOnConflictUpdateSet, cannot be set to nil.
NewSQLOnConflictUpdateSet func(way *Way) SQLOnConflictUpdateSet
// NewSQLUpdateSet Create SQLUpdateSet, cannot be set to nil.
NewSQLUpdateSet func(way *Way) SQLUpdateSet
// NewSQLCase Create SQLCase, cannot be set to nil.
NewSQLCase func(way *Way) SQLCase
// NewSQLWindowFuncFrame Create SQLWindowFuncFrame, cannot be set to nil.
NewSQLWindowFuncFrame func(frame string) SQLWindowFuncFrame
// NewSQLWindowFuncOver Create SQLWindowFuncOver, cannot be set to nil.
NewSQLWindowFuncOver func(way *Way) SQLWindowFuncOver
// NewMulti Create Multi, cannot be set to nil.
NewMulti func(way *Way) Multi
// NewQuantifier Create Quantifier, cannot be set to nil.
NewQuantifier func(filter Filter) Quantifier
// NewExtractFilter Create ExtractFilter, cannot be set to nil.
NewExtractFilter func(filter Filter) ExtractFilter
// NewTimeFilter Create TimeFilter, cannot be set to nil.
NewTimeFilter func(filter Filter) TimeFilter
// NewTableColumn Create TableColumn, cannot be set to nil.
NewTableColumn func(way *Way, tableName ...string) TableColumn
// ToSQLSelect Construct a query statement, cannot be set to nil.
ToSQLSelect func(s MakeSQL) *SQL
// ToSQLInsert Construct an insert statement, cannot be set to nil.
ToSQLInsert func(s MakeSQL) *SQL
// ToSQLDelete Construct a delete statement, cannot be set to nil.
ToSQLDelete func(s MakeSQL) *SQL
// ToSQLUpdate Construct an update statement, cannot be set to nil.
ToSQLUpdate func(s MakeSQL) *SQL
// ToSQLSelectExists Construct an exists statement, cannot be set to nil.
ToSQLSelectExists func(s MakeSQL) *SQL
// ToSQLSelectCount Construct a count statement, cannot be set to nil.
ToSQLSelectCount func(s MakeSQL) *SQL
// ScanTag Scan data to tag mapping on structure.
ScanTag string
// LabelsSeparator Separator string between multiple labels.
LabelsSeparator string
// TableMethodName Custom method name to get table name.
TableMethodName string
// InsertForbidColumn List of columns ignored when inserting data.
InsertForbidColumn []string
// UpdateForbidColumn List of columns ignored when updating data.
UpdateForbidColumn []string
// MaxLimit Check the maximum allowed LIMIT value; a value less than or equal to 0 will be unlimited.
MaxLimit int64
// MaxOffset Check the maximum allowed OFFSET value; a value less than or equal to 0 will be unlimited.
MaxOffset int64
// DefaultPageSize The default value of limit when querying data with the page parameter for pagination.
DefaultPageSize int64
// DeleteRequireWhere Deletion of data must be filtered using conditions.
DeleteRequireWhere bool
// UpdateRequireWhere Updated data must be filtered using conditions.
UpdateRequireWhere bool
}
Config Configuration structure.
func ConfigDefault ¶
func ConfigDefault() *Config
ConfigDefault Default configuration. If there is no highly customized configuration, please use it and set the Manual property for the specific database.
func ConfigDefaultMysql ¶
func ConfigDefaultMysql() *Config
ConfigDefaultMysql Mysql default configuration.
func ConfigDefaultPostgresql ¶
func ConfigDefaultPostgresql() *Config
ConfigDefaultPostgresql Postgresql default configuration.
func ConfigDefaultSqlite ¶
func ConfigDefaultSqlite() *Config
ConfigDefaultSqlite Sqlite default configuration.
type ExtractFilter ¶
type ExtractFilter interface {
// Delimiter Custom a delimiter string is used to split the target string.
Delimiter(delimiter string) ExtractFilter
// Between Use a delimiter string to separate multiple element values, with ',' as the default.
Between(column string, value *string, handle func(values []string) []any) ExtractFilter
// IntBetween Use a delimiter string to separate multiple element values, with ',' as the default.
// column BETWEEN int-min AND int-max, column >= int-min, column <= int-max
IntBetween(column string, value *string) ExtractFilter
// Int64Between Use a delimiter string to separate multiple element values, with ',' as the default.
// column BETWEEN int64-min AND int64-max, column >= int64-min, column <= int64-max
Int64Between(column string, value *string) ExtractFilter
// Float64Between Use a delimiter string to separate multiple element values, with ',' as the default.
// column BETWEEN float64-min AND float64-max, column >= float64-min, column <= float64-max
Float64Between(column string, value *string) ExtractFilter
// StringBetween Use a delimiter string to separate multiple element values, with ',' as the default.
// column BETWEEN string-min AND string-max, column >= string-min, column <= string-max
StringBetween(column string, value *string) ExtractFilter
// In Use a delimiter string to separate multiple element values, with ',' as the default.
In(column string, value *string, handle func(values []string) []any) ExtractFilter
// IntIn Use a delimiter string to separate multiple element values, with ',' as the default.
// column IN ( int-value1, int-value2, int-value3 ... )
IntIn(column string, value *string) ExtractFilter
// Int64In Use a delimiter string to separate multiple element values, with ',' as the default.
// column IN ( int64-value1, int64-value2, int64-value3 ... )
Int64In(column string, value *string) ExtractFilter
// StringIn Use a delimiter string to separate multiple element values, with ',' as the default.
// column IN ( string-value1, string-value2, string-value3 ... )
StringIn(column string, value *string) ExtractFilter
// LikeSearch Fuzzy search for a single keyword across multiple column values, ( column1 LIKE '%value%' OR column2 LIKE '%value%' OR column3 LIKE '%value%' ... )
LikeSearch(value *string, columns ...string) ExtractFilter
}
ExtractFilter Extract the available condition values for the Filter. Use a delimiter string to separate multiple element values, with ',' as the default.
type Filter ¶
type Filter interface {
Maker
V
W
// ToEmpty Clear existing filter criteria.
ToEmpty()
// Clone Copy the current object.
Clone() Filter
// Num Number of conditions used.
Num() int
// IsEmpty Are the filter criteria empty?
IsEmpty() 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.
// Please verify the validity of the parameter values and be wary of SQL injection attacks.
And(maker Maker) Filter
// Or Use logical operator `OR` to combine custom conditions.
// Please verify the validity of the parameter values and be wary of SQL injection attacks.
Or(maker Maker) Filter
// Group Add a new condition group, which is connected by the `AND` logical operator by default.
Group(group func(g Filter)) Filter
// OrGroup Add a new condition group, which is connected by the `OR` logical operator by default.
OrGroup(group func(g Filter)) Filter
// Use Implement import a set of conditional filter objects into the current object.
Use(values ...Maker) Filter
// New Create a new conditional filter object.
New() Filter
// Equal Implement conditional filtering: column = value .
Equal(column any, value any) Filter
// LessThan Implement conditional filtering: column < value .
LessThan(column any, value any) Filter
// LessThanEqual Implement conditional filtering: column <= value .
LessThanEqual(column any, value any) Filter
// GreaterThan Implement conditional filtering: column > value.
GreaterThan(column any, value any) Filter
// GreaterThanEqual Implement conditional filtering: column >= value .
GreaterThanEqual(column any, value any) Filter
// Between Implement conditional filtering: column BETWEEN value1 AND value2 .
Between(column any, start any, end any) Filter
// In Implement conditional filtering: column IN ( value1, value2, value3... ) || column IN ( subquery ) .
// Please do not use []uint8 as the value of values.
In(column any, values ...any) Filter
// InGroup Implement conditional filtering: ( column1, column2, column3... ) IN ( ( value1, value2, value3... ), ( value21, value22, value23... )... ) || ( column1, column2, column3... ) IN ( subquery ) .
InGroup(columns any, values any) Filter
// Exists Implement conditional filtering: EXISTS (subquery) .
Exists(subquery Maker) Filter
// Like Implement conditional filtering: column LIKE value.
Like(column any, value any) Filter
// IsNull Implement conditional filtering: column IS NULL .
IsNull(column any) Filter
// NotEqual Implement conditional filtering: column <> value .
NotEqual(column any, value any) Filter
// NotBetween Implement conditional filtering: column NOT BETWEEN value1 AND value2 .
NotBetween(column any, start any, end any) Filter
// NotIn Implement conditional filtering: column NOT IN ( value1, value2, value3... ) .
NotIn(column any, values ...any) Filter
// NotInGroup Implement conditional filtering: ( column1, column2, column3... ) NOT IN ( ( value1, value2, value3... ), ( value21, value22, value23... )... ) || ( column1, column2, column3... ) NOT IN ( subquery ) .
NotInGroup(columns any, values any) Filter
// NotExists Implement conditional filtering: NOT EXISTS (subquery) .
NotExists(subquery Maker) Filter
// NotLike Implement conditional filtering: column NOT LIKE value .
NotLike(column any, value any) Filter
// IsNotNull Implement conditional filtering: column IS NOT NULL .
IsNotNull(column any) Filter
// LikeSearch Implement the filter condition: ( column1 LIKE 'value' OR column2 LIKE 'value' OR column3 LIKE 'value' ... ) .
LikeSearch(value string, columns ...string) Filter
// AllCompare Implement conditional filtering: column {=||<>||>||>=||<||<=} ALL ( subquery ) .
AllCompare(fx func(q Quantifier)) Filter
// AnyCompare Implement conditional filtering: column {=||<>||>||>=||<||<=} ANY ( subquery ) .
AnyCompare(fx func(q Quantifier)) Filter
// CompareEqual Implement conditional filtering: script1 = script2 .
CompareEqual(column1 any, column2 any) Filter
// CompareNotEqual Implement conditional filtering: script1 <> script2 .
CompareNotEqual(column1 any, column2 any) Filter
// CompareGreaterThan Implement conditional filtering: script1 > script2 .
CompareGreaterThan(column1 any, column2 any) Filter
// CompareGreaterThanEqual Implement conditional filtering: script1 >= script2 .
CompareGreaterThanEqual(column1 any, column2 any) Filter
// CompareLessThan Implement conditional filtering: script1 < script2 .
CompareLessThan(column1 any, column2 any) Filter
// CompareLessThanEqual Implement conditional filtering: script1 <= script2 .
CompareLessThanEqual(column1 any, column2 any) Filter
}
Filter Implement SQL statement conditional filtering (general conditional filtering).
type MakeSQL ¶
type MakeSQL struct {
Way *Way
// Label Used for setting SQL statement labels.
Label SQLLabel
// With -> WITH
With SQLWith
// Query -> SELECT
Query SQLSelect
// Query -> FROM
Table SQLAlias
// Join -> JOIN
Join SQLJoin
// Where -> WHERE ( xxx )
Where Filter
// GroupBy -> GROUP BY xxx [HAVING xxx]
GroupBy SQLGroupBy
// Window -> WINDOW
Window SQLWindow
// OrderBy -> ORDER BY
OrderBy SQLOrderBy
// Limit -> LIMIT m [OFFSET n]
Limit SQLLimit
// Insert -> INSERT INTO xxx
Insert SQLInsert
// UpdateSet -> UPDATE xxx SET xxx [WHERE ( xxx )]
UpdateSet SQLUpdateSet
// ToExistsSubquery -> SELECT EXISTS ( SELECT 1 FROM xxx ) AS a
ToExistsSubquery []func(script *SQL)
// ToCountColumns -> SELECT COUNT(*) FROM xxx ...
ToCountColumns []string
}
MakeSQL Data structures for building SQL scripts.
type Maker ¶
type Maker interface {
// ToSQL Construct SQL statements that may contain parameters, the return value cannot be nil.
ToSQL() *SQL
}
Maker Build SQL fragments or SQL statements, which may include corresponding parameter lists. Notice: The ToSQL method must return a non-nil value for *SQL.
type Manual ¶
type Manual struct {
// DatabaseType Database type value.
DatabaseType cst.DatabaseType
// Replacer SQL Identifier Replacer.
Replacer Replacer
// Prepare Adjust the SQL statement format to fit the current database format.
Prepare func(prepare string) string
// InsertOneReturningId Insert a record and return the id value of the inserted data.
InsertOneReturningId func(r SQLReturning)
}
Manual For handling different types of databases.
func (*Manual) InsertOneAndScanInsertId ¶
func (s *Manual) InsertOneAndScanInsertId() func(r SQLReturning)
InsertOneAndScanInsertId INSERT INTO xxx RETURNING id
func (*Manual) InsertOneGetLastInsertId ¶
func (s *Manual) InsertOneGetLastInsertId() func(r SQLReturning)
InsertOneGetLastInsertId INSERT INTO xxx; sql.Result
type Map ¶
type Map interface {
// Get Getting the value corresponding to a key from the map.
Get(key string) (value any, has bool)
// Set Storing key-value to the map.
Set(key string, value any) Map
// Has Checking if the key exists in the map.
Has(key string) bool
// Del Deleting map key.
Del(key string) Map
// Map Getting the map value.
Map() map[string]any
// Len Getting the map length.
Len() int
// IsEmpty Is the map empty?
IsEmpty() bool
// ToEmpty Setting the map to empty value.
ToEmpty() Map
}
Map Store key-value to the map.
type MapScanner ¶
type MapScanner interface {
// AdjustColumnAnyValue Customize the default method for adjusting column values.
AdjustColumnAnyValue(adjust AdjustColumnAnyValue) MapScanner
// Scan Scanning the query results into []map[string]any.
// You can define a column value adjustment method with a higher priority
// than the default through the adjusts parameter.
Scan(rows *sql.Rows, adjusts ...AdjustColumnAnyValue) ([]map[string]any, error)
}
MapScanner Scanning the query results into []map[string]any.
func NewMapScanner ¶
func NewMapScanner() MapScanner
NewMapScanner Exposes a default implementation of the MapScanner interface.
type Multi ¶
type Multi interface {
Run
ToEmpty
V
W
// Len Number of SQL statements to be executed.
Len() int
// IsEmpty Are there no pending SQL statements?
IsEmpty() bool
// Add custom logic.
Add(values ...func(ctx context.Context) error) Multi
// AddQuery Add a query statement;
AddQuery(maker Maker, query func(rows *sql.Rows) error) Multi
// AddQueryRow Execute SQL statement using QueryRow; `dest` is the container for processing or storing the returned results.
AddQueryRow(maker Maker, dest ...any) Multi
// AddQueryExists Add a query exists statement.
AddQueryExists(maker Maker, exists *bool) Multi
// AddQueryScan Add a query statement; `result` is the container for processing or storing the returned results.
AddQueryScan(maker Maker, result any) Multi
// RowsAffected Get the number of affected rows.
RowsAffected(rows *int64) func(value sql.Result) error
// LastInsertId Get the id of the last inserted data.
LastInsertId(id *int64) func(value sql.Result) error
// AddExec Add a non-query statement; `result` is the container for processing or storing the returned results.
// If the value of `result` is empty, the number of affected rows will be discarded.
AddExec(maker Maker, result ...any) Multi
}
Multi This stacks multiple SQL statements sequentially and executes them one by one at the end. You can add custom logic anywhere. For each SQL statement to be executed, you only need to focus on the following three points: 1. The SQL statement to be executed and its corresponding parameter list. 2. Receive or process SQL execution results. 3. Should custom logic be executed after the SQL statement executes successfully?
type MyTrack ¶
type MyTrack struct {
// Context Value of context.
Context context.Context
// Type Track type.
Type MyTrackType
// TimeStart Start time.
TimeStart time.Time
// TimeEnd End time.
TimeEnd time.Time
// Err Error value.
Err error
// TxId Transaction id.
TxId string
// TxMsg Transaction message.
TxMsg string
// TxState Transaction state.
TxState string
// Prepare Original SQL statement.
Prepare string
// Args The parameter list corresponding to the original SQL statement.
Args []any
// Script Visual SQL statement.
Script string
}
MyTrack Implement Track interface.
type MyTrackType ¶
type MyTrackType string
const ( TrackDebug MyTrackType = "DEBUG" TrackSQL MyTrackType = "SQL" TrackTransaction MyTrackType = "TRANSACTION" )
type Quantifier ¶
type Quantifier interface {
// GetQuantifier Get quantifier value.
GetQuantifier() string
// SetQuantifier Set quantifier value.
SetQuantifier(quantifierString string) Quantifier
// Equal Implement the filter condition: column = QUANTIFIER ( subquery ) .
Equal(column any, subquery Maker) Quantifier
// NotEqual Implement the filter condition: column <> QUANTIFIER ( subquery ) .
NotEqual(column any, subquery Maker) Quantifier
// LessThan Implement the filter condition: column < QUANTIFIER ( subquery ) .
LessThan(column any, subquery Maker) Quantifier
// LessThanEqual Implement the filter condition: column <= QUANTIFIER ( subquery ) .
LessThanEqual(column any, subquery Maker) Quantifier
// GreaterThan Implement the filter condition: column > QUANTIFIER ( subquery ) .
GreaterThan(column any, subquery Maker) Quantifier
// GreaterThanEqual Implement the filter condition: column >= QUANTIFIER ( subquery ) .
GreaterThanEqual(column any, 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 Replacer ¶
type Replacer interface {
Get(key string) string
Set(key string, value string) Replacer
Del(key string) Replacer
Map() map[string]string
GetAll(keys []string) []string
}
Replacer SQL Identifier Replacer. All identifier mapping relationships should be set before the program is initialized. They cannot be set again while the program is running to avoid concurrent reading and writing of the map.
func NewReplacer ¶
func NewReplacer() Replacer
type RowsScanMakeSliceLength ¶
type RowsScanMakeSliceLength string
const (
MakerScanAllMakeSliceLength RowsScanMakeSliceLength = "maker_scan_all_make_slice_length"
)
type SQL ¶
type SQL struct {
// Prepare SQL fragments or SQL statements, which may contain SQL placeholders.
Prepare string
// Args The corresponding parameter list of the placeholder list.
Args []any
}
SQL Prepare SQL statements and parameter lists corresponding to placeholders.
func ExceptAllSQL ¶
ExceptAllSQL *SQL1, *SQL2, *SQL3 ... => ( QUERY_A ) EXCEPT ALL ( QUERY_B ) EXCEPT ALL ( QUERY_C )...
func ExceptSQL ¶
ExceptSQL *SQL1, *SQL2, *SQL3 ... => ( QUERY_A ) EXCEPT ( QUERY_B ) EXCEPT ( QUERY_C )...
func IntersectAllSQL ¶
IntersectAllSQL *SQL1, *SQL2, *SQL3 ... => ( QUERY_A ) INTERSECT ALL ( QUERY_B ) INTERSECT ALL ( QUERY_C )...
func IntersectSQL ¶
IntersectSQL *SQL1, *SQL2, *SQL3 ... => ( QUERY_A ) INTERSECT ( QUERY_B ) INTERSECT ( QUERY_C )...
func JoinMaker ¶
JoinMaker Concatenate multiple SQL scripts and their parameter lists using a specified delimiter.
func JoinSQLComma ¶
JoinSQLComma Use "," to concatenate multiple SQL scripts and parameters.
func JoinSQLCommaSpace ¶
JoinSQLCommaSpace Use ", " to concatenate multiple SQL scripts and parameters.
func JoinSQLEmpty ¶
JoinSQLEmpty Use "" to concatenate multiple SQL scripts and parameters.
func JoinSQLSemicolon ¶
JoinSQLSemicolon Use ";" to concatenate multiple SQL scripts and parameters.
func JoinSQLSpace ¶
JoinSQLSpace Use " " to concatenate multiple SQL scripts and parameters.
func ParcelCancelSQL ¶
ParcelCancelSQL Cancel parcel the SQL statement. ( `subquery` ) => `subquery` OR ( ( `subquery` ) ) => ( `subquery` )
func SliceDataToTableSQL ¶
func SliceDataToTableSQL(columns []string, rows func() [][]any, concat func(values ...*SQL) *SQL) *SQL
SliceDataToTableSQL Concatenate one or more objects into a table SQL statement. ["id", "name"] [ {"id":1, "name":"name1"}, {"id":2, "name":"name2"}, {"id":3, "name":"name3"} ... ] ==> ( SELECT 1 AS id, NULL AS name ) UNION ALL ( SELECT 2, 'name2' ) UNION ALL ( SELECT NULL, 'name3' ) ...
func UnionAllSQL ¶
UnionAllSQL *SQL1, *SQL2, *SQL3 ... => ( QUERY_A ) UNION ALL ( QUERY_B ) UNION ALL ( QUERY_C )...
func UnionSQL ¶
UnionSQL *SQL1, *SQL2, *SQL3 ... => ( QUERY_A ) UNION ( QUERY_B ) UNION ( QUERY_C )...
type SQLAlias ¶
type SQLAlias interface {
Maker
// GetSQL Get SQL statement.
GetSQL() *SQL
// SetSQL Set SQL statement.
SetSQL(script any) SQLAlias
// GetAlias Get alias name value.
GetAlias() string
// SetAlias Set alias name value.
SetAlias(alias string) SQLAlias
// IsEmpty Verify whether the SQL statement is empty.
IsEmpty() bool
// ToEmpty Set both the SQL statement and the alias to empty values.
ToEmpty() SQLAlias
}
SQLAlias SQL script + alias name.
type SQLCase ¶
type SQLCase interface {
Maker
// Alias Set alias name.
Alias(alias string) SQLCase
// Case SQL CASE.
Case(value any) SQLCase
// WhenThen Add WHEN xxx THEN xxx.
WhenThen(when, then any) SQLCase
// Else SQL CASE xxx ELSE xxx.
Else(value any) SQLCase
}
SQLCase Implementing SQL CASE.
func NewSQLCase ¶
type SQLGroupBy ¶
type SQLGroupBy interface {
Maker
ToEmpty
// Group Set the grouping column, allowing string, []string, *SQL, []*SQL, Maker, []Maker.
Group(group ...any) SQLGroupBy
// Having Set the conditions filter HAVING statement after GROUP BY.
Having(having func(having Filter)) SQLGroupBy
}
SQLGroupBy Build GROUP BY statements.
type SQLInsert ¶
type SQLInsert interface {
Maker
ToEmpty
// Table Insert data into the target table.
Table(table Maker) SQLInsert
// TableIsValid Report whether the current table name is valid.
TableIsValid() bool
// Forbid When inserting data, it is forbidden to set certain columns, such as: auto-increment id.
Forbid(columns ...string) SQLInsert
// GetForbid Get a list of columns that have been prohibited from insertion.
GetForbid() []string
// Select Set the columns to allow inserts only, not including defaults.
Select(columns ...string) SQLInsert
// Column Set the inserted column list. An empty value will delete the set field list.
Column(columns ...string) SQLInsert
// Values Set the list of values to be inserted.
Values(values ...[]any) SQLInsert
// SetSubquery Use the query result as the values of the insert statement.
SetSubquery(subquery Maker) SQLInsert
// ColumnValue Set a single column and value.
ColumnValue(column string, value any) SQLInsert
// ReturningId Insert a single record and get the id of the inserted data.
ReturningId() SQLInsert
// Create Parses the given insert data and sets the insert data.
Create(create any) SQLInsert
// Default Set the default column for inserted data, such as the creation timestamp.
Default(column string, value any) SQLInsert
// Remove Delete a column-value.
Remove(columns ...string) SQLInsert
// GetReturning Get returning value.
GetReturning() SQLReturning
// Returning Insert a piece of data and get the auto-increment value.
Returning(fx func(r SQLReturning)) SQLInsert
// GetColumn Get the list of inserted columns that have been set.
GetColumn(excludes ...string) []string
// OnConflict When inserting data, set the execution logic when there is a conflict.
OnConflict(fx func(o SQLOnConflict)) SQLInsert
}
SQLInsert Build INSERT statements.
type SQLJoin ¶
type SQLJoin interface {
Maker
ToEmpty
// GetMain Get join query the main table.
GetMain() SQLAlias
// SetMain Set join query the main table.
SetMain(table SQLAlias) SQLJoin
// Table Create a table for join query.
Table(table any, alias string) SQLAlias
// Join Use the join type to set the table join relationship.
Join(joinType string, table SQLAlias, on SQLJoinOn) SQLJoin
// InnerJoin INNER JOIN.
InnerJoin(table SQLAlias, on SQLJoinOn) SQLJoin
// LeftJoin LEFT JOIN.
LeftJoin(table SQLAlias, on SQLJoinOn) SQLJoin
// RightJoin RIGHT JOIN.
RightJoin(table SQLAlias, on SQLJoinOn) SQLJoin
// On Set the join query conditions.
On(filter func(on SQLJoinOn)) SQLJoinOn
// Equal Set connection conditions. For example: a.id = b.pid
// Column names must be prefixed with the table name.
// Always ensure the validity of parameter values and be wary of SQL injection vulnerabilities.
// Example: Equal("a.id", "b.pid")
Equal(table1column string, table2column string) SQLJoinOn
// Using The conditions for the join query use USING.
Using(columns ...string) SQLJoinOn
// Select Set the query column list.
Select(columns ...any) SQLJoin
// TableColumn Create a table name prefix for the query column.
TableColumn(table any, column string, aliases ...string) string
// TableColumns Add table name prefix to the query column list values.
TableColumns(table any, columns ...string) []string
}
SQLJoin Build a join query.
type SQLJoinOn ¶
type SQLJoinOn interface {
Maker
// And Append custom conditions to the ON statement or use custom conditions on the ON statement to associate tables.
And(filter func(f Filter)) SQLJoinOn
// Equal Use equal value JOIN ON condition.
Equal(table1column string, table2column string) SQLJoinOn
// Equals Use equal value JOIN ON condition.
Equals(table1alias string, table1column string, table2alias string, table2column string) SQLJoinOn
// Using Use USING instead of ON.
Using(columns ...string) SQLJoinOn
}
SQLJoinOn Construct the connection query conditions.
type SQLLabel ¶
type SQLLabel interface {
Maker
ToEmpty
// Labels Add custom labels.
Labels(labels ...string) SQLLabel
}
SQLLabel Constructing SQL statement labels.
type SQLLimit ¶
type SQLLimit interface {
Maker
ToEmpty
IsEmpty() bool
// Limit SQL LIMIT.
Limit(limit int64) SQLLimit
// Offset SQL OFFSET.
Offset(offset int64) SQLLimit
// Page SQL LIMIT and OFFSET.
Page(page int64, pageSize ...int64) SQLLimit
// DirectLimit Directly use the effective limit value, unaffected by the configured maximum.
DirectLimit(limit int64) SQLLimit
// DirectOffset Directly use the effective offset value, unaffected by the configured maximum.
DirectOffset(offset int64) SQLLimit
// DirectPage Directly use the effective limit and offset value, unaffected by the configured maximum.
DirectPage(page int64, pageSize ...int64) SQLLimit
}
SQLLimit Build LIMIT n[ OFFSET m] or OFFSET m ROWS FETCH NEXT n ROWS ONLY statements.
type SQLOnConflict ¶
type SQLOnConflict interface {
Maker
ToEmpty
// GetOnConflict Get ON CONFLICT columns.
GetOnConflict() []string
// SetOnConflict The column causing the conflict, such as a unique key or primary key, which can be a single column or multiple columns.
SetOnConflict(onConflicts ...string) SQLOnConflict
// Do The SQL statement that needs to be executed when a data conflict occurs. By default, nothing is done.
Do(maker Maker) SQLOnConflict
// DoUpdateSet SQL update statements executed when data conflicts occur.
DoUpdateSet(fx func(u SQLOnConflictUpdateSet)) SQLOnConflict
// GetInsert Get insert Maker.
GetInsert() Maker
// SetInsert Set insert Maker.
SetInsert(script Maker) SQLOnConflict
}
SQLOnConflict 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 */
type SQLOnConflictUpdateSet ¶
type SQLOnConflictUpdateSet 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) SQLOnConflictUpdateSet
}
SQLOnConflictUpdateSet 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' ...
type SQLOrderBy ¶
type SQLOrderBy interface {
Maker
ToEmpty
// Num Number of sorted columns used.
Num() int
// IsEmpty Is the sort column empty?
IsEmpty() bool
// Allow the list of columns that can be used for sorting.
Allow(columns ...string) SQLOrderBy
// Replace The column name that may be used.
Replace(dst string, src string) SQLOrderBy
// Asc Build column1 ASC, column2 ASC, column3 ASC...
Asc(columns ...string) SQLOrderBy
// Desc Build column1 DESC, column2 DESC, column3 DESC...
Desc(columns ...string) SQLOrderBy
// OrderString Automatically call sorting based on the sort string format.
OrderString(order *string) SQLOrderBy
}
SQLOrderBy Build ORDER BY statements.
type SQLReturning ¶
type SQLReturning interface {
Maker
ToEmpty
// Prepare When constructing a SQL statement that insert a row of data and return the id,
// you may need to adjust the SQL statement, such as adding `RETURNING id` to the end of the insert statement.
Prepare(prepare func(tmp *SQL)) SQLReturning
// Returning Set the RETURNING statement to return one or more columns.
Returning(columns ...string) SQLReturning
// LastInsertId The driver returns the id value of the inserted data.
LastInsertId() func(ctx context.Context, stmt *Stmt, args ...any) (lastInsertId int64, err error)
// QueryRowScan Return values from QueryRow scan for inserted data.
QueryRowScan(dest ...any) func(ctx context.Context, stmt *Stmt, args ...any) (int64, error)
// RowsAffected Returns the number of rows affected directly.
RowsAffected() func(ctx context.Context, stmt *Stmt, args ...any) (rowsAffected int64, err error)
// GetExecute Get execute function value.
GetExecute() func(ctx context.Context, stmt *Stmt, args ...any) (id int64, err error)
// SetExecute When constructing a SQL statement that inserts a row of data and returns the id,
// get the id value of the inserted row (this may vary depending on the database driver)
SetExecute(execute func(ctx context.Context, stmt *Stmt, args ...any) (id int64, err error)) SQLReturning
// GetInsert Get insert Maker.
GetInsert() Maker
// SetInsert Set insert Maker.
SetInsert(script Maker) SQLReturning
}
SQLReturning Build INSERT INTO xxx RETURNING xxx
type SQLSelect ¶
type SQLSelect interface {
Maker
ToEmpty
IsEmpty() bool
// Distinct DISTINCT column1, column2, column3 ...
Distinct() SQLSelect
// Add a custom column to the query list.
Add(maker Maker) SQLSelect
// Del Delete some columns from the query list.
Del(columns ...string) SQLSelect
// Has Does the column exist in the query list?
Has(column string) bool
// Len Number of columns to query.
Len() int
// Get Query list and its corresponding column parameter list.
Get() (columns []string, args map[int][]any)
// Set Query list and its corresponding column parameter list.
Set(columns []string, args map[int][]any) SQLSelect
// Select Add one or more query lists.
Select(columns ...any) SQLSelect
}
SQLSelect Build the query column set.
type SQLUpdateSet ¶
type SQLUpdateSet interface {
Maker
ToEmpty
IsEmpty() bool
Len() int
// Forbid Set a list of columns that cannot be updated.
Forbid(columns ...string) SQLUpdateSet
// GetForbid Get a list of columns that are prohibited from updating.
GetForbid() []string
// Select Set columns that only allow updates, not including defaults.
Select(columns ...string) SQLUpdateSet
// Set Update column assignment.
Set(column string, value any) SQLUpdateSet
// Decr Update column decrement.
Decr(column string, decr any) SQLUpdateSet
// Incr Update column increment.
Incr(column string, incr any) SQLUpdateSet
// Update Parse the given update data and assign the update value.
Update(update any) SQLUpdateSet
// Compare Compare struct assignment update.
Compare(old, new any, except ...string) SQLUpdateSet
// Default Set the default columns that need to be updated, such as update timestamp.
Default(column string, value any) SQLUpdateSet
// Remove Delete a column-value.
Remove(columns ...string) SQLUpdateSet
// Assign Assigning values through other column, null, empty string, subquery ...
// Please use this method with caution, consider the security of the src value.
Assign(dst string, src string) SQLUpdateSet
// GetUpdate Get a list of existing updates.
GetUpdate() ([]string, [][]any)
// SetUpdate Delete the existing update list and set the update list.
SetUpdate(updates []string, params [][]any) SQLUpdateSet
}
SQLUpdateSet Build UPDATE-SET statements.
type SQLValues ¶
type SQLValues interface {
Maker
ToEmpty
IsEmpty() bool
// GetSubquery Get subquery value.
GetSubquery() Maker
// SetSubquery The inserted data is a subquery.
SetSubquery(subquery Maker) SQLValues
// GetValues Get values value.
GetValues() [][]any
// SetValues The inserted data of VALUES.
SetValues(values ...[]any) SQLValues
}
SQLValues Build INSERT-VALUES statements.
type SQLWindowFuncFrame ¶
type SQLWindowFuncFrame interface {
Maker
// Script Custom SQL statement.
Script(maker Maker) SQLWindowFuncFrame
// UnboundedPreceding Start of partition.
UnboundedPreceding() *SQL
// NPreceding First n rows.
NPreceding(n int) *SQL
// CurrentRow Current row.
CurrentRow() *SQL
// NFollowing After n rows.
NFollowing(n int) *SQL
// UnboundedFollowing End of partition.
UnboundedFollowing() *SQL
// Between Build BETWEEN start AND end.
Between(fx func(ff SQLWindowFuncFrame) (*SQL, *SQL)) 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 GROUPS, ROWS or RANGE statements.
func NewSQLWindowFuncFrame ¶
func NewSQLWindowFuncFrame(frame string) SQLWindowFuncFrame
type SQLWindowFuncOver ¶
type SQLWindowFuncOver interface {
Maker
ToEmpty
// Script Custom OVER statement.
Script(maker Maker) SQLWindowFuncOver
// Partition The OVER clause defines window partitions so that the window function is calculated independently in each partition.
Partition(column ...string) SQLWindowFuncOver
// Asc Define the sorting within the partition so that the window function is calculated in order.
Asc(column string) SQLWindowFuncOver
// Desc Define the sorting within the partition so that the window function is calculated in descending order.
Desc(column string) SQLWindowFuncOver
// Groups Define the window based on the sort column values.
Groups(fx func(f SQLWindowFuncFrame)) SQLWindowFuncOver
// 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).
Range(fx func(f SQLWindowFuncFrame)) SQLWindowFuncOver
// 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).
Rows(fx func(f SQLWindowFuncFrame)) SQLWindowFuncOver
}
func NewSQLWindowFuncOver ¶
func NewSQLWindowFuncOver(way *Way) SQLWindowFuncOver
type SQLWith ¶
type SQLWith interface {
Maker
ToEmpty
// 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.
type Stmt ¶
type Stmt struct {
// contains filtered or unexported fields
}
Stmt is a wrapper for *sql.Stmt.
func (*Stmt) Exec ¶
Exec executes a prepared statement with the given arguments and returns a sql.Result summarizing the effect of the statement.
func (*Stmt) Execute ¶
Execute executes a prepared statement with the given arguments and returns number of rows affected.
func (*Stmt) Query ¶
func (s *Stmt) Query(ctx context.Context, query func(rows *sql.Rows) error, args ...any) (err error)
Query executes a prepared query statement with the given arguments and processes the query result set through anonymous functions (query).
type Table ¶
type Table struct {
// contains filtered or unexported fields
}
Table Quickly build SELECT, INSERT, UPDATE, DELETE statements and support immediate execution of them.
func (*Table) CountScan ¶
func (s *Table) CountScan(ctx context.Context, result any, counts ...string) (count int64, err error)
CountScan Merge statistics and scan data.
func (*Table) DeleteCreate ¶
func (s *Table) DeleteCreate(ctx context.Context, create any, where func(f Filter)) (deleteAffectedRows int64, insertResult int64, err error)
DeleteCreate Data for the same table. First delete all data that matches the specified WHERE condition, then insert the new data; if no WHERE condition is set, no data will be deleted.
func (*Table) GroupFunc ¶
func (s *Table) GroupFunc(fx func(g SQLGroupBy)) *Table
GroupFunc Set GROUP BY through func.
func (*Table) HavingFunc ¶
HavingFunc Set HAVING through func.
func (*Table) InsertFunc ¶
InsertFunc Set inserting data through func.
func (*Table) MapScan ¶
func (s *Table) MapScan(ctx context.Context, adjusts ...AdjustColumnAnyValue) ([]map[string]any, error)
MapScan Scanning the query results into []map[string]any.
func (*Table) OrderFunc ¶
func (s *Table) OrderFunc(fx func(o SQLOrderBy)) *Table
OrderFunc Set ORDER BY through func.
func (*Table) OrderString ¶
OrderString Set ORDER BY columns through *string.
func (*Table) QueryExists ¶
QueryExists Check if the data exists, allow replacing or updating the subquery script of EXISTS.
func (*Table) Select ¶
Select Add one or more query lists. If no parameter is provided, all existing query lists will be deleted.
func (*Table) SelectFunc ¶
SelectFunc Set SELECT through func.
func (*Table) ToExists ¶
ToExists Build SELECT EXISTS statement, allow replacing or updating the subquery script of EXISTS.
func (*Table) UpdateFunc ¶
func (s *Table) UpdateFunc(fx func(f Filter, u SQLUpdateSet)) *Table
UpdateFunc Set updating data through func.
func (*Table) Upsert ¶
func (s *Table) Upsert(ctx context.Context, upsert any, where func(f Filter)) (updateAffectedRows int64, insertResult int64, err error)
Upsert Data for the same table. Filter data based on the WHERE condition. If a record exists, update all data selected by the filter condition; otherwise, perform an insert operation.
func (*Table) UpsertFunc ¶
UpsertFunc Set UPDATE and INSERT through func, ultimately execute UPDATE or INSERT.
func (*Table) Window ¶
func (s *Table) Window(alias string, maker func(o SQLWindowFuncOver)) *Table
Window Add a window expression.
func (*Table) WindowFunc ¶
WindowFunc Custom window statements.
type TableColumn ¶
type TableColumn interface {
// Table Get the current table name.
Table() string
// Column Add table name prefix to single column name, allowing column alias to be set.
Column(column string, alias ...string) string
// ColumnAll Add table name prefix to column names in batches.
ColumnAll(columnAll ...string) []string
// ColumnSQL Single column to *SQL.
ColumnSQL(column string, alias ...string) *SQL
// ColumnAllSQL Multiple columns to *SQL.
ColumnAllSQL(columnAll ...string) *SQL
}
TableColumn Add the prefix "table_name." before the column name. Allow the table name to be empty, which makes it possible to replace column names or construct SQL statements based on column names.
func NewTableColumn ¶
func NewTableColumn(way *Way, tableName ...string) TableColumn
type TableNamer ¶
type TableNamer interface {
// Table Get the table name.
Table() string
}
TableNamer Generic interface for getting table name.
type TimeFilter ¶
type TimeFilter interface {
SetTime(value time.Time) TimeFilter
// LastMinutes Last n minutes.
LastMinutes(column string, minutes int) TimeFilter
// LastHours Last n hours.
LastHours(column string, hours int) TimeFilter
// Today Time range that has passed today.
Today(column string) TimeFilter
// Yesterday From midnight yesterday to midnight today.
Yesterday(column string) TimeFilter
// LastDays Last n days.
LastDays(column string, days int) TimeFilter
// ThisMonth This month.
ThisMonth(column string) TimeFilter
// LastMonth Last month.
LastMonth(column string) TimeFilter
// LastMonths Last n months.
LastMonths(column string, months int) TimeFilter
// ThisQuarter This quarter.
ThisQuarter(column string) TimeFilter
// LastQuarter Last quarter.
LastQuarter(column string) TimeFilter
// LastQuarters Last n quarters.
LastQuarters(column string, quarters int) TimeFilter
// ThisYear This year.
ThisYear(column string) TimeFilter
// LastYear Last year.
LastYear(column string) TimeFilter
// LastYears Last n years.
LastYears(column string, years int) TimeFilter
}
TimeFilter Commonly used timestamp range filtering conditions.
type ToEmpty ¶
type ToEmpty interface {
// ToEmpty Set the property values of the object to the default values of the corresponding types.
ToEmpty()
}
ToEmpty Set the property values of the object to the default values of the corresponding types.
type V ¶
type V interface {
// V Get the currently used *Way object value.
V() *Way
}
V Get the currently used *Way object value.
type W ¶
type W interface {
// W Use the non-nil value *Way.
W(way *Way)
}
W Use the non-nil value *Way.
type Way ¶
type Way struct {
// contains filtered or unexported fields
}
func (*Way) Exec ¶
Exec executes a prepared statement with the given arguments and returns a sql.Result summarizing the effect of the statement.
func (*Way) Execute ¶
Execute executes a prepared statement with the given arguments and returns number of rows affected.
func (*Way) IsInTransaction ¶
IsInTransaction is it currently in a transaction?
func (*Way) MapScan ¶
func (s *Way) MapScan(ctx context.Context, maker Maker, adjusts ...AdjustColumnAnyValue) (result []map[string]any, err error)
MapScan executes a query statement and scan the query results into []map[string]any.
func (*Way) MultiExecute ¶
MultiExecute executes multiple statements.
func (*Way) MultiStmtExecute ¶
func (s *Way) MultiStmtExecute(ctx context.Context, prepare string, argsQueue <-chan []any) (affectedRows int64, err error)
MultiStmtExecute executes statement multiple times using the same prepared statement. The exit conditions are as follows: 1. Context was canceled or timed out. 2. Abnormal execution process (unexpected error occurred). 3. Close the argsQueue channel.
func (*Way) MultiStmtQuery ¶
func (s *Way) MultiStmtQuery(ctx context.Context, prepare string, argsQueue <-chan []any, query func(rows *sql.Rows) error) (err error)
MultiStmtQuery executes query statement multiple times using the same prepared statement. The exit conditions are as follows: 1. Context was canceled or timed out. 2. Abnormal execution process (unexpected error occurred). 3. Close the argsQueue channel.
func (*Way) NewExtractFilter ¶
func (s *Way) NewExtractFilter(filter Filter) ExtractFilter
func (*Way) NewTimeFilter ¶
func (s *Way) NewTimeFilter(filter Filter) TimeFilter
func (*Way) Prepare ¶
Prepare creates a prepared statement for later queries or executions. If a transaction has already started, the transaction object should be used first.
func (*Way) QueryExists ¶
QueryExists executes a query statement to check if the data exists.
func (*Way) QueryRow ¶
func (s *Way) QueryRow(ctx context.Context, maker Maker, query func(row *sql.Row) error) (err error)
QueryRow executes a statement and return row data, typically, these are INSERT, UPDATE and DELETE.
func (*Way) Replace ¶
Replace get a single identifier mapping value, if it does not exist, return the original value.
func (*Way) ReplaceAll ¶
ReplaceAll get multiple identifier mapping values, return the original value if none exists.
func (*Way) Scan ¶
Scan executes a query statement and get all query results, through the mapping of column names and struct tags.
func (*Way) T ¶
func (s *Way) T(tableName ...string) TableColumn
T Register a shortcut method T to quickly create a TableColumn instance.
func (*Way) Table ¶
Table Create a *Table object to execute SELECT, INSERT, UPDATE, and DELETE statements.
func (*Way) Transaction ¶
func (s *Way) Transaction(ctx context.Context, fx 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, fx 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, fx 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) WindowFunc ¶
func (s *Way) WindowFunc(alias string) *WindowFunc
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) 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) 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, args ...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, args ...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, args ...any) *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, args ...any) *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) Over ¶
func (s *WindowFunc) Over(prepare string, args ...any) *WindowFunc
Over Define the OVER clause.
func (*WindowFunc) OverFunc ¶
func (s *WindowFunc) OverFunc(fx func(o SQLWindowFuncOver)) *WindowFunc
OverFunc Define the OVER clause.
func (*WindowFunc) PercentRank ¶
func (s *WindowFunc) PercentRank() *WindowFunc
PercentRank PERCENT_RANK()
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) 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) WindowFunc ¶
func (s *WindowFunc) WindowFunc(funcName string, funcArgs ...any) *WindowFunc
WindowFunc Using custom function. for example: CUME_DIST(), PERCENT_RANK(), PERCENTILE_CONT(), PERCENTILE_DISC()...