hey

package module
v2.0.7 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2025 License: MIT Imports: 13 Imported by: 1

README

What is hey?

Hey is a SQL building tool that helps you quickly generate commonly used SQL statements.
For example: INSERT, DELETE, UPDATE, SELECT ...

INSTALL

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

Documentation

Overview

Package hey is a helper that quickly responds to the results of insert, delete, update, select sql statements. You can also use hey to quickly build sql statements.

Index

Constants

View Source
const (
	State0 = 0
	State1 = 1

	StateY = "Y"
	StateN = "N"

	StateYes = "YES"
	StateNo  = "NO"

	StateOn  = "ON"
	StateOff = "OFF"
)

Common data values for table.column.

View Source
const (
	DriverNameMysql    = "mysql"
	DriverNamePostgres = "postgres"
	DriverNameSqlite3  = "sqlite3"
)
View Source
const (
	// DefaultTag Mapping of default database column name and struct tag.
	DefaultTag = "db"

	// EmptyString Empty string value.
	EmptyString = ""
)
View Source
const (
	SqlPoint = "."
	SqlSpace = " "
	SqlStar  = "*"

	SqlAs       = "AS"
	SqlAsc      = "ASC"
	SqlDesc     = "DESC"
	SqlUnion    = "UNION"
	SqlUnionAll = "UNION ALL"

	SqlJoinInner = "INNER JOIN"
	SqlJoinLeft  = "LEFT JOIN"
	SqlJoinRight = "RIGHT JOIN"
	SqlJoinFull  = "FULL JOIN"
	SqlJoinCross = "CROSS JOIN"

	SqlAnd = "AND"
	SqlOr  = "OR"

	SqlNot  = "NOT"
	SqlNull = "NULL"

	SqlPlaceholder      = "?"
	SqlEqual            = "="
	SqlNotEqual         = "<>"
	SqlGreaterThan      = ">"
	SqlGreaterThanEqual = ">="
	SqlLessThan         = "<"
	SqlLessThanEqual    = "<="

	SqlAll = "ALL"
	SqlAny = "ANY"

	SqlLeftSmallBracket  = "("
	SqlRightSmallBracket = ")"

	SqlExpect    = "EXCEPT"
	SqlIntersect = "INTERSECT"

	SqlDistinct = "DISTINCT"
)
View Source
const (
	AliasA = "a"
	AliasB = "b"
	AliasC = "c"
	AliasD = "d"
	AliasE = "e"
	AliasF = "f"
	AliasG = "g"
)
View Source
const (
	DefaultAliasNameCount = "counts"
)

Variables

View Source
var (
	DefaultConfig = Config{
		Scan:                   ScanSliceStruct,
		ScanTag:                DefaultTag,
		DeleteMustUseWhere:     true,
		UpdateMustUseWhere:     true,
		TransactionMaxDuration: time.Second * 5,
		WarnDuration:           time.Millisecond * 200,
	}
)
View Source
var (
	// ErrNoAffectedRows No rows are affected when execute SQL.
	ErrNoAffectedRows = errors.New("database: there are no affected rows")
)

Functions

func ArgString

func ArgString(helper Helper, i interface{}) string

ArgString Convert SQL statement parameters into text strings.

func BasicTypeValue

func BasicTypeValue(value interface{}) interface{}

func BuildCount

func BuildCount(s *Get, countColumns ...string) (prepare string, args []interface{})

BuildCount Build count query. SELECT COUNT(*) AS count FROM ( [WITH xxx] SELECT xxx FROM xxx [INNER JOIN xxx ON xxx] [WHERE xxx] [GROUP BY xxx [HAVING xxx]] ) AS a SELECT COUNT(*) AS count FROM ( query1 UNION [ALL] query2 [UNION [ALL] ...] ) AS a

func BuildGet

func BuildGet(s *Get) (prepare string, args []interface{})

BuildGet Build a complete query. [WITH xxx] SELECT xxx FROM xxx [INNER JOIN xxx ON xxx] [WHERE xxx] [GROUP BY xxx [HAVING xxx]] [ORDER BY xxx] [LIMIT xxx [OFFSET xxx]]

func BuildOrderByLimitOffset

func BuildOrderByLimitOffset(s *Get) (prepare string)

BuildOrderByLimitOffset Build query table of ORDER BY, LIMIT, OFFSET. [ORDER BY xxx] [LIMIT xxx [OFFSET xxx]]

func BuildTable

func BuildTable(s *Get) (prepare string, args []interface{})

BuildTable Build query table (without ORDER BY, LIMIT, OFFSET). [WITH xxx] SELECT xxx FROM xxx [INNER JOIN xxx ON xxx] [WHERE xxx] [GROUP BY xxx [HAVING xxx]]

func BuildUnion

func BuildUnion(withs []*GetWith, unionType string, gets []*Get) (prepare string, args []interface{})

BuildUnion Combines the results of two or more SELECT queries into a single result set. [WITH xxx] /*query1*/( [WITH xxx] SELECT xxx FROM xxx [INNER JOIN xxx ON xxx] [WHERE xxx] [GROUP BY xxx [HAVING xxx]] [ORDER BY xxx] [LIMIT xxx [OFFSET xxx]]) UNION [ALL] /*query2*/( [WITH xxx] SELECT xxx FROM xxx [INNER JOIN xxx ON xxx] [WHERE xxx] [GROUP BY xxx [HAVING xxx]] [ORDER BY xxx] [LIMIT xxx [OFFSET xxx]]) [ORDER BY xxx] [LIMIT xxx [OFFSET xxx]]

func BuildWith

func BuildWith(withs []*GetWith) (prepare string, args []interface{})

BuildWith Build SQL WITH. [WITH a AS ( xxx )[, b AS ( xxx ) ]].

func ConcatString

func ConcatString(sss ...string) string

ConcatString concatenate string.

func EqualAll

func EqualAll(f Filter, column string, subquery *Get)

EqualAll There are few practical application scenarios because all values are required to be equal.

func EqualAny

func EqualAny(f Filter, column string, subquery *Get)

EqualAny Implement the filter condition: column = ANY ( subquery ) .

func EvenSlice2Map

func EvenSlice2Map[K comparable](elems ...K) map[K]K

