hey

package module
v5.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 18 Imported by: 0

README

What is hey?

Hey is a simple, high-performance ORM for Go.
For example: INSERT, DELETE, UPDATE, SELECT ...

hey's mission

  1. Support as many SQL general syntax as possible.
  2. Write less or no original strings in business code, such as "username", "SUM(salary)", "id = ?", "SELECT id, name FROM your_table_name" ...
  3. Try to avoid using reflection when scanning and querying data to reduce time consumption.
  4. Through the template code of the table structure, when the database table structure changes, your code can immediately perceive it.
  5. When you implement a business, focus more on the business rather than on building SQL statements.
  6. Allows the use of custom caches to reduce query request pressure on relational databases.
  7. It (hey) can help you build complex SQL statements, especially complex query SQL statements.
  8. Allows you to define a set of commonly used template SQL statements and use them in complex SQL statements.

INSTALL

go get github.com/cd365/hey/v5@latest

EXAMPLE

package main

import (
	"database/sql"
	"os"
	"time"

	"github.com/cd365/hey/v5"
	"github.com/cd365/logger/v9"
	_ "github.com/go-sql-driver/mysql" /* Registering the database driver */
	_ "github.com/lib/pq"              /* Registering the database driver */
	_ "github.com/mattn/go-sqlite3"    /* Registering the database driver */
)

// Postgresql Connect to postgresql
func Postgresql() (*hey.Way, error) {
	db, err := sql.Open("postgres", "postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable")
	if err != nil {
		return nil, err
	}

	db.SetConnMaxLifetime(time.Minute * 3)
	db.SetConnMaxIdleTime(time.Minute * 3)
	db.SetMaxOpenConns(1000)
	db.SetMaxIdleConns(200)

	way := hey.NewWay(db)

	cfg := way.GetCfg()

	cfg.Manual = hey.Postgresql()
	cfg.Manual.Replacer = hey.NewReplacer() // Optional, You can customize it by using "table_or_column_name" instead of table_or_column_name

	cfg.DeleteMustUseWhere = true
	cfg.UpdateMustUseWhere = true
	cfg.TransactionMaxDuration = time.Second * 5
	cfg.WarnDuration = time.Millisecond * 200
	// cfg.TransactionOptions = &sql.TxOptions{Isolation: sql.LevelReadCommitted}

	way.SetLogger(logger.NewLogger(os.Stdout)) // Optional, Record SQL call log

	return way, nil
}

// Mysql Connect to mysql
func Mysql() (*hey.Way, error) {
	db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/mysql?charset=utf8mb4&collation=utf8mb4_unicode_ci&timeout=90s&multiStatements=true")
	if err != nil {
		return nil, err
	}

	db.SetConnMaxLifetime(time.Minute * 3)
	db.SetConnMaxIdleTime(time.Minute * 3)
	db.SetMaxOpenConns(1000)
	db.SetMaxIdleConns(200)

	way := hey.NewWay(db)

	cfg := way.GetCfg()

	cfg.Manual = hey.Mysql()
	cfg.Manual.Replacer = hey.NewReplacer() // Optional, You can customize it by using `table_or_column_name` instead of table_or_column_name

	cfg.DeleteMustUseWhere = true
	cfg.UpdateMustUseWhere = true
	cfg.TransactionMaxDuration = time.Second * 5
	cfg.WarnDuration = time.Millisecond * 200
	// cfg.TransactionOptions = &sql.TxOptions{Isolation: sql.LevelRepeatableRead}

	way.SetLogger(logger.NewLogger(os.Stdout)) // Optional, Record SQL call log

	return way, nil
}

// Sqlite Connect to sqlite
func Sqlite() (*hey.Way, error) {
	db, err := sql.Open("sqlite3", "my_database.db")
	if err != nil {
		return nil, err
	}

	db.SetConnMaxLifetime(time.Minute * 3)
	db.SetConnMaxIdleTime(time.Minute * 3)
	db.SetMaxOpenConns(10)
	db.SetMaxIdleConns(2)

	way := hey.NewWay(db)

	cfg := way.GetCfg()

	cfg.Manual = hey.Mysql()
	cfg.Manual.Replacer = hey.NewReplacer() // Optional, You can customize it by using `table_or_column_name` instead of table_or_column_name

	cfg.DeleteMustUseWhere = true
	cfg.UpdateMustUseWhere = true
	cfg.TransactionMaxDuration = time.Second * 5
	cfg.WarnDuration = time.Millisecond * 200
	// cfg.TransactionOptions = &sql.TxOptions{Isolation: sql.LevelReadCommitted}

	way.SetLogger(logger.NewLogger(os.Stdout)) // Optional, Record SQL call log

	return way, nil
}

Documentation

Index

Constants

View Source
const (
	StrDefaultTag      = "db"
	StrTableMethodName = "TableName"

	StrEmpty = ""
	Str36    = "$"
	Str37    = "%"
	Str39    = "'"
	Str43    = "+"
	Str45    = "-"
	Str47    = "/"
	Str63    = "?"
	StrComma = ","
	StrPoint = "."
	StrStar  = "*"

	StrSpace      = " "
	StrCommaSpace = ", "

	StrNull = "NULL"
	StrAs   = "AS"
	StrAsc  = "ASC"
	StrDesc = "DESC"

	StrUnion        = "UNION"
	StrUnionAll     = "UNION ALL"
	StrIntersect    = "INTERSECT"
	StrIntersectAll = "INTERSECT ALL"
	StrExpect       = "EXCEPT"
	StrExpectAll    = "EXCEPT ALL"

	StrJoinInner = "INNER JOIN"
	StrJoinLeft  = "LEFT JOIN"
	StrJoinRight = "RIGHT JOIN"

	StrAnd = "AND"
	StrOr  = "OR"
	StrNot = "NOT"

	StrPlaceholder   = "?"
	StrEqual         = "="
	StrNotEqual      = "<>"
	StrLessThan      = "<"
	StrLessThanEqual = "<="
	StrMoreThan      = ">"
	StrMoreThanEqual = ">="

	StrAll = "ALL"
	StrAny = "ANY"

	StrLeftSmallBracket  = "("
	StrRightSmallBracket = ")"

	StrCoalesce = "COALESCE"
	StrCount    = "COUNT"
	StrAvg      = "AVG"
	StrMax      = "MAX"
	StrMin      = "MIN"
	StrSum      = "SUM"

	StrDistinct = "DISTINCT"

	StrSelect    = "SELECT"
	StrInsert    = "INSERT"
	StrUpdate    = "UPDATE"
	StrDelete    = "DELETE"
	StrFrom      = "FROM"
	StrInto      = "INTO"
	StrValues    = "VALUES"
	StrSet       = "SET"
	StrWhere     = "WHERE"
	StrReturning = "RETURNING"

	StrBetween     = "BETWEEN"
	StrConflict    = "CONFLICT"
	StrDo          = "DO"
	StrExcluded    = "EXCLUDED"
	StrExists      = "EXISTS"
	StrGroupBy     = "GROUP BY"
	StrHaving      = "HAVING"
	StrIn          = "IN"
	StrIs          = "IS"
	StrLike        = "LIKE"
	StrLimit       = "LIMIT"
	StrNothing     = "NOTHING"
	StrOffset      = "OFFSET"
	StrOn          = "ON"
	StrOrderBy     = "ORDER BY"
	StrOver        = "OVER"
	StrPartitionBy = "PARTITION BY"
	StrUsing       = "USING"
	StrWith        = "WITH"
	StrRecursive   = "RECURSIVE"

	StrCase = "CASE"
	StrWhen = "WHEN"
	StrThen = "THEN"
	StrElse = "ELSE"
	StrEnd  = "END"

	StrRange = "RANGE"
	StrRows  = "ROWS"
)
View Source
const (
	// ErrEmptyPrepare The prepared value executed is an empty string.
	ErrEmptyPrepare = Err("hey: the prepared value executed is an empty string")

	// ErrNoRows Error no rows.
	ErrNoRows = Err("hey: no rows")

	// ErrNoRowsAffected Error no rows affected.
	ErrNoRowsAffected = Err("hey: no rows affected")

	// ErrTransactionIsNil Error transaction isn't started.
	ErrTransactionIsNil = Err("hey: transaction is nil")

	// ErrMethodNotImplemented Error method not implemented.
	ErrMethodNotImplemented = Err("hey: method not implemented")
)
View Source
const DefaultAliasNameCount = "counts"
View Source
const StrId = "id"

Variables

This section is empty.

Functions

func AnyAny

func AnyAny[T any](slice []T) []any

AnyAny Convert any type of slice to []any.

func ArrayDiscard

func ArrayDiscard[V any](values []V, discard func(k int, v V) bool) []V

ArrayDiscard Delete some elements from a slice.

func ArrayToArray

func ArrayToArray[V any, W any](values []V, fc func(k int, v V) W) []W

ArrayToArray Create a slice from another slice.

func ArrayToAssoc

func ArrayToAssoc[V any, K comparable, W any](values []V, fc func(v V) (K, W)) map[K]W

ArrayToAssoc Create a map from a slice.

func AssocDiscard

func AssocDiscard[K comparable, V any](values map[K]V, discard func(k K, v V) bool) map[K]V

AssocDiscard Delete some elements from the map.

func AssocToArray

func AssocToArray[K comparable, V any, W any](values map[K]V, fc func(k K, v V) W) []W

AssocToArray Create a slice from a map.

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

AssocToAssoc Create a map based on another map.

func DiscardDuplicate

func DiscardDuplicate[T comparable](discard func(tmp T) bool, dynamic ...T) (result []T)

DiscardDuplicate Slice deduplication.

func DropTable

func DropTable(ctx context.Context, db *sql.DB, tables ...string) error

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

func ExecuteScript(ctx context.Context, db *sql.DB, execute string, args ...any) error

ExecuteScript Execute SQL script.

func InGroupValues

func InGroupValues[T any](values []T, fc func(tmp T) []any) [][]any

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

func InValues[T any](values []T, fc func(tmp T) any) []any

InValues Build column IN ( values[0].attributeN, values[1].attributeN, values[2].attributeN ... )

func LastNotEmptyString

func LastNotEmptyString(sss []string) string

LastNotEmptyString Get last not empty string, return empty string if it does not exist.

func LikeSearch added in v5.1.0

func LikeSearch(filter Filter, value any, columns ...string)

LikeSearch Implement the filter condition: ( column1 LIKE 'value' OR column2 LIKE 'value' OR column3 LIKE 'value' ... ) .

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 MergeArray

func MergeArray[V any](values ...[]V) []V

MergeArray Merge slices.

func MergeAssoc

func MergeAssoc[K comparable, V any](values ...map[K]V) map[K]V

MergeAssoc Merge maps.

func MustAffectedRows

func MustAffectedRows(affectedRows int64, err error) error

MustAffectedRows At least one row is affected.

func ParcelCancelPrepare

func ParcelCancelPrepare(prepare string) string

ParcelCancelPrepare Cancel parcel the SQL statement. ( `subquery` ) => `subquery` OR ( ( `subquery` ) ) => ( `subquery` )

func ParcelPrepare

func ParcelPrepare(prepare string) string

ParcelPrepare Parcel the SQL statement. `subquery` => ( `subquery` )

func Prefix

func Prefix(prefix string, name string) string

Prefix Add SQL prefix name; if the prefix exists, it will not be added.

func QuickScan added in v5.2.0

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

func RowsScan(rows *sql.Rows, result any, tag string) error

RowsScan Scan the query result set into the receiving object. Support type *AnyStruct, **AnyStruct, *[]AnyStruct, *[]*AnyStruct, **[]AnyStruct, **[]*AnyStruct, *[]int, *[]float64, *[]string ...

func SQLString

func SQLString(value string) string

SQLString Convert a go string to a sql string.

func SQLToString

func SQLToString(script *SQL) string

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 Strings

func Strings(elements ...string) string

Strings Concatenate multiple strings in sequence.

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

func StructModify(object any, tag string, except ...string) (fields []string, values []any)

StructModify Object should be one of anyStruct, *anyStruct get the fields and values that need to be modified.

func StructObtain

func StructObtain(object any, tag string, except ...string) (fields []string, values []any)

StructObtain Object should be one of anyStruct, *anyStruct for get all fields and values.

func StructUpdate

func StructUpdate(origin any, latest any, tag string, except ...string) (fields []string, values []any)

StructUpdate Compare origin and latest for update.

func TruncateTable

func TruncateTable(ctx context.Context, db *sql.DB, tables ...string) error

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 WayContext added in v5.1.0

func WayContext(ctx context.Context, way *Way) context.Context

WayContext Store *Way in the context.

Types

type AdjustColumnAnyValue added in v5.2.0

type AdjustColumnAnyValue func(columnTypes []*sql.ColumnType, results []map[string]any) error

type Cache

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

Cache Read and write data in cache.

func NewCache

func NewCache(cacher Cacher) *Cache

NewCache Create a new *Cache object.

func (*Cache) Del

func (s *Cache) Del(key string) error

Del Deleting data from the cache.

func (*Cache) DurationRange

func (s *Cache) DurationRange(duration time.Duration, minValue int, maxValue int) time.Duration

DurationRange Get a random Duration between minValue*duration and maxValue*duration.

func (*Cache) Exists

func (s *Cache) Exists(key string) (exists bool, err error)

Exists Whether cached data exists?

func (*Cache) Get

func (s *Cache) Get(key string) (value []byte, exists bool, err error)

Get Read cache data from cache.

func (*Cache) GetBool