EvenSlice2Map even slice to map.

func ExpectGet

func ExpectGet(gets ...*Get) (prepare string, args []interface{})

ExpectGet (query1) EXCEPT (query2) EXCEPT (query3)...

func GetCount

func GetCount(get *Get, countColumns ...string) (count int64, err error)

GetCount execute the built SQL statement and scan query result for count.

func GetCountGet

func GetCountGet(get *Get, result interface{}, countColumn ...string) (int64, error)

GetCountGet execute the built SQL statement and scan query result, count + get.

func GetCountQuery

func GetCountQuery(get *Get, query func(rows *sql.Rows) (err error), countColumn ...string) (int64, error)

GetCountQuery execute the built SQL statement and scan query result, count + query.

func GetExists

func GetExists(get *Get) (exists bool, err error)

GetExists Determine whether the query result exists.

func GetGet

func GetGet(get *Get, result interface{}) error

GetGet execute the built SQL statement and scan query result.

func GetQuery

func GetQuery(get *Get, query func(rows *sql.Rows) (err error)) error

GetQuery execute the built SQL statement and scan query result.

func GetScanAll

func GetScanAll(get *Get, fc func(rows *sql.Rows) error) error

GetScanAll execute the built SQL statement and scan all from the query results.

func GetScanOne

func GetScanOne(get *Get, dest ...interface{}) error

GetScanOne execute the built SQL statement and scan at most once from the query results.

func GetViewMap

func GetViewMap(get *Get) (result []map[string]interface{}, err error)

GetViewMap execute the built SQL statement and scan all from the query results.

func GreaterThanAll

func GreaterThanAll(f Filter, column string, subquery *Get)

GreaterThanAll Implement the filter condition: column > ALL ( subquery ) .

func GreaterThanAny

func GreaterThanAny(f Filter, column string, subquery *Get)

GreaterThanAny Implement the filter condition: column > ANY ( subquery ) .

func GreaterThanEqualAll

func GreaterThanEqualAll(f Filter, column string, subquery *Get)

GreaterThanEqualAll Implement the filter condition: column >= ALL ( subquery ) .

func GreaterThanEqualAny

func GreaterThanEqualAny(f Filter, column string, subquery *Get)

GreaterThanEqualAny Implement the filter condition: column >= ANY ( subquery ) .

func IntersectGet

func IntersectGet(gets ...*Get) (prepare string, args []interface{})

IntersectGet (query1) INTERSECT (query2) INTERSECT (query3)...

func LastNotEmptyString

func LastNotEmptyString(sss []string) string

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

func LessThanAll

func LessThanAll(f Filter, column string, subquery *Get)

LessThanAll Implement the filter condition: column < ALL ( subquery ) .

func LessThanAny

func LessThanAny(f Filter, column string, subquery *Get)

LessThanAny Implement the filter condition: column < ANY ( subquery ) .

func LessThanEqualAll

func LessThanEqualAll(f Filter, column string, subquery *Get)

LessThanEqualAll Implement the filter condition: column <= ALL ( subquery ) .

func LessThanEqualAny

func LessThanEqualAny(f Filter, column string, subquery *Get)

LessThanEqualAny Implement the filter condition: column <= ANY ( subquery ) .

func MergeMap

func MergeMap[K comparable, V interface{}](elems ...map[K]V) map[K]V

MergeMap merge multiple maps.

func MergeSlice

func MergeSlice[V interface{}](elems ...[]V) []V

MergeSlice merge multiple slices.

func MustAffectedRows

func MustAffectedRows(affectedRows int64, err error) error

MustAffectedRows at least one row is affected.

func NotEqualAll

func NotEqualAll(f Filter, column string, subquery *Get)

NotEqualAll Implement the filter condition: column <> ALL ( subquery ) .

func NotEqualAny

func NotEqualAny(f Filter, column string, subquery *Get)

NotEqualAny Implement the filter condition: column <> ANY ( subquery ) .

func PrepareString

func PrepareString(helper Helper, prepare string, args []interface{}) string

PrepareString Merge executed SQL statements and parameters.

func PutCase

func PutCase(i *Case)

PutCase put *Case in the pool.

func PutFilter

func PutFilter(f Filter)

func RemoveDuplicate

func RemoveDuplicate(dynamic ...interface{}) (result []interface{})

RemoveDuplicate remove duplicate element.

func RemoveDuplicates

func RemoveDuplicates[T comparable](dynamic ...T) (result []T)

RemoveDuplicates remove duplicate element.

func RemoveSliceMemberByIndex

func RemoveSliceMemberByIndex[T interface{}](indexList []int, elementList []T) []T

RemoveSliceMemberByIndex delete slice member by index.

func ScanAll

func ScanAll(rows *sql.Rows, fc func(rows *sql.Rows) error) (err error)

ScanAll Iteratively scan from query results.

func ScanOne

func ScanOne(rows *sql.Rows, dest ...interface{}) error

ScanOne Scan at most once from the query results.

func ScanSliceStruct

func ScanSliceStruct(rows *sql.Rows, result interface{}, tag string) error

ScanSliceStruct Scan the query result set into the receiving object the receiving object type is *[]AnyStruct or *[]*AnyStruct.

func ScanViewMap

func ScanViewMap(rows *sql.Rows) ([]map[string]interface{}, error)

ScanViewMap Scan query result to []map[string]interface{}, view query result.

func Slice2MapNewKey

func Slice2MapNewKey[K comparable](elems []K, createKey func(v K) K) map[K]K

Slice2MapNewKey make map by slice, create key.

func Slice2MapNewVal

func Slice2MapNewVal[K comparable, V interface{}](elems []K, createValue func(v K) V) map[K]V

Slice2MapNewVal make map by slice, create value.

func SliceIter

func SliceIter[V interface{}](iter func(v V) V, elems []V) []V

SliceIter slice iteration.

func SliceMatchMap

func SliceMatchMap[K comparable, X interface{}, Y interface{}](kx map[K]X, handle func(x X, y Y), key func(y Y) K, elems []Y)

SliceMatchMap use the `key` value of each element in `elems` to match in the map, and call `handle` if the match is successful.

func SqlAlias

func SqlAlias(name string, alias string) string

SqlAlias sql alias name.

func SqlPrefix

func SqlPrefix(prefix string, name string) string

SqlPrefix sql prefix name.

func StructInsert

func StructInsert(object interface{}, tag string, except []string, allow []string) (fields []string, values [][]interface{})

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 interface{}, tag string, except ...string) (fields []string, values []interface{})

StructModify object should be one of struct{}, *struct{} get the fields and values that need to be modified.

func StructObtain

func StructObtain(object interface{}, tag string, except ...string) (fields []string, values []interface{})

StructObtain object should be one of struct{}, *struct{} for get all fields and values.

func StructUpdate

func StructUpdate(origin interface{}, latest interface{}, tag string, except ...string) (fields []string, values []interface{})

StructUpdate compare origin and latest for update.

Types

type Add

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

Add for INSERT.

func NewAdd

func NewAdd(way *Way) *Add

NewAdd for INSERT.

func (*Add) Add

func (s *Add) Add() (int64, error)

Add execute the built SQL statement.

func (*Add) Comment

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

Comment set comment.

func (*Add) Context

func (s *Add) Context(ctx context.Context) *Add

Context set context.

func (*Add) Create

func (s *Add) Create(create interface{}) *Add

Create value of create should be one of struct{}, *struct{}, map[string]interface{}, []struct, []*struct{}, *[]struct{}, *[]*struct{}.

func (*Add) Default

func (s *Add) Default(fc func(o *Add)) *Add

Default Add field = value .

func (*Add) FieldValue

func (s *Add) FieldValue(field string, value interface{}) *Add

FieldValue append field-value for insert one or more rows.

func (*Add) FieldsValues

func (s *Add) FieldsValues(fields []string, values [][]interface{}) *Add

FieldsValues set fields and values.

func (*Add) Permit

func (s *Add) Permit(permit ...string) *Add

Permit Set a list of fields that can only be inserted.

func (*Add) ReturnId added in v2.0.7

func (s *Add) ReturnId(getReturningColumn func() string, getId func(ctx context.Context, stmt *Stmt, args []interface{}) (id int64, err error)) (id int64, err error)

ReturnId execute the built SQL statement, returning auto-increment field value.

func (*Add) SQL

func (s *Add) SQL() (prepare string, args []interface{})

SQL build SQL statement.

func (*Add) Table

func (s *Add) Table(table string) *Add

Table set table name.

func (*Add) ValuesSubQuery

func (s *Add) ValuesSubQuery(prepare string, args []interface{}) *Add

ValuesSubQuery values is a query SQL statement.

func (*Add) ValuesSubQueryGet

func (s *Add) ValuesSubQueryGet(get *Get, fields ...string) *Add

ValuesSubQueryGet values is a query SQL statement.

func (*Add) Way

func (s *Add) Way() *Way

Way get current *Way.

type AdjustColumn added in v2.0.6

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

func NewAdjustColumn added in v2.0.6

func NewAdjustColumn(way *Way, aliases ...string) *AdjustColumn

func (*AdjustColumn) Adjust added in v2.0.6

func (s *AdjustColumn) Adjust(adjust func(column string) string, columns ...string) []string

Adjust Batch adjust columns.

func (*AdjustColumn) Alias added in v2.0.6

func (s *AdjustColumn) Alias() string

Alias Get the alias name value.

func (*AdjustColumn) Avg added in v2.0.6

func (s *AdjustColumn) Avg(column string, aliases ...string) string

Avg AVG(column[, alias])

func (*AdjustColumn) Column added in v2.0.6

func (s *AdjustColumn) Column(column string, aliases ...string) string

Column Add table name prefix to single column name, allowing column alias to be set.

func (*AdjustColumn) ColumnAll added in v2.0.6

func (s *AdjustColumn) ColumnAll(columns ...string) []string

ColumnAll Add table name prefix to column names in batches.

func (*AdjustColumn) Count added in v2.0.6

func (s *AdjustColumn) 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 (*AdjustColumn) IfNull added in v2.0.6

func (s *AdjustColumn) IfNull(column string, defaultValue string, aliases ...string) string

IfNull If the value is NULL, set the default value.

func (*AdjustColumn) IfNullAvg added in v2.0.6

func (s *AdjustColumn) IfNullAvg(column string, aliases ...string) string

IfNullAvg IF_NULL(AVG(column),0)[ AS column_name]

func (*AdjustColumn) IfNullMax added in v2.0.6

func (s *AdjustColumn) IfNullMax(column string, aliases ...string) string

IfNullMax IF_NULL(MAX(column),0)[ AS column_name]

func (*AdjustColumn) IfNullMin added in v2.0.6

func (s *AdjustColumn) IfNullMin(column string, aliases ...string) string

IfNullMin IF_NULL(MIN(column),0)[ AS column_name]

func (*AdjustColumn) IfNullSum added in v2.0.6

func (s *AdjustColumn) IfNullSum(column string, aliases ...string) string

IfNullSum IF_NULL(SUM(column),0)[ AS column_name]

func (*AdjustColumn) Max added in v2.0.6

func (s *AdjustColumn) Max(column string, aliases ...string) string

Max MAX(column[, alias])

func (*AdjustColumn) Min added in v2.0.6

func (s *AdjustColumn) Min(column string, aliases ...string) string

Min MIN(column[, alias])

func (*AdjustColumn) SetAlias added in v2.0.6

func (s *AdjustColumn) SetAlias(alias string) *AdjustColumn

SetAlias Set the alias name value.

func (*AdjustColumn) Sum added in v2.0.6

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

Sum SUM(column[, alias])

type Caller

type Caller interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)

	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)

	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}

Caller The implementation object is usually one of *sql.Conn, *sql.DB, *sql.Tx.

type Case

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

Case Implementing SQL CASE.

func GetCase

func GetCase() *Case

GetCase get *Case from pool.

func (*Case) Alias

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

Alias AS alias .

func (*Case) Else

func (s *Case) Else(elseExpr string, elseArgs ...interface{}) *Case

Else Expressions of else.

func (*Case) If

func (s *Case) If(when func(f Filter), then string, thenArgs ...interface{}) *Case

If CASE WHEN condition THEN expressions.

func (*Case) SQL

func (s *Case) SQL() (prepare string, args []interface{})