func (s *Cache) GetBool(key string) (value bool, exists bool, err error)

GetBool Read bool cache data from cache.

func (*Cache) GetCacher

func (s *Cache) GetCacher() Cacher

GetCacher Read Cacher.

func (*Cache) GetFloat

func (s *Cache) GetFloat(key string) (value float64, exists bool, err error)

GetFloat Read float64 cache data from cache.

func (*Cache) GetInt

func (s *Cache) GetInt(key string) (value int64, exists bool, err error)

GetInt Read int64 cache data from cache.

func (*Cache) GetString

func (s *Cache) GetString(key string) (value string, exists bool, err error)

GetString Read string cache data from cache.

func (*Cache) GetUnmarshal

func (s *Cache) GetUnmarshal(key string, value any) (exists bool, err error)

GetUnmarshal Read cached data from the cache and deserialize cached data.

func (*Cache) MarshalSet

func (s *Cache) MarshalSet(key string, value any, duration ...time.Duration) error

MarshalSet Serialize cache data and write the serialized data to the cache.

func (*Cache) Set

func (s *Cache) Set(key string, value []byte, duration ...time.Duration) error

Set Write cache data to cache.

func (*Cache) SetBool

func (s *Cache) SetBool(key string, value bool, duration ...time.Duration) error

SetBool Write bool cache data to cache.

func (*Cache) SetCacher

func (s *Cache) SetCacher(cacher Cacher) *Cache

SetCacher Write Cacher.

func (*Cache) SetFloat

func (s *Cache) SetFloat(key string, value float64, duration ...time.Duration) error

SetFloat Write float64 cache data to cache.

func (*Cache) SetInt

func (s *Cache) SetInt(key string, value int64, duration ...time.Duration) error

SetInt Write int64 cache data to cache.

func (*Cache) SetString

func (s *Cache) SetString(key string, value string, duration ...time.Duration) error

SetString Write string cache data to 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 {
	// Debug For debug output SQL script.
	Debug DebugMaker

	// MapScan Custom MapScan.
	MapScan MapScanner

	// Manual For handling different types of databases.
	Manual *Manual

	// Scan For scanning 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

	// TableMethodName Custom method name to get table name.
	TableMethodName 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.

func DefaultCfg

func DefaultCfg() Cfg

DefaultCfg default configure value.

type DatabaseReader

type DatabaseReader interface {
	// Read Get an object for read.
	Read() *Way
}

DatabaseReader Separate read and write, when you distinguish between reading and writing, please do not use the same object for both reading and writing.

func NewDatabaseReader

func NewDatabaseReader(choose func(n int) int, reads []*Way) DatabaseReader

NewDatabaseReader It is recommended that objects used for writing should not appear in reads.

type DebugMaker

type DebugMaker interface {
	// Debug Output SQL script to the specified output stream.
	// Warning: Binary byte slice will be converted to hexadecimal strings.
	Debug(maker Maker) DebugMaker

	GetLogger() *logger.Logger

	SetLogger(log *logger.Logger) DebugMaker
}

DebugMaker Output SQL script to the specified output stream. Warning: Binary byte slice will be converted to hexadecimal strings.

func NewDebugMaker

func NewDebugMaker() DebugMaker

type Err

type Err string

func (Err) Error

func (s Err) Error() string

type Filter

type Filter interface {
	Maker

	// ToEmpty Clear the existing conditional filtering of the current object.
	ToEmpty() Filter

	// Num Number of conditions used.
	Num() int

	// IsEmpty Is the current object an empty object?
	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.
	And(script *SQL) Filter

	// Or Use logical operator `OR` to combine custom conditions.
	Or(script *SQL) 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(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 any, value any, null ...bool) 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

	// MoreThan Implement conditional filtering: column > value.
	MoreThan(column any, value any) Filter

	// MoreThanEqual Implement conditional filtering: column >= value .
	MoreThanEqual(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 ) .
	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, null ...bool) 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

	// 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

	// GetReplacer For get *Way.
	GetReplacer() Replacer

	// SetReplacer For set *Way.
	SetReplacer(replacer Replacer) 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

	// CompareMoreThan Implement conditional filtering: script1 > script2 .
	CompareMoreThan(column1 any, column2 any) Filter

	// CompareMoreThanEqual Implement conditional filtering: script1 >= script2 .
	CompareMoreThanEqual(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).

func F

func F() Filter

F New a Filter.

func ParcelFilter

func ParcelFilter(tmp Filter) Filter

ParcelFilter Parcel the SQL filter statement. `SQL_FILTER_STATEMENT` => ( `SQL_FILTER_STATEMENT` )

type Limiter

type Limiter interface {
	GetLimit() int64

	GetOffset() int64
}

Limiter limit and offset.

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.

func JoinMaker

func JoinMaker(separator string, makers ...Maker) Maker

JoinMaker Concatenate multiple SQL scripts and their parameter lists using a specified delimiter.

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

	// Replacer SQL Identifier Replacer.
	Replacer Replacer
}

Manual For handling different types of databases.

func Mysql

func Mysql() *Manual

func Postgresql

func Postgresql() *Manual

func Sqlite

func Sqlite() *Manual

type MapScanner added in v5.2.0

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 added in v5.2.0

func NewMapScanner() MapScanner

NewMapScanner Exposes a default implementation of the MapScanner interface.

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 MyContext added in v5.1.0

type MyContext string

MyContext Custom context key type.

const (
	// MyWay Store the *hey.Way, *hey.Way.
	MyWay MyContext = "HEY_MY_WAY"

	// MyTable Store the *hey.Table, *hey.Table.
	MyTable MyContext = "HEY_MY_TABLE"

	// MyTableName Store the original table name, string.
	MyTableName MyContext = "HEY_MY_TABLE_NAME"

	// MyAffectedRows Store the number of rows affected, int64.
	MyAffectedRows MyContext = "HEY_MY_AFFECTED_ROWS"

	// MyInsertOne Store the status for inserting a piece of data, bool.
	MyInsertOne MyContext = "HEY_MY_INSERT_ONE"

	// MyInsertAll Store the status for inserting multiple records status, bool.
	MyInsertAll MyContext = "HEY_MY_INSERT_ALL"

	// MyInsertData Store the inserted data, any.
	MyInsertData MyContext = "HEY_MY_INSERT_DATA"

	// MyInsertId Store the inserted id value, int64.
	MyInsertId MyContext = "HEY_MY_INSERT_ID"

	// MyInsertQuery Insert the query result data into the table, for example: data statistics table, *SQL.
	MyInsertQuery MyContext = "HEY_MY_INSERT_QUERY"
)

type MyDelete added in v5.1.0

type MyDelete interface {
	// AfterDelete Set post-delete data hook.
	AfterDelete(fc func(ctx context.Context) (context.Context, error))

	// AfterDeleteValue Get post-delete data hook.
	AfterDeleteValue() func(ctx context.Context) (context.Context, error)

	// BeforeDelete Set pre-delete data hook.
	BeforeDelete(fc func(ctx context.Context) (context.Context, error))

	// BeforeDeleteValue Get pre-delete data hook.
	BeforeDeleteValue() func(ctx context.Context) (context.Context, error)

	// DeleteFilter Custom delete logic Filter.
	DeleteFilter(fc func(f Filter))

	// DeleteFilterValue Custom delete logic Filter value.
	DeleteFilterValue() func(f Filter)

	// ResetDelete Reset the default Delete method.
	ResetDelete(fc func(ctx context.Context, where Filter) (affectedRows int64, err error))

	// Delete Physically delete data.
	Delete(ctx context.Context, where Filter) (affectedRows int64, err error)

	// DeleteById Physically delete data.
	DeleteById(ctx context.Context, ids any) (affectedRows int64, err error)
}

MyDelete For DELETE.

type MyHidden added in v5.1.0

type MyHidden interface {
	// AfterHidden Set post-hidden data hook.
	AfterHidden(fc func(ctx context.Context) (context.Context, error))

	// AfterHiddenValue Get post-hidden data hook.
	AfterHiddenValue() func(ctx context.Context) (context.Context, error)

	// BeforeHidden Set pre-hidden data hook.
	BeforeHidden(fc func(ctx context.Context) (context.Context, error))

	// BeforeHiddenValue Get pre-hidden data hook.
	BeforeHiddenValue() func(ctx context.Context) (context.Context, error)

	// HiddenFilter Custom hidden logic Filter.
	HiddenFilter(fc func(f Filter))

	// HiddenFilterValue Custom hidden logic Filter value.
	HiddenFilterValue() func(f Filter)

	// HiddenUpdate Set pseudo-delete logic method.
	HiddenUpdate(fc func(u SQLUpdateSet))

	// ResetHidden Reset the default Hidden method.
	ResetHidden(fc func(ctx context.Context, where Filter) (affectedRows int64, err error))

	// Hidden Logical deletion of data.
	Hidden(ctx context.Context, where Filter) (affectedRows int64, err error)

	// HiddenById Logical deletion of data.
	HiddenById(ctx context.Context, ids any) (affectedRows int64, err error)
}

MyHidden Logical deletion of data.

type MyInsert added in v5.1.0

type MyInsert interface {
	// AfterInsert Set post-insert data hook.
	AfterInsert(fc func(ctx context.Context) (context.Context, error))

	// AfterInsertValue Get post-insert data hook.
	AfterInsertValue() func(ctx context.Context) (context.Context, error)

	// BeforeInsert Set pre-insert data hook.
	BeforeInsert(fc func(ctx context.Context) (context.Context, error))

	// BeforeInsertValue Get pre-insert data hook.
	BeforeInsertValue() func(ctx context.Context) (context.Context, error)

	// ResetInsertOne Reset the default InsertOne method.
	ResetInsertOne(fc func(ctx context.Context, insert any) (id int64, err error))

	// ResetInsertAll Reset the default InsertAll method.
	ResetInsertAll(fc func(ctx context.Context, insert any) (affectedRows int64, err error))

	// ResetInsertFromQuery Reset the default InsertFromQuery method.
	ResetInsertFromQuery(fc func(ctx context.Context, columns []string, query Maker) (affectedRows int64, err error))

	// InsertOne Insert a record and return the primary key value (usually an integer value).
	InsertOne(ctx context.Context, insert any) (id int64, err error)

	// InsertAll Insert multiple records and return the number of rows affected.
	InsertAll(ctx context.Context, insert any) (affectedRows int64, err error)

	// InsertFromQuery Insert the query result data into the table, for example: data statistics table.
	InsertFromQuery(ctx context.Context, columns []string, query Maker) (affectedRows int64, err error)
}

MyInsert For INSERT.

type MySchema added in v5.1.0

type MySchema interface {
	MyInsert
	MyDelete
	MyUpdate
	MySelect
	MyHidden
}

MySchema Combo MyInsert, MyDelete, MyUpdate, MySelect, MyHidden interfaces.

type MySelect added in v5.1.0

type MySelect interface {
	// Table Get table name.
	Table() string

	// Columns Get table columns.
	Columns() []string

	// SelectFilter Custom select logic Filter.
	SelectFilter(fc func(f Filter))

	// SelectFilterValue Custom select logic Filter value.
	SelectFilterValue() func(f Filter)

	// ResetSelect Reset the default Select method.
	ResetSelect(fc func(ctx context.Context, selectAll func(ctx context.Context, table *Table) error, options ...func(o *Table)) error)

	// SelectAll Query multiple data.
	SelectAll(ctx context.Context, receiver any, options ...func(o *Table)) error

	// SelectOne Query a piece of data.
	SelectOne(ctx context.Context, receiver any, options ...func(o *Table)) error

	// SelectAllById Query multiple data.
	SelectAllById(ctx context.Context, ids any, receiver any, options ...func(o *Table)) error

	// SelectOneById Query a piece of data.
	SelectOneById(ctx context.Context, id any, receiver any, options ...func(o *Table)) error

	// SelectSQL Construct a subquery as a query table or CTE.
	SelectSQL(options ...func(o *Table)) *SQL

	// SelectExists Check whether the data exists.
	SelectExists(ctx context.Context, options ...func(o *Table)) (bool, error)

	// SelectCount Total number of statistical records.
	SelectCount(ctx context.Context, options ...func(o *Table)) (count int64, err error)

	// SelectCountFetch First count the total number of entries, then scan the list data.
	SelectCountFetch(ctx context.Context, receiver any, options ...func(o *Table)) (count int64, err error)

	// F Quickly create a new Filter instance.
	F() Filter

	// Equal Filter.Equal
	Equal(column any, value any) Filter

	// In Filter.In
	In(column any, values ...any) Filter

	// InGroup Filter.InGroup
	InGroup(columns any, values any) Filter

	// IdEqual Filter.Equal using id.
	IdEqual(value any) Filter

	// IdIn Filter.In using id.
	IdIn(values ...any) Filter

	// LikeSearch Keyword search matches multiple columns.
	LikeSearch(keyword string, columns ...string) Filter
}

MySelect For SELECT.

type MyUpdate added in v5.1.0