SQL Make SQL expr: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE else_result END [AS alias_name] .

type Config

type Config struct {
	// Scan Scan data into structure.
	Scan func(rows *sql.Rows, result interface{}, tag string) error

	// ScanTag Scan data to tag mapping on structure.
	ScanTag string

	// Helper Helpers for handling different types of databases.
	Helper Helper

	// DeleteMustUseWhere Deletion of data must be filtered using conditions.
	DeleteMustUseWhere bool

	// UpdateMustUseWhere Updated data must be filtered using conditions.
	UpdateMustUseWhere bool

	// TransactionOptions Start transaction.
	TransactionOptions *sql.TxOptions

	// TransactionMaxDuration Maximum transaction execution time.
	TransactionMaxDuration time.Duration

	// WarnDuration SQL execution time warning threshold.
	WarnDuration time.Duration
}

Config Configure of Way.

type Del

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

Del for DELETE.

func NewDel

func NewDel(way *Way) *Del

NewDel for DELETE.

func (*Del) Comment

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

Comment set comment.

func (*Del) Context

func (s *Del) Context(ctx context.Context) *Del

Context set context.

func (*Del) Del

func (s *Del) Del() (int64, error)

Del execute the built SQL statement.

func (*Del) SQL

func (s *Del) SQL() (prepare string, args []interface{})

SQL build SQL statement.

func (*Del) Table

func (s *Del) Table(table string) *Del

Table set table name.

func (*Del) Way

func (s *Del) Way() *Way

Way get current *Way.

func (*Del) Where

func (s *Del) Where(where Filter) *Del

Where set where.

type Filter

type Filter interface {
	// SQL Generate conditional filtering SQL statements and their parameters.
	SQL() (string, []interface{})

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

	// 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(prepare string, args ...interface{}) Filter

	// Or Use logical operator `OR` to combine custom conditions.
	Or(prepare string, args ...interface{}) 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(fs ...Filter) Filter

	// New Create a new conditional filter object based on a set of conditional filter objects.
	New(fs ...Filter) Filter

	// GreaterThan Implement conditional filtering: column > value .
	GreaterThan(column string, value interface{}) Filter

	// GreaterThanEqual Implement conditional filtering: column >= value .
	GreaterThanEqual(column string, value interface{}) Filter

	// LessThan Implement conditional filtering: column < value .
	LessThan(column string, value interface{}) Filter

	// LessThanEqual Implement conditional filtering: column <= value .
	LessThanEqual(column string, value interface{}) Filter

	// Equal Implement conditional filtering: column = value .
	Equal(column string, value interface{}) Filter

	// Between Implement conditional filtering: column BETWEEN value1 AND value2 .
	Between(column string, start interface{}, end interface{}) Filter

	// In Implement conditional filtering: column IN ( value1, value2, value3... ) .
	In(column string, values ...interface{}) Filter

	// InSql Implement conditional filtering: column IN ( subquery ) .
	InSql(column string, prepare string, args ...interface{}) Filter

	// InCols Implement conditional filtering: ( column1, column2, column3... ) IN ( ( value1, value2, value3... ), ( value21, value22, value23... )... ) .
	InCols(columns []string, values ...[]interface{}) Filter

	// InColsSql Implement conditional filtering: ( column1, column2, column3... ) IN ( subquery ) .
	InColsSql(columns []string, prepare string, args ...interface{}) Filter

	// Exists Implement conditional filtering: EXISTS ( subquery ) .
	Exists(prepare string, args ...interface{}) Filter

	// Like Implement conditional filtering: column LIKE value .
	Like(column string, value interface{}) Filter

	// IsNull Implement conditional filtering: column IS NULL .
	IsNull(column string) Filter

	// InGet Implement conditional filtering: column IN ( subquery ) .
	InGet(column string, get *Get) Filter

	// InColsGet Implement conditional filtering: ( column1, column2, column3... ) IN ( subquery ) .
	InColsGet(columns []string, get *Get) Filter

	// ExistsGet Implement conditional filtering: EXISTS ( subquery ) .
	ExistsGet(get *Get) Filter

	// NotEqual Implement conditional filtering: column <> value .
	NotEqual(column string, value interface{}) Filter

	// NotBetween Implement conditional filtering: column NOT BETWEEN value1 AND value2 .
	NotBetween(column string, start interface{}, end interface{}) Filter

	// NotIn Implement conditional filtering: column NOT IN ( value1, value2, value3... ) .
	NotIn(column string, values ...interface{}) Filter

	// NotInCols Implement conditional filtering: ( column1, column2, column3... ) NOT IN ( ( value1, value2, value3... ), ( value21, value22, value23... )... ) .
	NotInCols(columns []string, values ...[]interface{}) Filter

	// NotLike Implement conditional filtering: column NOT LIKE value .
	NotLike(column string, value interface{}) Filter

	// IsNotNull Implement conditional filtering: column IS NOT NULL .
	IsNotNull(column string) Filter
}

Filter Implement SQL statement condition filtering.

func F

func F() Filter

F New a Filter.

func GetFilter

func GetFilter() Filter

type Get

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

Get for SELECT.

func NewGet

func NewGet(way *Way) *Get

NewGet for SELECT.

func (*Get) AddColumn

func (s *Get) AddColumn(column ...string) *Get

AddColumn append the columns list of query.

func (*Get) AddColumnCase

func (s *Get) AddColumnCase(caseList ...func(c *Case)) *Get

AddColumnCase append the columns list of query.

func (*Get) Alias

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

Alias for table alias name, don't forget to call the current method when the table is a SQL statement.

func (*Get) Asc

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

Asc set order by column ASC.

func (*Get) Column

func (s *Get) Column(column ...string) *Get

Column set the columns list of query.

func (*Get) Comment

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

Comment set comment.

func (*Get) Context

func (s *Get) Context(ctx context.Context) *Get

Context set context.

func (*Get) Count

func (s *Get) Count(column ...string) (int64, error)

Count execute the built SQL statement and scan query result for count.

func (*Get) CountGet

func (s *Get) CountGet(result interface{}, countColumn ...string) (int64, error)

CountGet execute the built SQL statement and scan query result, count + get.

func (*Get) CountQuery

func (s *Get) CountQuery(query func(rows *sql.Rows) (err error), countColumn ...string) (int64, error)