type MyUpdate interface {
	// AfterUpdate Set post-update data hook.
	AfterUpdate(fc func(ctx context.Context) (context.Context, error))

	// AfterUpdateValue Get post-update data hook.
	AfterUpdateValue() func(ctx context.Context) (context.Context, error)

	// BeforeUpdate Set pre-update data hook.
	BeforeUpdate(fc func(ctx context.Context) (context.Context, error))

	// BeforeUpdateValue Get pre-update data hook.
	BeforeUpdateValue() func(ctx context.Context) (context.Context, error)

	// UpdateFilter Custom update logic Filter.
	UpdateFilter(fc func(f Filter))

	// UpdateFilterValue Custom update logic Filter value.
	UpdateFilterValue() func(f Filter)

	// ResetUpdate Reset the default Update method.
	ResetUpdate(fc func(ctx context.Context, where Filter, update func(u SQLUpdateSet)) (affectedRows int64, err error))

	// Update Implementing updated data.
	Update(ctx context.Context, where Filter, update func(u SQLUpdateSet)) (affectedRows int64, err error)

	// UpdateById Implementing updated data.
	UpdateById(ctx context.Context, ids any, update func(u SQLUpdateSet)) (affectedRows int64, err error)

	// Modify Implementing updated data.
	Modify(ctx context.Context, where Filter, modify any) (affectedRows int64, err error)

	// ModifyById Implementing updated data.
	ModifyById(ctx context.Context, id any, modify any) (affectedRows int64, err error)
}

MyUpdate For UPDATE.

type Quantifier

type Quantifier interface {
	GetQuantifier() string

	SetQuantifier(quantifierString string) Quantifier

	Equal(column any, subquery Maker) Quantifier

	NotEqual(column any, subquery Maker) Quantifier

	LessThan(column any, subquery Maker) Quantifier

	LessThanEqual(column any, subquery Maker) Quantifier

	MoreThan(column any, subquery Maker) Quantifier

	MoreThanEqual(column any, subquery Maker) Quantifier
}

Quantifier Implement the filter condition: column {=||<>||>||>=||<||<=} [QUANTIFIER ]( subquery ) . QUANTIFIER is usually one of ALL, ANY, SOME ... or EmptyString.

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 Avg

func Avg(values ...any) *SQL

Avg Building SQL function AVG.

func Coalesce

func Coalesce(values ...any) *SQL

Coalesce Building SQL function COALESCE.

func CopySQL

func CopySQL(src *SQL) (dst *SQL)

CopySQL Copy *SQL.

func Count

func Count(values ...any) *SQL

Count Building SQL function COUNT.

func ExceptAllSQL

func ExceptAllSQL(scripts ...*SQL) *SQL

ExceptAllSQL *SQL1, *SQL2, *SQL3 ... => ( ( QUERY_A ) EXCEPT ALL ( QUERY_B ) EXCEPT ALL ( QUERY_C )... )

func ExceptSQL

func ExceptSQL(scripts ...*SQL) *SQL

ExceptSQL *SQL1, *SQL2, *SQL3 ... => ( ( QUERY_A ) EXCEPT ( QUERY_B ) EXCEPT ( QUERY_C )... )

func FuncSQL

func FuncSQL(funcName string, funcArgs ...any) *SQL

FuncSQL Building SQL functions.

func IntersectAllSQL

func IntersectAllSQL(scripts ...*SQL) *SQL

IntersectAllSQL *SQL1, *SQL2, *SQL3 ... => ( ( QUERY_A ) INTERSECT ALL ( QUERY_B ) INTERSECT ALL ( QUERY_C )... )

func IntersectSQL

func IntersectSQL(scripts ...*SQL) *SQL

IntersectSQL *SQL1, *SQL2, *SQL3 ... => ( ( QUERY_A ) INTERSECT ( QUERY_B ) INTERSECT ( QUERY_C )... )

func JoinSQL

func JoinSQL(separator string, values ...any) *SQL

JoinSQL Use `separator` to concatenate multiple SQL scripts and parameters.

func JoinSQLComma

func JoinSQLComma(values ...any) *SQL

JoinSQLComma Use StrComma to concatenate multiple SQL scripts and parameters.

func JoinSQLCommaSpace

func JoinSQLCommaSpace(values ...any) *SQL

JoinSQLCommaSpace Use StrCommaSpace to concatenate multiple SQL scripts and parameters.

func JoinSQLEmpty

func JoinSQLEmpty(values ...any) *SQL

JoinSQLEmpty Use StrEmpty to concatenate multiple SQL scripts and parameters.

func JoinSQLSpace

func JoinSQLSpace(values ...any) *SQL

JoinSQLSpace Use StrSpace to concatenate multiple SQL scripts and parameters.

func Max

func Max(values ...any) *SQL

Max Building SQL function MAX.

func Min

func Min(values ...any) *SQL

Min Building SQL function MIN.

func NewEmptySQL

func NewEmptySQL() *SQL

func NewSQL

func NewSQL(prepare string, args ...any) *SQL

func ParcelCancelSQL

func ParcelCancelSQL(script *SQL) *SQL

ParcelCancelSQL Cancel parcel the SQL statement. ( `subquery` ) => `subquery` OR ( ( `subquery` ) ) => ( `subquery` )

func ParcelSQL

func ParcelSQL(script *SQL) *SQL

ParcelSQL Parcel the SQL statement. `subquery` => ( `subquery` )

func Sum

func Sum(values ...any) *SQL

Sum Building SQL function SUM.

func UnionAllSQL

func UnionAllSQL(scripts ...*SQL) *SQL

UnionAllSQL *SQL1, *SQL2, *SQL3 ... => ( ( QUERY_A ) UNION ALL ( QUERY_B ) UNION ALL ( QUERY_C )... )

func UnionSQL

func UnionSQL(scripts ...*SQL) *SQL

UnionSQL *SQL1, *SQL2, *SQL3 ... => ( ( QUERY_A ) UNION ( QUERY_B ) UNION ( QUERY_C )... )

func (*SQL) Copy

func (s *SQL) Copy() *SQL

Copy Make a copy.

func (*SQL) IsEmpty

func (s *SQL) IsEmpty() bool

IsEmpty Used to determine whether the current SQL fragments or SQL statements is empty string.

func (*SQL) ToEmpty

func (s *SQL) ToEmpty() *SQL

ToEmpty Set Prepare, Args to empty value.

func (*SQL) ToSQL

func (s *SQL) ToSQL() *SQL

ToSQL Implementing the Maker interface.

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.

func Alias

func Alias(script any, aliases ...string) SQLAlias

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

func NewSQLCase(way *Way) SQLCase

type SQLComment

type SQLComment interface {
	Maker

	ToEmpty

	// Comment Add comment.
	Comment(comment string) SQLComment
}

SQLComment Constructing SQL statement comments.

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

	// 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

	// Subquery Use the query result as the values of the insert statement.
	Subquery(subquery Maker) SQLInsert

	// ColumnValue Set a single column and value.
	ColumnValue(column string, value any) 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

	// Returning Insert a piece of data and get the auto-increment value.
	Returning(fc 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(fc func(o SQLOnConflict)) SQLInsert
}

SQLInsert Build INSERT statements.

type SQLJoin

type SQLJoin interface {
	Maker

	ToEmpty

	// GetTable Get join query the main table.
	GetTable() SQLAlias

	// SetTable Set join query the main table.
	SetTable(table SQLAlias) SQLJoin

	// Table Create a table for join query.
	Table(table any, alias string) SQLAlias

	// On Set the join query conditions.
	On(on func(on SQLJoinOn, table1alias string, table2alias string)) SQLJoinAssoc

	// Using The conditions for the join query use USING.
	Using(columns ...string) SQLJoinAssoc

	// OnEqual The join query conditions uses table1.column = table2.column.
	OnEqual(table1column string, table2column string) SQLJoinAssoc

	// Join Use the join type to set the table join relationship, if the table1 value is nil, use the main table.
	Join(joinType string, table1 SQLAlias, table2 SQLAlias, on SQLJoinAssoc) SQLJoin

	// InnerJoin Set the table join relationship, if the table1 value is nil, use the main table.
	InnerJoin(table1 SQLAlias, table2 SQLAlias, on SQLJoinAssoc) SQLJoin

	// LeftJoin Set the table join relationship, if the table1 value is nil, use the main table.
	LeftJoin(table1 SQLAlias, table2 SQLAlias, on SQLJoinAssoc) SQLJoin

	// RightJoin Set the table join relationship, if the table1 value is nil, use the main table.
	RightJoin(table1 SQLAlias, table2 SQLAlias, on SQLJoinAssoc) SQLJoin

	// Select Set the query column list.
	Select(columns ...any) SQLJoin

	// Prefix Set column prefix with the table name or table alias.
	Prefix(prefix SQLAlias, column string, aliases ...string) string

	// PrefixSelect Add a column list to the query based on the table alias or table name prefix.
	PrefixSelect(prefix SQLAlias, columns ...string) SQLJoin
}

SQLJoin Build a join query.

type SQLJoinAssoc

type SQLJoinAssoc func(table1alias string, table2alias string) SQLJoinOn

type SQLJoinOn

type SQLJoinOn interface {
	Maker

	// Equal Use equal value JOIN ON condition.
	Equal(table1alias string, table1column string, table2alias string, table2column string) SQLJoinOn

	// On Append custom conditions to the ON statement or use custom conditions on the ON statement to associate tables.
	On(on func(f Filter)) SQLJoinOn

	// Using Use USING instead of ON.
	Using(columns ...string) SQLJoinOn
}

SQLJoinOn Construct the connection query conditions.

type SQLLimit

type SQLLimit interface {
	Maker

	ToEmpty

	// Limit SQL LIMIT.
	Limit(limit int64) SQLLimit

	// Offset SQL OFFSET.
	Offset(offset int64) SQLLimit

	// Page SQL LIMIT and OFFSET.
	Page(page int64, limit ...int64) SQLLimit
}

SQLLimit Build LIMIT n[ OFFSET m] statements.

type SQLOnConflict