CountQuery execute the built SQL statement and scan query result, count + query.

func (*Get) CrossJoin

func (s *Get) CrossJoin(fs ...func(j *GetJoin)) *Get

CrossJoin for cross join.

func (*Get) Desc

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

Desc set order by column Desc.

func (*Get) Distinct

func (s *Get) Distinct(distinct bool) *Get

Distinct Remove duplicate records: one field value or a combination of multiple fields.

func (*Get) Exists

func (s *Get) Exists() (bool, error)

Exists Determine whether the query result exists.

func (*Get) FullJoin

func (s *Get) FullJoin(fs ...func(j *GetJoin)) *Get

FullJoin for full join.

func (*Get) Get

func (s *Get) Get(result interface{}) error

Get execute the built SQL statement and scan query result.

func (*Get) Group

func (s *Get) Group(group ...string) *Get

Group set group columns.

func (*Get) Having

func (s *Get) Having(having Filter) *Get

Having set filter of group result.

func (*Get) InnerJoin

func (s *Get) InnerJoin(fs ...func(j *GetJoin)) *Get

InnerJoin for inner join.

func (*Get) LeftJoin

func (s *Get) LeftJoin(fs ...func(j *GetJoin)) *Get

LeftJoin for left join.

func (*Get) Limit

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

Limit set limit.

func (*Get) Limiter

func (s *Get) Limiter(limiter Limiter) *Get

Limiter set limit and offset at the same time.

func (*Get) Offset

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

Offset set offset.

func (*Get) Order

func (s *Get) Order(order string, orderMap ...map[string]string) *Get

Order set the column sorting list in batches through regular expressions according to the request parameter value.

func (*Get) Query

func (s *Get) Query(query func(rows *sql.Rows) (err error)) error

Query execute the built SQL statement and scan query result.

func (*Get) Raw

func (s *Get) Raw(prepare string, args []interface{}) *Get

Raw Directly set the native SQL statement and the corresponding parameter list.

func (*Get) RightJoin

func (s *Get) RightJoin(fs ...func(j *GetJoin)) *Get

RightJoin for right join.

func (*Get) SQL

func (s *Get) SQL() (prepare string, args []interface{})

SQL build SQL statement.

func (*Get) SQLCount

func (s *Get) SQLCount(columns ...string) (string, []interface{})

SQLCount build SQL statement for count.

func (*Get) ScanAll

func (s *Get) ScanAll(fc func(rows *sql.Rows) error) error

ScanAll execute the built SQL statement and scan all from the query results.

func (*Get) ScanOne

func (s *Get) ScanOne(dest ...interface{}) error

ScanOne execute the built SQL statement and scan at most once from the query results.

func (*Get) SubQuery

func (s *Get) SubQuery(prepare string, args []interface{}) *Get

SubQuery table is a query SQL statement.

func (*Get) SubQueryGet

func (s *Get) SubQueryGet(get *Get, alias ...string) *Get

SubQueryGet table is a query SQL statement.

func (*Get) Table

func (s *Get) Table(table string, alias ...string) *Get

Table set table name.

func (*Get) Union

func (s *Get) Union(unions ...*Get) *Get

Union for union(After calling the current method, only WITH, ORDER BY, LIMIT, and OFFSET are valid for the current query attributes.).

func (*Get) UnionAll

func (s *Get) UnionAll(unions ...*Get) *Get

UnionAll for union all(After calling the current method, only WITH, ORDER BY, LIMIT, and OFFSET are valid for the current query attributes.).

func (*Get) ViewMap

func (s *Get) ViewMap() ([]map[string]interface{}, error)

ViewMap execute the built SQL statement and scan all from the query results.

func (*Get) Way

func (s *Get) Way() *Way

Way get current *Way.

func (*Get) Where

func (s *Get) Where(where Filter) *Get

Where set where.

func (*Get) With

func (s *Get) With(with ...*GetWith) *Get

With for with query.

type GetJoin

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

GetJoin join SQL statement.

func (*GetJoin) Alias

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

Alias for table alias name, don't forget to call the current method when the table is a SQL statement.

func (*GetJoin) On

func (s *GetJoin) On(on string) *GetJoin

On join query condition.

func (*GetJoin) OnEqual

func (s *GetJoin) OnEqual(fields ...string) *GetJoin

OnEqual join query condition, support multiple fields.

func (*GetJoin) SQL

func (s *GetJoin) SQL() (prepare string, args []interface{})

SQL build SQL statement.

func (*GetJoin) SubQuery

func (s *GetJoin) SubQuery(prepare string, args []interface{}) *GetJoin

SubQuery table is a query SQL statement.

func (*GetJoin) SubQueryGet

func (s *GetJoin) SubQueryGet(get *Get, alias ...string) *GetJoin

SubQueryGet table is a query SQL statement.

func (*GetJoin) Table

func (s *GetJoin) Table(table string) *GetJoin

Table set table name.

func (*GetJoin) Using

func (s *GetJoin) Using(fields ...string) *GetJoin

Using join query condition.

type GetWith

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

GetWith CTE: Common Table Expression.

func NewWith

func NewWith() *GetWith

func (*GetWith) Recursive

func (s *GetWith) Recursive(recursive bool) *GetWith

func (*GetWith) SQL

func (s *GetWith) SQL() (prepare string, args []interface{})

func (*GetWith) With

func (s *GetWith) With(alias string, prepare string, args []interface{}) *GetWith

func (*GetWith) WithGet

func (s *GetWith) WithGet(alias string, get *Get) *GetWith

type Helper

type Helper interface {
	// DriverName Get the driver name.
	DriverName() []byte

	// DataSourceName Get the data source name.
	DataSourceName() []byte

	// SetIdentifier Custom Identifier.
	SetIdentifier(identifier Identifier) Helper

	Identifier

	// SetPrepare Custom method.
	SetPrepare(prepare func(prepare string) string) Helper

	// Prepare Before executing preprocessing, adjust the preprocessing SQL format.
	Prepare(prepare string) string

	// SetIfNull Custom method.
	SetIfNull(ifNull func(columnName string, columnDefaultValue string) string) Helper

	// IfNull Set a default value when the query field value is NULL.
	IfNull(columnName string, columnDefaultValue string) string

	// SetBinaryDataToHexString Custom method.
	SetBinaryDataToHexString(binaryDataToHexString func(binaryData []byte) string) Helper

	// BinaryDataToHexString Convert binary data to hexadecimal string.
	BinaryDataToHexString(binaryData []byte) string
}

type Identifier added in v2.0.7

type Identifier interface {
	Identify() string
	AddIdentify(keys []string) []string
	DelIdentify(keys []string) []string
}

func NewIdentifier added in v2.0.7

func NewIdentifier(identify string) Identifier

type Limiter

type Limiter interface {
	GetLimit() int64
	GetOffset() int64
}

Limiter limit and offset.

type LogSql added in v2.0.4

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

LogSql Record executed prepare args.

func (*LogSql) Write added in v2.0.4

func (s *LogSql) Write()

type LogSqlArgs added in v2.0.4

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

LogSqlArgs Record executed args of prepare.

type Mod

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

Mod for UPDATE.

func NewMod

func NewMod(way *Way) *Mod

NewMod for UPDATE.

func (*Mod) Comment

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

Comment set comment.

func (*Mod) Context

func (s *Mod) Context(ctx context.Context) *Mod

Context set context.

func (*Mod) Decr

func (s *Mod) Decr(field string, value interface{}) *Mod

Decr SET field = field - value.

func (*Mod) Default

func (s *Mod) Default(fc func(o *Mod)) *Mod

Default SET field = expr .

func (*Mod) Expr

func (s *Mod) Expr(field string, expr string, args ...interface{}) *Mod

Expr update field using custom expr.

func (*Mod) FieldsValues

func (s *Mod) FieldsValues(fields []string, values []interface{}) *Mod

FieldsValues SET field = value by slice, require len(fields) == len(values).

func (*Mod) Incr

func (s *Mod) Incr(field string, value interface{}) *Mod

Incr SET field = field + value.

func (*Mod) Mod

func (s *Mod) Mod() (int64, error)

Mod execute the built SQL statement.

func (*Mod) Modify

func (s *Mod) Modify(modify interface{}) *Mod

Modify value of modify should be one of struct{}, *struct{}, map[string]interface{}.

func (*Mod) Permit

func (s *Mod) Permit(permit ...string) *Mod

Permit Sets a list of fields that can only be updated.

func (*Mod) SQL

func (s *Mod) SQL() (prepare string, args []interface{})

SQL build SQL statement.

func (*Mod) Set

func (s *Mod) Set(field string, value interface{}) *Mod

Set field = value.

func (*Mod) SetCase

func (s *Mod) SetCase(field string, value func(c *Case)) *Mod

SetCase SET salary = CASE WHEN department_id = 1 THEN salary * 1.1 WHEN department_id = 2 THEN salary * 1.05 ELSE salary.

func (*Mod) SetSQL

func (s *Mod) SetSQL() (prepare string, args []interface{})

SetSQL prepare args of set.

func (*Mod) Table

func (s *Mod) Table(table string) *Mod

Table set table name.

func (*Mod) Update

func (s *Mod) Update(originObject interface{}, latestObject interface{}, except ...string) *Mod

Update for compare origin and latest to automatically calculate need to update fields.

func (*Mod) Way

func (s *Mod) Way() *Way

Way get current *Way.

func (*Mod) Where

func (s *Mod) Where(where Filter) *Mod

Where set where.

type MysqlHelper

type MysqlHelper struct {
	Identifier
	// contains filtered or unexported fields
}

MysqlHelper helper for mysql.

func NewMysqlHelper

func NewMysqlHelper() *MysqlHelper

func (*MysqlHelper) BinaryDataToHexString added in v2.0.5

func (s *MysqlHelper) BinaryDataToHexString(binaryData []byte) string

func (*MysqlHelper) DataSourceName added in v2.0.1

func (s *MysqlHelper) DataSourceName() []byte

func (*MysqlHelper) DriverName added in v2.0.1

func (s *MysqlHelper) DriverName() []byte

func (*MysqlHelper) IfNull

func (s *MysqlHelper) IfNull(columnName string, columnDefaultValue string) string

func (*MysqlHelper) Prepare

func (s *MysqlHelper) Prepare(prepare string) string

func (*MysqlHelper) SetBinaryDataToHexString added in v2.0.7

func (s *MysqlHelper) SetBinaryDataToHexString(binaryDataToHexString func(binaryData []byte) string) Helper

func (*MysqlHelper) SetIdentifier added in v2.0.7

func (s *MysqlHelper) SetIdentifier(identifier Identifier) Helper

func (*MysqlHelper) SetIfNull added in v2.0.7

func (s *MysqlHelper) SetIfNull(ifNull func(columnName string, columnDefaultValue string) string) Helper

func (*MysqlHelper) SetPrepare added in v2.0.7

func (s *MysqlHelper) SetPrepare(prepare func(prepare string) string) Helper

type PostgresHelper

type PostgresHelper struct {
	Identifier
	// contains filtered or unexported fields
}

PostgresHelper helper for postgresql.

func NewPostgresHelper

func NewPostgresHelper() *PostgresHelper

func (*PostgresHelper) BinaryDataToHexString added in v2.0.5

func (s *PostgresHelper) BinaryDataToHexString(binaryData []byte) string

func (*PostgresHelper) DataSourceName added in v2.0.1

func (s *PostgresHelper) DataSourceName() []byte

func (*PostgresHelper) DriverName added in v2.0.1

func (s *PostgresHelper) DriverName() []byte

func (*PostgresHelper) IfNull

func (s *PostgresHelper) IfNull(columnName string, columnDefaultValue string) string

func (*PostgresHelper) Prepare

func (s *PostgresHelper) Prepare(prepare string) string

func (*PostgresHelper) SetBinaryDataToHexString added in v2.0.7

func (s *PostgresHelper) SetBinaryDataToHexString(binaryDataToHexString func(binaryData []byte) string) Helper

func (*PostgresHelper) SetIdentifier added in v2.0.7

func (s *PostgresHelper) SetIdentifier(identifier Identifier) Helper

func (*PostgresHelper) SetIfNull added in v2.0.7

func (s *PostgresHelper) SetIfNull(ifNull func(columnName string, columnDefaultValue string) string) Helper