type SQLOnConflict interface {
	Maker

	ToEmpty

	// 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) 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(fc func(u SQLOnConflictUpdateSet)) 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

	// Asc Build column1 ASC, column2 ASC, column3 ASC...
	Asc(columns ...string) SQLOrderBy

	// Desc Build column1 DESC, column2 DESC, column3 DESC...
	Desc(columns ...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

	// Execute 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)
	Execute(execute func(ctx context.Context, stmt *Stmt, args ...any) (id int64, err error)) 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 Put Maker to the query list.
	Add(maker Maker) SQLSelect

	// Del Delete some columns from the query list. If not specified, delete all.
	Del(columns ...string) SQLSelect

	// Has Does the column exist in the query list?
	Has(column string) bool

	// Len Query list length.
	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. If no parameter is provided, all existing query lists will be deleted.
	Select(columns ...any) SQLSelect
}

SQLSelect Build the query column set.

type SQLUpdateSet

type SQLUpdateSet interface {
	Maker

	ToEmpty

	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

	// SetMap Update column assignment by map.
	SetMap(columnValue map[string]any) SQLUpdateSet

	// SetSlice Update column assignment by slice.
	SetSlice(columns []string, values []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 ...
	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

	// Subquery The inserted data is a subquery.
	Subquery(subquery Maker) SQLValues

	// Values The inserted data of VALUES.
	Values(values ...[]any) SQLValues
}

SQLValues Build INSERT-VALUES statements.

type SQLWindowFuncFrame

type SQLWindowFuncFrame interface {
	Maker

	// SQL Custom SQL statement.
	SQL(value any) 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(fc 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 ROWS or RANGE statements.

func NewSQLWindowFuncFrame

func NewSQLWindowFuncFrame(frame string) SQLWindowFuncFrame

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 Prepare a handle.

func (*Stmt) Close

func (s *Stmt) Close() (err error)

Close -> Close prepare a handle.

func (*Stmt) Exec

func (s *Stmt) Exec(ctx context.Context, args ...any) (sql.Result, error)

Exec -> Execute prepared, that can be called repeatedly.

func (*Stmt) Execute

func (s *Stmt) Execute(ctx context.Context, args ...any) (int64, error)

Execute -> Execute prepared, that can be called repeatedly, return number of rows affected.

func (*Stmt) Fetch

func (s *Stmt) Fetch(ctx context.Context, result any, args ...any) error

Fetch -> Query prepared and get all query results, that can be called repeatedly.

func (*Stmt) Query

func (s *Stmt) Query(ctx context.Context, query func(rows *sql.Rows) error, args ...any) error

Query -> Query prepared, that can be called repeatedly.

func (*Stmt) QueryRow

func (s *Stmt) QueryRow(ctx context.Context, query func(row *sql.Row) error, args ...any) error

QueryRow -> 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.

func (*StringMutex) Get

func (s *StringMutex) Get(key string) *sync.Mutex

Get returns the sync.Mutex corresponding to the given key.

func (*StringMutex) Len

func (s *StringMutex) Len() int

Len returns the number of mutexes.

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

func (s *Table) Alias(alias string) *Table

Alias Set the table alias name.

func (*Table) Asc

func (s *Table) Asc(column string) *Table

Asc Sort ascending.

func (*Table) Comment

func (s *Table) Comment(comment string) *Table

Comment SQL statement notes.

func (*Table) Count

func (s *Table) Count(ctx context.Context, counts ...string) (int64, error)

Count Total number of statistics.

func (*Table) CountFetch added in v5.1.0

func (s *Table) CountFetch(ctx context.Context, result any, counts ...string) (count int64, err error)

CountFetch Merge statistics and scan data.

func (*Table) Create

func (s *Table) Create(ctx context.Context, create any) (int64, error)

Create Quickly insert data into the table.

func (*Table) Delete

func (s *Table) Delete(ctx context.Context) (int64, error)

Delete Execute a DELETE statement.

func (*Table) Desc

func (s *Table) Desc(column string) *Table

Desc Sort descending.

func (*Table) Distinct

func (s *Table) Distinct() *Table

Distinct SQL DISTINCT columns.

func (*Table) F

func (s *Table) F(filters ...Filter) Filter

F Quickly create a Filter.

func (*Table) Fetch

func (s *Table) Fetch(ctx context.Context, result any) error

Fetch Scan data into result by reflect.

func (*Table) GROUP

func (s *Table) GROUP(fc func(g SQLGroupBy)) *Table

GROUP Set GROUP BY through func.

func (*Table) Group

func (s *Table) Group(groups ...any) *Table

Group Set GROUP BY condition.

func (*Table) HAVING

func (s *Table) HAVING(fc func(h Filter)) *Table

HAVING Set HAVING through func.

func (*Table) Having

func (s *Table) Having(filters ...Filter) *Table

Having Set the HAVING condition.

func (*Table) INSERT

func (s *Table) INSERT(fc func(i SQLInsert)) *Table

INSERT Set inserting data through func.

func (*Table) InnerJoin

func (s *Table) InnerJoin(fc func(j SQLJoin) (left SQLAlias, right SQLAlias, assoc SQLJoinAssoc)) *Table

InnerJoin INNER JOIN.

func (*Table) Insert

func (s *Table) Insert(ctx context.Context) (int64, error)

Insert Execute an INSERT INTO statement.

func (*Table) JOIN

func (s *Table) JOIN(fc func(j SQLJoin)) *Table

JOIN Custom join query.

func (*Table) LIMIT

func (s *Table) LIMIT(fc func(o SQLLimit)) *Table

LIMIT Set LIMIT x [OFFSET x] through func.

func (*Table) LeftJoin

func (s *Table) LeftJoin(fc func(j SQLJoin) (left SQLAlias, right SQLAlias, assoc SQLJoinAssoc)) *Table

LeftJoin LEFT JOIN.

func (*Table) Limit

func (s *Table) Limit(limit int64) *Table

Limit Set the maximum number of query result sets.

func (*Table) Limiter

func (s *Table) Limiter(limiter Limiter) *Table

Limiter Set limit and offset at the same time.

func (*Table) MapScan added in v5.2.0

func (s *Table) MapScan(ctx context.Context, adjusts ...AdjustColumnAnyValue) ([]map[string]any, error)

MapScan Scanning the query results into []map[string]any.

func (*Table) Modify

func (s *Table) Modify(ctx context.Context, modify any) (int64, error)

Modify Quickly update data in the table.

func (*Table) ORDER

func (s *Table) ORDER(fc func(o SQLOrderBy)) *Table

ORDER Set ORDER BY through func.

func (*Table) Offset

func (s *Table) Offset(offset int64) *Table

Offset Set the offset of the query target data.

func (*Table) Page

func (s *Table) Page(page int64, limit ...int64) *Table

Page Pagination query, page number + page limit.

func (*Table) Query

func (s *Table) Query(ctx context.Context, query func(rows *sql.Rows) error) error

Query Execute a SELECT statement.

func (*Table) RightJoin

func (s *Table) RightJoin(fc func(j SQLJoin) (left SQLAlias, right SQLAlias, assoc SQLJoinAssoc)) *Table

RightJoin RIGHT JOIN.

func (*Table) SELECT

func (s *Table) SELECT(fc func(q SQLSelect)) *Table

SELECT Set SELECT through func.

func (*Table) Select

func (s *Table) Select(selects ...any) *Table

Select Add one or more query lists. If no parameter is provided, all existing query lists will be deleted.

func (*Table) TABLE

func (s *Table) TABLE(fc func(t SQLAlias)) *Table

TABLE Set query table through func.

func (*Table) Table

func (s *Table) Table(table any) *Table

Table Set the table name, or possibly a subquery with an alias.

func (*Table) ToCount added in v5.1.0

func (s *Table) ToCount(counts ...string) *SQL

ToCount Build COUNT-SELECT statement.

func (*Table) ToDelete

func (s *Table) ToDelete() *SQL

ToDelete Build DELETE statement.

func (*Table) ToEmpty

func (s *Table) ToEmpty() *Table

ToEmpty Do not reset table.

func (*Table) ToInsert

func (s *Table) ToInsert() *SQL

ToInsert Build INSERT statement.

func (*Table) ToSQL

func (s *Table) ToSQL() *SQL

ToSQL Implementing the Maker interface using query statement.

func (*Table) ToSelect

func (s *Table) ToSelect() *SQL

ToSelect Build SELECT statement.

func (*Table) ToUpdate

func (s *Table) ToUpdate() *SQL

ToUpdate Build UPDATE statement.

func (*Table) UPDATE

func (s *Table) UPDATE(fc func(f Filter, u SQLUpdateSet)) *Table

UPDATE Set updating data through func.

func (*Table) Update

func (s *Table) Update(ctx context.Context) (int64, error)

Update Execute an UPDATE statement.

func (*Table) V

func (s *Table) V(values ...*Way) *Table

V Use *Way given a non-nil value.

func (*Table) W

func (s *Table) W() *Way

W Get the currently used *Way object.

func (*Table) WHERE

func (s *Table) WHERE(fc func(f Filter)) *Table

WHERE Set WHERE through func.

func (*Table) WITH

func (s *Table) WITH(fc func(w SQLWith)) *Table

WITH Custom common table expression (CTE).

func (*Table) Where

func (s *Table) Where(filters ...Filter) *Table

Where Set the WHERE condition.

func (*Table) With

func (s *Table) With(alias string, maker Maker, columns ...string) *Table

With Add a common table expression.

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

func (s *TableColumn) Alias() string

Alias Get the alias name value.

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.

func (*TableColumn) Sum

func (s *TableColumn) Sum(column string, aliases ...string) string

Sum SUM(column[, alias])

type TableNamer

type TableNamer interface {
	// Table Get the table name.
	Table() string
}

TableNamer Generic interface for getting table name.

type ToEmpty

type ToEmpty interface {
	// ToEmpty Sets the property value of an object to empty value.
	ToEmpty()
}

ToEmpty Sets the property value of an object to empty value.

type Way

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

Way Quick insert, delete, update, select helper.

func ContextWay added in v5.1.0

func ContextWay(ctx context.Context, defaultWay *Way) *Way

ContextWay Try to extract *Way from the context.

func NewWay

func NewWay(db *sql.DB) *Way

func (*Way) Alias

func (s *Way) Alias(script any, aliases ...string) SQLAlias

func (*Way) Begin

func (s *Way) Begin(ctx context.Context, opts ...*sql.TxOptions) (*Way, error)

Begin -> Open transaction.

func (*Way) BeginConn

func (s *Way) BeginConn(ctx context.Context, conn *sql.Conn, opts ...*sql.TxOptions) (*Way, error)

BeginConn -> Open transaction using *sql.Conn.

func (*Way) Case

func (s *Way) Case() SQLCase

func (*Way) Commit

func (s *Way) Commit() error

Commit -> Transaction commit.

func (*Way) Create added in v5.1.0

func (s *Way) Create(ctx context.Context, table any, values any, options ...func(t *Table)) (int64, error)

Create Quick insert, the first method in options will serve as the pre-method, and all the subsequent methods will serve as post-methods.

func (*Way) Debug

func (s *Way) Debug(maker Maker) *Way

Debug Debugging output SQL script.

func (*Way) Delete added in v5.1.0

func (s *Way) Delete(ctx context.Context, table any, column string, values any, options ...func(f Filter)) (int64, error)

Delete Quick delete.

func (*Way) DeleteById added in v5.1.0

func (s *Way) DeleteById(ctx context.Context, table any, values any, options ...func(f Filter)) (int64, error)

DeleteById Delete data according to one or more id values.

func (*Way) Exec

func (s *Way) Exec(ctx context.Context, maker Maker) (sql.Result, error)

Exec -> Execute the execute sql statement.

func (*Way) Execute

func (s *Way) Execute(ctx context.Context, maker Maker) (int64, error)

Execute -> Execute the execute sql statement.

func (*Way) F

func (s *Way) F(filters ...Filter) Filter

F -> Quickly initialize a filter.

func (*Way) Fetch

func (s *Way) Fetch(ctx context.Context, maker Maker, result any) error

Fetch -> Query prepared and get all query results, through the mapping of column names and struct tags.

func (*Way) Func

func (s *Way) Func(funcName string, funcArgs ...any) *SQL

Func Building SQL functions.

func (*Way) GetCfg

func (s *Way) GetCfg() *Cfg

func (*Way) GetDatabase

func (s *Way) GetDatabase() *sql.DB

func (*Way) GetDatabaseReader

func (s *Way) GetDatabaseReader() DatabaseReader

func (*Way) GetLogger

func (s *Way) GetLogger() *logger.Logger

func (*Way) IsInTransaction

func (s *Way) IsInTransaction() bool

IsInTransaction -> Is the transaction currently in progress?

func (*Way) IsRead

func (s *Way) IsRead() bool

IsRead -> Is an object for read?

func (*Way) MapScan added in v5.2.0

func (s *Way) MapScan(ctx context.Context, maker Maker, adjusts ...AdjustColumnAnyValue) (result []map[string]any, err error)

MapScan -> Scanning the query results into []map[string]any.

func (*Way) MultiExecute

func (s *Way) MultiExecute(ctx context.Context, makers []Maker) (affectedRows int64, err error)

MultiExecute Execute multiple DML statements.

func (*Way) MultiFetch

func (s *Way) MultiFetch(ctx context.Context, makers []Maker, results []any) (err error)

MultiFetch Execute multiple DQL statements.

func (*Way) MultiStmtExecute

func (s *Way) MultiStmtExecute(ctx context.Context, prepare string, lists [][]any) (affectedRows int64, err error)

MultiStmtExecute Executing a DML statement multiple times using the same prepared statement.

func (*Way) MultiStmtFetch

func (s *Way) MultiStmtFetch(ctx context.Context, prepare string, lists [][]any, results []any) (err error)

MultiStmtFetch Executing a DQL statement multiple times using the same prepared statement.

func (*Way) MyDelete added in v5.1.0

func (s *Way) MyDelete(table string) MyDelete

func (*Way) MyHidden added in v5.1.0

func (s *Way) MyHidden(table string, update func(u SQLUpdateSet)) MyHidden

func (*Way) MyInsert added in v5.1.0

func (s *Way) MyInsert(table string) MyInsert

func (*Way) MySchema added in v5.1.0

func (s *Way) MySchema(table string, columns []string) MySchema

func (*Way) MySelect added in v5.1.0

func (s *Way) MySelect(table string, columns []string) MySelect

func (*Way) MyUpdate added in v5.1.0

func (s *Way) MyUpdate(table string) MyUpdate

func (*Way) Now

func (s *Way) Now() time.Time

Now -> Get current time, the transaction open status will get the same time.

func (*Way) Prepare

func (s *Way) Prepare(ctx context.Context, prepare string) (stmt *Stmt, err error)

Prepare -> Prepare SQL statement, remember to call *Stmt.Close().

func (*Way) Query

func (s *Way) Query(ctx context.Context, maker Maker, query func(rows *sql.Rows) error) error

Query -> Execute the query sql statement.

func (*Way) QueryRow

func (s *Way) QueryRow(ctx context.Context, maker Maker, query func(row *sql.Row) error) error

QueryRow -> Execute SQL statement and return row data, usually INSERT, UPDATE, DELETE.

func (*Way) Read

func (s *Way) Read() *Way

func (*Way) Replace

func (s *Way) Replace(key string) string

Replace Get a single identifier mapping value, if it does not exist, return the original value.

func (*Way) ReplaceAll

func (s *Way) ReplaceAll(keys []string) []string

ReplaceAll Get multiple identifier mapping values, return the original value if none exists.

func (*Way) Rollback

func (s *Way) Rollback() error

Rollback -> Transaction rollback.

func (*Way) SetCfg

func (s *Way) SetCfg(cfg *Cfg) *Way

func (*Way) SetDatabase

func (s *Way) SetDatabase(db *sql.DB) *Way

func (*Way) SetDatabaseReader

func (s *Way) SetDatabaseReader(reader DatabaseReader) *Way

func (*Way) SetLogger

func (s *Way) SetLogger(log *logger.Logger) *Way

func (*Way) T

func (s *Way) T() *TableColumn

T Table empty alias

func (*Way) Table

func (s *Way) Table(table any) *Table

Table Create a *Table object to execute SELECT, INSERT, UPDATE, and DELETE statements.

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

func (s *Way) TransactionMessage(message string) *Way

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) Update added in v5.1.0

func (s *Way) Update(ctx context.Context, table any, column string, value any, update any, options ...func(f Filter, u SQLUpdateSet)) (int64, error)

Update Quick update, the first method in options will serve as the pre-method, and all the subsequent methods will serve as post-methods.

func (*Way) UpdateById added in v5.1.0

func (s *Way) UpdateById(ctx context.Context, table any, value any, update any, options ...func(f Filter, u SQLUpdateSet)) (int64, error)

UpdateById Update by id value, the first method in options will serve as the pre-method, and all the subsequent methods will serve as post-methods.

func (*Way) V

func (s *Way) V(values ...*Way) *Way

V -> Prioritize the specified non-empty object, otherwise use the current object.

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

func (s *WindowFunc) CumeDist() *WindowFunc

CumeDist CUME_DIST()

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, 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) 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) PercentRank

func (s *WindowFunc) PercentRank() *WindowFunc

PercentRank PERCENT_RANK()

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(funcName string, funcArgs ...any) *WindowFunc

Window Using custom function. for example: CUME_DIST(), PERCENT_RANK(), PERCENTILE_CONT(), PERCENTILE_DISC()...

Jump to

Keyboard shortcuts

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