func (*PostgresHelper) SetPrepare added in v2.0.7

func (s *PostgresHelper) SetPrepare(prepare func(prepare string) string) Helper

type PrepareArgs

type PrepareArgs struct {
	Prepare string

	Args []interface{}
}

PrepareArgs Statements to be executed and corresponding parameter list.

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.

func NewReader

func NewReader(choose func(n int) int, reads []*Way) Reader

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

type Sqlite3Helper added in v2.0.1

type Sqlite3Helper struct {
	Identifier
	// contains filtered or unexported fields
}

Sqlite3Helper helper for sqlite3.

func NewSqlite3Helper added in v2.0.1

func NewSqlite3Helper() *Sqlite3Helper

func (*Sqlite3Helper) BinaryDataToHexString added in v2.0.5

func (s *Sqlite3Helper) BinaryDataToHexString(binaryData []byte) string

func (*Sqlite3Helper) DataSourceName added in v2.0.1

func (s *Sqlite3Helper) DataSourceName() []byte

func (*Sqlite3Helper) DriverName added in v2.0.1

func (s *Sqlite3Helper) DriverName() []byte

func (*Sqlite3Helper) IfNull added in v2.0.1

func (s *Sqlite3Helper) IfNull(columnName string, columnDefaultValue string) string

func (*Sqlite3Helper) Prepare added in v2.0.1

func (s *Sqlite3Helper) Prepare(prepare string) string

func (*Sqlite3Helper) SetBinaryDataToHexString added in v2.0.7

func (s *Sqlite3Helper) SetBinaryDataToHexString(binaryDataToHexString func(binaryData []byte) string) Helper

func (*Sqlite3Helper) SetIdentifier added in v2.0.7

func (s *Sqlite3Helper) SetIdentifier(identifier Identifier) Helper

func (*Sqlite3Helper) SetIfNull added in v2.0.7

func (s *Sqlite3Helper) SetIfNull(ifNull func(columnName string, columnDefaultValue string) string) Helper

func (*Sqlite3Helper) SetPrepare added in v2.0.7

func (s *Sqlite3Helper) SetPrepare(prepare func(prepare string) string) Helper

type Stmt

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

Stmt Prepare handle.

func (*Stmt) Close

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

Close -> Close prepare handle.

func (*Stmt) Exec

func (s *Stmt) Exec(args ...interface{}) (int64, error)

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

func (*Stmt) ExecContext

func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (int64, error)

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

func (*Stmt) Execute

func (s *Stmt) Execute(args ...interface{}) (sql.Result, error)

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

func (*Stmt) ExecuteContext

func (s *Stmt) ExecuteContext(ctx context.Context, args ...interface{}) (sql.Result, error)

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

func (*Stmt) Query

func (s *Stmt) Query(query func(rows *sql.Rows) error, args ...interface{}) error

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

func (*Stmt) QueryContext

func (s *Stmt) QueryContext(ctx context.Context, query func(rows *sql.Rows) error, args ...interface{}) error

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

func (*Stmt) QueryRow

func (s *Stmt) QueryRow(query func(rows *sql.Row) error, args ...interface{}) (err error)

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

func (*Stmt) QueryRowContext

func (s *Stmt) QueryRowContext(ctx context.Context, query func(rows *sql.Row) error, args ...interface{}) error

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

func (*Stmt) TakeAll

func (s *Stmt) TakeAll(result interface{}, args ...interface{}) error

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

func (*Stmt) TakeAllContext

func (s *Stmt) TakeAllContext(ctx context.Context, result interface{}, args ...interface{}) error

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

type SubQuery

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

func NewSubQuery

func NewSubQuery(prepare string, args []interface{}) *SubQuery

func (*SubQuery) SQL

func (s *SubQuery) SQL() (prepare string, args []interface{})

type Way

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

Way Quick insert, delete, update, select helper.

func NewWay

func NewWay(driverName string, dataSourceName string) (*Way, error)

func (*Way) Add

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

Add -> Create an instance that executes the INSERT sql statement.

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

func (s *Way) Commit() error

Commit -> Transaction commit.

func (*Way) DB

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

func (*Way) Del

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

Del -> Create an instance that executes the DELETE sql statement.

func (*Way) Exec

func (s *Way) Exec(prepare string, args ...interface{}) (int64, error)

Exec -> Execute the execute sql statement.

func (*Way) ExecContext

func (s *Way) ExecContext(ctx context.Context, prepare string, args ...interface{}) (int64, error)

ExecContext -> Execute the execute sql statement.

func (*Way) Execute

func (s *Way) Execute(prepare string, args ...interface{}) (sql.Result, error)

Execute -> Execute the execute sql statement.

func (*Way) ExecuteContext

func (s *Way) ExecuteContext(ctx context.Context, prepare string, args ...interface{}) (sql.Result, error)

ExecuteContext -> Execute the execute sql statement.

func (*Way) F

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

F -> Quickly initialize a filter.

func (*Way) Get

func (s *Way) Get(table ...string) *Get

Get -> Create an instance that executes the SELECT sql statement.

func (*Way) GetConfig added in v2.0.1

func (s *Way) GetConfig() *Config

func (*Way) GetLogger added in v2.0.1

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

func (*Way) GetReader added in v2.0.1

func (s *Way) GetReader() Reader

func (*Way) Getter

func (s *Way) Getter(caller Caller, query func(rows *sql.Rows) error, prepare string, args ...interface{}) error

Getter -> Execute the query sql statement with args, no prepared is used.

func (*Way) GetterContext

func (s *Way) GetterContext(ctx context.Context, caller Caller, query func(rows *sql.Rows) error, prepare string, args ...interface{}) (err error)

GetterContext -> Execute the query sql statement with args, no prepared is used.

func (*Way) IsRead

func (s *Way) IsRead() bool

IsRead -> Is an object for read?

func (*Way) LogSql added in v2.0.4

func (s *Way) LogSql(prepare string, args []interface{}) *LogSql

func (*Way) Mod

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

Mod -> Create an instance that executes the UPDATE sql statement.

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(prepare string, caller ...Caller) (*Stmt, error)

Prepare -> Prepare sql statement, don't forget to call *Stmt.Close().

func (*Way) PrepareContext

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

PrepareContext -> Prepare sql statement, don't forget to call *Stmt.Close().

func (*Way) Query

func (s *Way) Query(query func(rows *sql.Rows) error, prepare string, args ...interface{}) error

Query -> Execute the query sql statement.

func (*Way) QueryContext

func (s *Way) QueryContext(ctx context.Context, query func(rows *sql.Rows) error, prepare string, args ...interface{}) error

QueryContext -> Execute the query sql statement.

func (*Way) QueryRow

func (s *Way) QueryRow(query func(row *sql.Row) error, prepare string, args ...interface{}) error

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

func (*Way) QueryRowContext

func (s *Way) QueryRowContext(ctx context.Context, query func(row *sql.Row) error, prepare string, args ...interface{}) error

QueryRowContext -> Execute sql statement and return a row data, usually INSERT, UPDATE, DELETE.

func (*Way) Read

func (s *Way) Read() *Way

func (*Way) Rollback

func (s *Way) Rollback() error

Rollback -> Transaction rollback.

func (*Way) ScanAll

func (s *Way) ScanAll(rows *sql.Rows, fc func(rows *sql.Rows) error) error

ScanAll -> Iteratively scan from query results.

func (*Way) ScanOne

func (s *Way) ScanOne(rows *sql.Rows, dest ...interface{}) error

ScanOne -> Scan at most once from the query results.

func (*Way) SetConfig

func (s *Way) SetConfig(cfg Config) *Way

func (*Way) SetLogger

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

func (*Way) SetReader

func (s *Way) SetReader(reader Reader) *Way

func (*Way) Setter

func (s *Way) Setter(caller Caller, prepare string, args ...interface{}) (int64, error)

Setter -> Execute the execute sql statement with args, no prepared is used.

func (*Way) SetterContext

func (s *Way) SetterContext(ctx context.Context, caller Caller, prepare string, args ...interface{}) (int64, error)

SetterContext -> Execute the execute sql statement with args, no prepared is used.

func (*Way) T added in v2.0.6

func (s *Way) T() *AdjustColumn

T Table empty alias

func (*Way) TA added in v2.0.6

func (s *Way) TA() *AdjustColumn

TA Table alias `a`

func (*Way) TB added in v2.0.6

func (s *Way) TB() *AdjustColumn

TB Table alias `b`

func (*Way) TC added in v2.0.6

func (s *Way) TC() *AdjustColumn

TC Table alias `c`

func (*Way) TD added in v2.0.6

func (s *Way) TD() *AdjustColumn

TD Table alias `d`

func (*Way) TE added in v2.0.6

func (s *Way) TE() *AdjustColumn

TE Table alias `e`

func (*Way) TF added in v2.0.6

func (s *Way) TF() *AdjustColumn

TF Table alias `f`

func (*Way) TG added in v2.0.6

func (s *Way) TG() *AdjustColumn

TG Table alias `g`

func (*Way) TakeAll

func (s *Way) TakeAll(result interface{}, prepare string, args ...interface{}) error

TakeAll -> Query prepared and get all query results.

func (*Way) TakeAllContext

func (s *Way) TakeAllContext(ctx context.Context, result interface{}, prepare string, args ...interface{}) error

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

func (*Way) Transaction

func (s *Way) Transaction(ctx context.Context, fc func(tx *Way) error, opts ...*sql.TxOptions) error

Transaction -> Atomically executes a set of SQL statements. If a transaction has been opened, the opened transaction instance will be used.

func (*Way) TransactionIsNil added in v2.0.3

func (s *Way) TransactionIsNil() bool

TransactionIsNil -> Is the transaction object empty?

func (*Way) TransactionMessage added in v2.0.3

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

TransactionMessage -> Set the prompt for the current transaction, can only be set once.

func (*Way) TransactionNew added in v2.0.3

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) WindowFunc added in v2.0.5

func (s *Way) WindowFunc(alias ...string) *WindowFunc

WindowFunc New a window function object.

type WindowFunc

type WindowFunc struct {
	// Helper Database helper.
	Helper Helper
	// 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 field 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(column string) *WindowFunc

Count COUNT() Returns the number of rows in the window.

func (*WindowFunc) DenseRank

func (s *WindowFunc) DenseRank() *WindowFunc

DenseRank DENSE_RANK() Similar to RANK(), but does not skip rankings.

func (*WindowFunc) Desc

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

Desc Define the sorting within the partition so that the window function is calculated in descending order.

func (*WindowFunc) FirstValue

func (s *WindowFunc) FirstValue(column string) *WindowFunc

FirstValue FIRST_VALUE() Returns the value of the first row in the window.

func (*WindowFunc) Lag

func (s *WindowFunc) Lag(column string, offset int64, defaultValue any) *WindowFunc

Lag LAG() Returns the value of the row before the current row.

func (*WindowFunc) LastValue

func (s *WindowFunc) LastValue(column string) *WindowFunc

LastValue LAST_VALUE() Returns the value of the last row in the window.

func (*WindowFunc) Lead

func (s *WindowFunc) Lead(column string, offset int64, defaultValue any) *WindowFunc

Lead LEAD() Returns the value of a row after the current row.

func (*WindowFunc) Max

func (s *WindowFunc) Max(column string) *WindowFunc

Max MAX() Returns the maximum value within the window.

func (*WindowFunc) Min

func (s *WindowFunc) Min(column string) *WindowFunc

Min MIN() Returns the minimum value within the window.

func (*WindowFunc) NthValue

func (s *WindowFunc) NthValue(column string, LineNumber int64) *WindowFunc

NthValue NTH_VALUE() The Nth value can be returned according to the specified order. This is very useful when you need to get data at a specific position.

func (*WindowFunc) Ntile

func (s *WindowFunc) Ntile(buckets int64) *WindowFunc

Ntile NTILE() Divide the rows in the window into n buckets and assign a bucket number to each row.

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

func (s *WindowFunc) Result() string

Result Query column expressions.

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

func (s *WindowFunc) WindowFrame(windowFrame string) *WindowFunc

WindowFrame Set custom window frame clause.

func (*WindowFunc) WithFunc

func (s *WindowFunc) WithFunc(withFunc string) *WindowFunc

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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