hey

package module
v3.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2025 License: MIT Imports: 18 Imported by: 0

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

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(balance)", "id = ?", "SELECT id, name FROM your_table_name" ...
  3. Try to avoid using reflection when scanning and querying data to reduce time consumption.
  4. When the database table structure changes, your code will be able to feel it immediately.
  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.

INSTALL

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

How to use hey?

Here are some examples of use:

package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"github.com/cd365/hey/v3"
	"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 */
	"os"
	"time"
)

// 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.Replace = hey.NewReplace() // 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.Replace = hey.NewReplace() // 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.Replace = hey.NewReplace() // 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
}

type ExampleAnyStruct struct {
	Name string `db:"name"` // Table column name
	Age  int    `db:"age"`  // Table column age
}

// Insert Inserting Data
func Insert(way *hey.Way) (affectedRowsOrLastInsertId int64, err error) {
	add := way.Add("your_table_name")

	// Timeout control can be set through the context.
	add.Context(context.Background())

	// Custom SQL statement comments.
	add.Comment("The first insert statement")

	common := func(add *hey.Add) {
		add.ExceptPermit(func(except hey.UpsertColumns, permit hey.UpsertColumns) {
			// Set the list of fields that are not allowed to be added through the `except` object.
			// Set the list of fields that can only be added through the `permit` object.
			except.Add("id", "deleted_at")
		}).Default(func(add *hey.Add) {
			now := way.Now()
			add.ColumnValue("created_at", now.Unix())
			add.ColumnValue("updated_at", now.Unix())
			add.ColumnValue("gender", "female")
		})
	}

	// Method A:
	{
		common(add) // Optional
		affectedRowsOrLastInsertId, err = add.Create(ExampleAnyStruct{}).Add()
		if err != nil {
			return
		}
	}

	// Method B:
	{
		// common(add) // Optional
		affectedRowsOrLastInsertId, err = add.Create(
			map[string]any{
				"your_column_name": "your_column_value",
			},
		).Add()
		if err != nil {
			return
		}
	}

	// Method C:
	{
		// common(add) // Optional
		lists := make([]*ExampleAnyStruct, 0)
		affectedRowsOrLastInsertId, err = add.Create(lists).Add()
		if err != nil {
			return
		}
	}

	// Method D:
	{
		cols := []string{"column1", "column2", "column3"}
		affectedRowsOrLastInsertId, err = add.CmderValues(way.Get("your_query_data_table").Select(cols...), cols).Add()
		if err != nil {
			return
		}
	}

	// Method E:
	{
		// mysql: insert one and get last insert id
		// common(add) // Optional
		affectedRowsOrLastInsertId, err = add.AddOne(func(add hey.AddOneReturnSequenceValue) {
			add.Execute(func(ctx context.Context, stmt *hey.Stmt, args []any) (sequenceValue int64, err error) {
				result, err := stmt.ExecuteContext(ctx, args)
				if err != nil {
					return 0, err
				}
				return result.LastInsertId()
			})
		})
		if err != nil {
			return
		}

		// postgresql: insert one and get last insert id
		// common(add) // Optional
		affectedRowsOrLastInsertId, err = add.AddOne(func(add hey.AddOneReturnSequenceValue) {
			add.Adjust(func(prepare string, args []any) (string, []any) {
				return fmt.Sprintf("%s RETURNING %s", prepare, "id"), args
			}).Execute(func(ctx context.Context, stmt *hey.Stmt, args []any) (sequenceValue int64, err error) {
				err = stmt.QueryRowContext(ctx, func(rows *sql.Row) error { return rows.Scan(&sequenceValue) }, args...)
				return
			})
		})
		if err != nil {
			return
		}
	}

	return affectedRowsOrLastInsertId, nil
}

func filterIdIn[T int | int64 | string](ids ...T) func(f hey.Filter) {
	return func(f hey.Filter) {
		// Type A
		f.In("ids", ids)
		// Type B
		f.In("ids", hey.ArrayToArray(ids, func(k int, v T) any { return v }))
	}
}

// Delete Deleting Data
func Delete(way *hey.Way) (affectedRows int64, err error) {
	del := way.Del("your_table_name")
	// del.Table("your_table_name")

	// Timeout control can be set through the context.
	del.Context(context.Background())

	// Custom SQL statement comments.
	del.Comment("The first delete statement")

	// Method A for WHERE:
	del.Where(func(f hey.Filter) { f.Equal("id", 1) })

	// Method B for WHERE:
	where := way.F()
	where.Equal("id", 1)
	del.Where(func(f hey.Filter) { f.Use(where) })

	// Method C for WHERE:
	del.Where(filterIdIn(1, 2, 3))

	// By default, the constructed SQL statements are output to the terminal for easy debugging.
	// way.Debug(del)

	return del.Del()
}

// Update Updating data
func Update(way *hey.Way) (affectedRows int64, err error) {
	mod := way.Mod("your_table_name")
	// mod.Table("your_table_name")

	// Timeout control can be set through the context.
	mod.Context(context.Background())

	// Custom SQL statement comments.
	mod.Comment("The first update statement")

	// Remember to set the conditional filter when executing the update statement.
	where := way.F().Equal("id", 1)
	where.Clean().Equal("id", 2)
	mod.Where(func(f hey.Filter) { f.Use(where) })

	mod.ExceptPermit(func(except hey.UpsertColumns, permit hey.UpsertColumns) {
		except.Add("id", "created_at", "deleted_at")
	})
	mod.Default(func(mod *hey.Mod) {
		now := mod.GetWay().Now()
		// now = way.Now()
		mod.Set("updated_at", now.Unix())
	})
	mod.Set("name", "Jack")
	mod.Incr("nums", 1)
	mod.Decr("nums", -1)

	return mod.Mod()
}

// Select Querying data
func Select(way *hey.Way) error {
	get := way.Get("your_table_name")
	// get.Table("your_table_name")

	// Timeout control can be set through the context.
	get.Context(context.Background())

	// Custom SQL statement comments.
	get.Comment("The first select statement")

	// Query a piece of data.
	one := &ExampleAnyStruct{}
	if err := get.Limit(1).Get(one); err != nil {
		if !errors.Is(err, hey.ErrNoRows) {
			return err
		}
	}
	// Query a piece of data in ascending order according to id.
	_ = get.Asc("id").Limit(1).Get(one)
	// Query a piece of data in descending order according to id.
	_ = get.Desc("id").Limit(1).Get(one)

	// Query multiple records
	more := make([]*ExampleAnyStruct, 0)
	_ = get.Asc("id").Limit(10).Get(&more)
	_ = get.Asc("id").Limit(10).Offset(10).Get(&more)

	// Specify a list of columns
	_ = get.Select("id", "name", "age").Limit(10).Get(&more)

	// Setting the WHERE condition
	_ = get.Where(func(f hey.Filter) {
		f.GreaterThan("id", 0)
		f.Equal("status", 1)
	}).Limit(10).Get(&more)

	// Setting complex WHERE conditions
	_ = get.Where(func(f hey.Filter) {
		// f.Not()
		f.Group(func(g hey.Filter) {
			g.Group(func(g hey.Filter) {
				g.Group(func(g hey.Filter) {
					g.Equal("role", "student")
					g.LessThanEqual("age", 18)
				})
				g.OrGroup(func(g hey.Filter) {
					g.Equal("gender", "female")
					g.Between("age", 12, 18)
				})
			})
			g.OrGroup(func(g hey.Filter) {
				g.Equal("privilege", "Y")
			})
		})
		f.Equal("status", 1)
		f.IsNull("is_delete")
	}).Limit(10).Get(&more)

	// Group By
	_ = get.Group("age").Having(func(f hey.Filter) { /* TODO */ }).Get(&more)

	// Join queries

	joinGroupBy := make([]string, 0)
	_ = get.Alias(hey.AliasA).Join(func(join hey.QueryJoin) {
		a := join.GetMaster()
		b := join.NewTable("inner_join_table_name_b", hey.AliasB)

		// Joining with subqueries
		// b = join.NewSubquery(way.Get(), hey.AliasB)

		// Special note: When the left table uses a nil value, the table name specified by the Get object will be used for connection by default.
		join.InnerJoin(nil, b, join.OnEqual("left_column_name_a", "right_column_name_b"))

		// Use the specified table as the left table.
		c := join.NewTable("inner_join_table_name_c", hey.AliasC)
		join.InnerJoin(b, c, join.OnEqual("left_column_name_b", "right_column_name_c"))

		/* When the names of the fields in two tables are the same, you can use the following abbreviations. */
		// join.InnerJoin(b, c, join.Using("user_id"))

		// Set the query columns list
		join.SelectGroupsColumns(
			join.TableSelect(a, "id"),
			join.TableSelect(b, "name"),
			join.TableSelect(c, "age"),
			/* ... */
		)
		join.SelectTableColumnAlias(a, "email", "admin_email")
		join.SelectTableColumnAlias(b, "email", "user_email")
		join.SelectTableColumnAlias(c, "score", "score_result")

		// Using a column list prefixed with a table alias in a GROUP BY statement.
		joinGroupBy = join.TableSelect(a, "id", "name")
	}).
		Where(func(f hey.Filter) {}).
		Desc("age").
		Group(joinGroupBy...).
		Limit(10).
		Get(&more)

	// Custom scan data.
	_ = get.ScanAll(func(rows *sql.Rows) error {
		tmp := &ExampleAnyStruct{}
		if err := rows.Scan(&tmp.Name /* ... */); err != nil {
			return err
		}
		more = append(more, tmp)
		return nil
	})

	// Subquery
	_ = get.Subquery(way.Get("table_name"), "a").
		Select("id", "name", "age").
		Where(func(f hey.Filter) {}).
		Desc("id").
		Limit(10).
		Get(&more)

	// Multiple columns comparison
	queried := make([]*ExampleAnyStruct, 0)
	_ = get.Where(func(f hey.Filter) {
		f.InCols(
			[]string{"name", "age"},
			hey.ColumnsInValues(queried, func(tmp *ExampleAnyStruct) []any { return []any{tmp.Name, tmp.Age} })...,
		)
	})

	// Quickly scan data into any structure, do not use reflect scan data.
	prepare, args := get.Select("name", "age").Limit(10).Desc("id").Cmd()
	more, _ = hey.RowsScanStructAll[ExampleAnyStruct](context.Background(), get.GetWay(), func(rows *sql.Rows, v *ExampleAnyStruct) error {
		return rows.Scan(&v.Name, &v.Age)
	}, prepare, args...)

	// Quickly scan a piece of data into any structure, do not use reflect scan data.
	prepare, args = get.Select("name", "age").Limit(1).Desc("id").Cmd()
	one, err := hey.RowsScanStructOne[ExampleAnyStruct](context.Background(), get.GetWay(), func(rows *sql.Rows, v *ExampleAnyStruct) error {
		return rows.Scan(&v.Name, &v.Age)
	}, prepare, args...)
	if err != nil {
		if !errors.Is(err, hey.ErrNoRows) {
			return err
		}
	}

	return nil
}

// Transaction Atomic batch processing
func Transaction(way *hey.Way) error {
	// Automatically commit or rollback the transaction by returning an error through the closure function.
	// The transaction will be committed only when the closure function is successfully called and the returned error value is nil.
	if false {
		return way.Transaction(nil, func(tx *hey.Way) error {
			rows, err := tx.Del("table1").Where(func(f hey.Filter) { f.Equal("id", 1) }).Del()
			if err != nil {
				return err
			}
			if rows == 0 {
				return errors.New("delete failed")
			}
			rows, err = tx.Mod("table2").Where(func(f hey.Filter) { f.Equal("id", 1) }).
				Incr("balance", 10.02).
				Incr("version", 1).
				Set("updated_at", tx.Now().Unix()).
				Mod()
			if err != nil {
				return err
			}
			if rows == 0 {
				return errors.New("update failed")
			}
			return nil
		}, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
	}

	// Manually manage transactions, beware of code panic.
	ctx, cancel := context.WithTimeout(context.Background(), way.GetCfg().TransactionMaxDuration)
	defer cancel()
	tx, err := way.Begin(ctx)
	if err != nil {
		return err
	}
	// defer tx.Rollback() // Want to give it a try?

	/* TODO ... Your business logic */

	// _ = tx.Commit()
	_ = tx.Rollback()
	return nil
}

// Transaction1 Minimize other code in transactions.
func Transaction1(way *hey.Way) error {
	add := way.Add("example_table_1").
		Create(map[string]interface{}{})
	del := way.Del("example_table_2").
		Where(func(f hey.Filter) {
			f.Equal("id", 1)
		})
	mod := way.Mod("example_table_3").
		Set("name", "Jerry").
		Where(func(f hey.Filter) {
			f.Equal("id", 1)
		})
	get := way.Get("example_table_4").
		Select("name", "age").
		Where(func(f hey.Filter) {
			f.Equal("id", 1)
		}).
		Limit(1).
		Desc("id")

	{
		// handle object add, del, mod, get ...
		// TODO ...
	}

	// Generate SQL statements first.
	prepare1, args1 := add.Cmd()
	prepare2, args2 := del.Cmd()
	prepare3, args3 := mod.Cmd()
	prepare4, args4 := get.Cmd()

	var had *ExampleAnyStruct

	err := way.Transaction(nil, func(tx *hey.Way) error {
		rows, err := tx.Exec(prepare1, args1...)
		if err != nil {
			return err
		}
		if rows == 0 {
			return errors.New("insert failed")
		}

		had, err = hey.RowsScanStructOne[ExampleAnyStruct](
			nil, tx,
			func(rows *sql.Rows, v *ExampleAnyStruct) error {
				return rows.Scan(&v.Name, &v.Age /*, .... */)
			},
			prepare4,
			args4...,
		)
		if err != nil {
			if errors.Is(err, hey.ErrNoRows) {
				// todo
				// return errors.New("record does not exists")
			} else {
				return err
			}
		}
		{
			// use had todo ...
			// Replace the parameters in the following SQL statement to be executed ?
			_ = had
		}

		rows, err = tx.Exec(prepare2, args2...)
		if err != nil {
			return err
		}
		if rows == 0 {
			return errors.New("delete failed")
		}

		rows, err = tx.Exec(prepare3, args3...)
		if err != nil {
			return err
		}
		if rows == 0 {
			return errors.New("update failed")
		}

		return nil
	})
	if err != nil {
		return err
	}

	// TODO other logic codes.

	return nil
}

type ExampleAnyStructUpdate struct {
	Id   int64   `json:"id" db:"id" validate:"required,min=1"`              // Table column id
	Name *string `json:"name" db:"name" validate:"omitempty,min=0,max=255"` // Table column name
	Age  *int    `json:"age" db:"age" validate:"omitempty,min=0,max=150"`   // Table column age
}

// Others Use cases.
func Others(way *hey.Way) error {

	// UNION, UNION ALL, EXCEPT, INTERSECT
	{
		get1 := way.Get("table1").Limit(10)
		get2 := way.Get("table2").Limit(10)
		get3 := way.Get("table3").Limit(10)

		get := hey.UnionAllCmder(get1, get2, get3)
		// get = hey.UnionCmder(get1, get2, get3)
		// get = hey.ExceptCmder(get1, get2, get3)
		// get = hey.IntersectCmder(get1, get2, get3)
		lists := make([]*ExampleAnyStruct, 0)
		err := way.Get().Subquery(get, hey.AliasA).Get(&lists)
		if err != nil {
			return err
		}
	}

	// Update any structure with tag.
	{
		update := &ExampleAnyStructUpdate{}
		_, err := way.Mod("table_name").ExceptPermit(func(except hey.UpsertColumns, permit hey.UpsertColumns) {
			except.Add("id", "created_at", "deleted_at")
			// permit.Add("name", "age")
		}).Update(update).Mod()
		if err != nil {
			return err
		}
	}

	// Update by comparing the property values of the structure.
	{
		origin := &ExampleAnyStruct{}
		update := &ExampleAnyStructUpdate{}
		_, err := way.Mod("table_name").ExceptPermit(func(except hey.UpsertColumns, permit hey.UpsertColumns) {
			except.Add("id", "created_at", "deleted_at")
			// permit.Add("name", "age")
		}).Compare(origin, update).Mod()
		if err != nil {
			return err
		}
	}

	// Select GROUP BY
	{
		t1 := way.TA()
		get := way.Get("table_name").Alias(t1.Alias())
		get.GetSelect().AddAll("uid", t1.SUM("balance", "balance"))
		get.Group("uid").Having(func(f hey.Filter) {
			f.GreaterThanEqual(t1.SUM("balance"), 100)
		})
		_ = get.Get(nil)
	}

	// Update the same column for multiple records.
	{
		// When you need to update the following data at the same time.
		// UPDATE account SET name = 'Alice', age = 18 WHERE ( id = 1 )
		// UPDATE account SET name = 'Bob', age = 20 WHERE ( id = 2 )
		// UPDATE account SET name = 'Tom', age = 21 WHERE ( id = 3 )
		ctx, cancel := context.WithTimeout(context.Background(), way.GetCfg().TransactionMaxDuration)
		defer cancel()

		args := [][]any{
			{"Alice", 18, 1},
			{"Bob", 20, 2},
			{"Tom", 21, 3},
		}
		mod := way.Mod("account").Set("name", "").Set("age", 0).Where(func(f hey.Filter) { f.Equal("id", 1) })
		prepare, _ := mod.Cmd()

		// Efficiently re-execute the same SQL statement by simply changing the parameters.
		affectedRows, err := way.BatchUpdateContext(ctx, prepare, args)
		if err != nil {
			return err
		}
		_ = affectedRows
	}

	return nil
}

// UsingCache Using cache query data.
func UsingCache(way *hey.Way, cacher hey.Cacher, mutexes *hey.StringMutex) (data []*ExampleAnyStruct, err error) {
	// The cacher is usually implemented in Memcached, Redis, current program memory, or even files.
	cache := hey.NewCache(cacher)

	get := way.Get("your_table_name").Select("name", "age").Desc("id").Limit(20).Offset(0)

	cacheCmder := hey.NewCacheCmder(cache, get)

	data = make([]*ExampleAnyStruct, 0)

	exists, err := cacheCmder.GetUnmarshal(&data)
	if err != nil {
		return nil, err
	}

	if exists {
		// The data has been obtained from the cache and no longer needs to be queried from the database.
		return data, nil
	}

	// Prepare to query data from the database.
	cacheKey, _ := cacheCmder.GetCacheKey()

	mutex := mutexes.Get(cacheKey)

	mutex.Lock()
	defer mutex.Unlock()

	exists, err = cacheCmder.GetUnmarshal(&data)
	if err != nil {
		return nil, err
	}

	if exists {
		// The data has been obtained from the cache and no longer needs to be queried from the database.
		return data, nil
	}

	// Querying data from database.
	if err = get.Get(&data); err != nil {
		return nil, err
	}

	// Cache query data.
	if err = cacheCmder.MarshalSet(data, cache.DurationRange(time.Second, 7, 9)); err != nil {
		return nil, err
	}

	return data, nil
}

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 (
	// DefaultTag Mapping of default database column name and struct tag.
	DefaultTag = "db"

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

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

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

	SqlAnd = "AND"
	SqlOr  = "OR"

	SqlNot  = "NOT"
	SqlNull = "NULL"

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

	SqlAll = "ALL"
	SqlAny = "ANY"

	SqlLeftSmallBracket  = "("
	SqlRightSmallBracket = ")"

	SqlExpect    = "EXCEPT"
	SqlIntersect = "INTERSECT"

	SqlCoalesce = "COALESCE"

	SqlDistinct = "DISTINCT"

	SqlSelect = "SELECT"
	SqlInsert = "INSERT"
	SqlUpdate = "UPDATE"
	SqlDelete = "DELETE"
	SqlFrom   = "FROM"
	SqlInto   = "INTO"
	SqlValues = "VALUES"
	SqlSet    = "SET"
	SqlWhere  = "WHERE"

	SqlBetween     = "BETWEEN"
	SqlConflict    = "CONFLICT"
	SqlDo          = "DO"
	SqlExcluded    = "EXCLUDED"
	SqlExists      = "EXISTS"
	SqlGroupBy     = "GROUP BY"
	SqlHaving      = "HAVING"
	SqlIn          = "IN"
	SqlIs          = "IS"
	SqlLike        = "LIKE"
	SqlLimit       = "LIMIT"
	SqlNothing     = "NOTHING"
	SqlOffset      = "OFFSET"
	SqlOn          = "ON"
	SqlOrderBy     = "ORDER BY"
	SqlOver        = "OVER"
	SqlPartitionBy = "PARTITION BY"
	SqlUsing       = "USING"
	SqlWith        = "WITH"
)
View Source
const (
	AliasA = "a"
	AliasB = "b"
	AliasC = "c"
	AliasD = "d"
	AliasE = "e"
	AliasF = "f"
	AliasG = "g"
)
View Source
const (
	DefaultAliasNameCount = "counts"

	RowsScanStructAllMakeSliceLength = "rows_scan_struct_all_make_slice_length"
)
View Source
const (
	// ErrNoRows Error no rows.
	ErrNoRows = manualError("hey: no rows")

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

Variables

This section is empty.

Functions

func ArrayDiscard added in v3.2.0

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

func ArrayToArray

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

func ArrayToAssoc

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

func AssocDiscard added in v3.2.0

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

func AssocToArray

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

func AssocToAssoc added in v3.2.0

func AssocToAssoc[K comparable, V any, X comparable, Y any](values map[K]V, fc func(k K, v V) (X, Y)) map[X]Y

func CmderGet

func CmderGet(ctx context.Context, way *Way, cmder Cmder, result any) error

CmderGet execute the built SQL statement and scan query results.

func CmderGetCmd

func CmderGetCmd(s *Get) (prepare string, args []any)

CmderGetCmd 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 CmderGetCount

func CmderGetCount(s *Get, countColumns ...string) (prepare string, args []any)

CmderGetCount 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 CmderGetOrderLimitOffset

func CmderGetOrderLimitOffset(s *Get) (prepare string, args []any)

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

func CmderGetTable

func CmderGetTable(s *Get) (prepare string, args []any)

CmderGetTable 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 CmderQuery

func CmderQuery(ctx context.Context, way *Way, cmder Cmder, query func(rows *sql.Rows) (err error)) error

CmderQuery execute the built SQL statement and scan query results.

func CmderScanAll

func CmderScanAll(ctx context.Context, way *Way, cmder Cmder, custom func(rows *sql.Rows) error) error

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

func CmderScanOne

func CmderScanOne(ctx context.Context, way *Way, cmder Cmder, dest ...any) error

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

func CmderViewMap

func CmderViewMap(ctx context.Context, way *Way, cmder Cmder) (result []map[string]any, err error)

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

func ColumnInValues

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

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

func ColumnsInValues

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

ColumnsInValues Build ( column1, column2, column3 ... ) IN ( ( values[0].attribute1, values[0].attribute2, values[0].attribute3 ... ), ( values[1].attribute1, values[1].attribute2, values[1].attribute3 ... ) ... )

func ConcatString

func ConcatString(sss ...string) string

ConcatString concatenate string.

func DiscardDuplicate added in v3.1.0

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

DiscardDuplicate discard duplicate element.

func GetCount

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

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

func GetCountGet

func GetCountGet(get *Get, result any, countColumn ...string) (int64, error)

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

func GetCountQuery

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

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

func GetExists

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

GetExists Determine whether the query result exists.

func GetGet

func GetGet(get *Get, result any) 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 results.

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 ...any) 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]any, err error)

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

func IsEmptyCmder

func IsEmptyCmder(cmder Cmder) bool

IsEmptyCmder Check whether the result (SQL statement) of Cmder is empty.

func LastNotEmptyString

func LastNotEmptyString(sss []string) string

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

func MergeArray

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

func MergeAssoc

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

func MustAffectedRows

func MustAffectedRows(affectedRows int64, err error) error

MustAffectedRows at least one row is affected.

func NullDefaultValue

func NullDefaultValue(prepare string, defaultValue string) string

NullDefaultValue Use defaultValue to replace NULL values.

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 PutFilter

func PutFilter(f Filter)

func RowsScan added in v3.2.0

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

func RowsScanStructAll

func RowsScanStructAll[V any](ctx context.Context, way *Way, scan func(rows *sql.Rows, v *V) error, prepare string, args ...any) ([]*V, error)

RowsScanStructAll Rows scan to any struct, based on struct scan data.

func RowsScanStructAllCmder

func RowsScanStructAllCmder[V any](ctx context.Context, way *Way, scan func(rows *sql.Rows, v *V) error, cmder Cmder) ([]*V, error)

RowsScanStructAllCmder Rows scan to any struct, based on struct scan data.

func RowsScanStructOne

func RowsScanStructOne[V any](ctx context.Context, way *Way, scan func(rows *sql.Rows, v *V) error, prepare string, args ...any) (*V, error)

RowsScanStructOne Rows scan to any struct, based on struct scan data.

func RowsScanStructOneCmder

func RowsScanStructOneCmder[V any](ctx context.Context, way *Way, scan func(rows *sql.Rows, v *V) error, cmder Cmder) (*V, error)

RowsScanStructOneCmder Rows scan to any struct, based on struct scan data.

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 ...any) error

ScanOne Scan at most once from the query results.

func ScanViewMap

func ScanViewMap(rows *sql.Rows) ([]map[string]any, error)

ScanViewMap Scan query result to []map[string]any, view query result.

func SqlAlias

func SqlAlias(name string, alias string) string

SqlAlias sql alias name.

func SqlPrefix

func SqlPrefix(prefix string, name string) string

SqlPrefix add SQL prefix name; if the prefix exists, it will not be added.

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.

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

func (s *Add) AddOne(custom func(add AddOneReturnSequenceValue)) (int64, error)

AddOne execute the built SQL statement, return the sequence value of the data.

func (*Add) Cmd

func (s *Add) Cmd() (prepare string, args []any)

Cmd build SQL statement.

func (*Add) CmderValues

func (s *Add) CmderValues(cmdValues Cmder, columns []string) *Add

CmderValues values is a query SQL statement.

func (*Add) ColumnValue

func (s *Add) ColumnValue(column string, value any) *Add

ColumnValue append column-value for insert one or more rows.

func (*Add) ColumnsValues

func (s *Add) ColumnsValues(columns []string, values [][]any) *Add

ColumnsValues set columns and values.

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 any) *Add

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

func (*Add) Default

func (s *Add) Default(add func(add *Add)) *Add

Default Add column = value .

func (*Add) ExceptPermit

func (s *Add) ExceptPermit(custom func(except UpsertColumns, permit UpsertColumns)) *Add

ExceptPermit Set a list of columns that are not allowed to be inserted and a list of columns that are only allowed to be inserted.

func (*Add) GetColumns

func (s *Add) GetColumns() []string

GetColumns list of columns to insert.

func (*Add) GetContext

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

GetContext get context.

func (*Add) GetValues

func (s *Add) GetValues() [][]any

GetValues list of values to insert.

func (*Add) GetWay

func (s *Add) GetWay() *Way

GetWay get current *Way.

func (*Add) SetWay added in v3.0.1

func (s *Add) SetWay(way *Way) *Add

SetWay use the specified *Way object.

func (*Add) Table

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

Table set table name.

type AddOneReturnSequenceValue

type AddOneReturnSequenceValue interface {
	// Adjust You may need to modify the SQL statement to be executed.
	Adjust(adjust func(prepare string, args []any) (string, []any)) AddOneReturnSequenceValue

	// Context Custom context.
	Context(ctx context.Context) AddOneReturnSequenceValue

	// Execute Customize the method to return the sequence value of inserted data.
	Execute(execute func(ctx context.Context, stmt *Stmt, args []any) (sequenceValue int64, err error)) AddOneReturnSequenceValue

	// AddOne Insert a record and return the sequence value of the data (usually an auto-incrementing id value).
	AddOne() (int64, error)
}

AddOneReturnSequenceValue Insert a record and return the sequence value of the data (usually an auto-incrementing id value).

type Cache added in v3.2.0

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

Cache Read and write data in cache.

func NewCache added in v3.2.0

func NewCache(cacher Cacher) *Cache

NewCache Create a new *Cache object.

func (*Cache) Del added in v3.2.0

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

Del Deleting data from the cache.

func (*Cache) DurationRange added in v3.2.0

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

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

Exists Whether cached data exists?

func (*Cache) Get added in v3.2.0

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

Get Read cache data from cache.

func (*Cache) GetBool added in v3.2.0

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

GetBool Read bool cache data from cache.

func (*Cache) GetCacher added in v3.2.0

func (s *Cache) GetCacher() Cacher

GetCacher Read Cacher.

func (*Cache) GetFloat added in v3.2.0

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

GetFloat Read float64 cache data from cache.

func (*Cache) GetInt added in v3.2.0

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

GetInt Read int64 cache data from cache.

func (*Cache) GetString added in v3.2.0

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

GetString Read string cache data from cache.

func (*Cache) GetUnmarshal added in v3.2.0

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

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

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

Set Write cache data to cache.

func (*Cache) SetBool added in v3.2.0

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

SetBool Write bool cache data to cache.

func (*Cache) SetCacher added in v3.2.0

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

SetCacher Write Cacher.

func (*Cache) SetFloat added in v3.2.0

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

SetFloat Write float64 cache data to cache.

func (*Cache) SetInt added in v3.2.0

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

SetInt Write int64 cache data to cache.

func (*Cache) SetString added in v3.2.0

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

SetString Write string cache data to cache.

type CacheCmder added in v3.2.0

type CacheCmder 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(cmder Cmder) (string, error)) CacheCmder

	// Reset For reset cmder and it's related property values.
	Reset(cmder ...Cmder) CacheCmder

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

CacheCmder Cache SQL statement related data, including but not limited to cache query data.

func NewCacheCmder added in v3.2.0

func NewCacheCmder(cache *Cache, cmder Cmder) CacheCmder

NewCacheCmder Create a new CacheCmder object.

type Cacher added in v3.2.0

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 Caller

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

	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

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

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

type Cfg

type Cfg struct {
	// DeleteMustUseWhere Deletion of data must be filtered using conditions.
	DeleteMustUseWhere bool

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

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

	// Scan Scan data into structure.
	Scan func(rows *sql.Rows, result any, tag string) error

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

	// TransactionOptions Start transaction.
	TransactionOptions *sql.TxOptions

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

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

	// Debugger Debug output SQL script.
	Debugger Debugger
	// contains filtered or unexported fields
}

Cfg Configure of Way.

func DefaultCfg

func DefaultCfg() Cfg

DefaultCfg default configure value.

type Cmder

type Cmder interface {
	// Cmd Get a list of script statements and their corresponding parameters.
	Cmd() (prepare string, args []any)
}

Cmder Used to build SQL expression and its corresponding parameter list.

func ConcatCmder

func ConcatCmder(concat string, custom func(index int, cmder Cmder) Cmder, items ...Cmder) Cmder

ConcatCmder Concat multiple Cmder.

func ExceptCmder

func ExceptCmder(items ...Cmder) Cmder

ExceptCmder CmderA, CmderB ... => ( ( QUERY_A ) EXCEPT ( QUERY_B ) ... )

func IntersectCmder

func IntersectCmder(items ...Cmder) Cmder

IntersectCmder CmderA, CmderB ... => ( ( QUERY_A ) INTERSECT ( QUERY_B ) ... )

func NewCmder

func NewCmder(prepare string, args []any) Cmder

NewCmder Construct a Cmder using SQL statements and parameter lists.

func ParcelCancelCmder

func ParcelCancelCmder(cmder Cmder) Cmder

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

func ParcelCmder

func ParcelCmder(cmder Cmder) Cmder

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

func UnionAllCmder

func UnionAllCmder(items ...Cmder) Cmder

UnionAllCmder CmderA, CmderB, CmderC ... => ( ( QUERY_A ) UNION ALL ( QUERY_B ) UNION ALL ( QUERY_C ) ... )

func UnionCmder

func UnionCmder(items ...Cmder) Cmder

UnionCmder CmderA, CmderB, CmderC ... => ( ( QUERY_A ) UNION ( QUERY_B ) UNION ( QUERY_C ) ... )

type Debugger

type Debugger interface {
	// Debug Debug output SQL script
	Debug(cmder Cmder) Debugger

	GetLogger() *logger.Logger

	SetLogger(log *logger.Logger) Debugger
}

Debugger Debug output SQL script.

func NewDebugger added in v3.2.0

func NewDebugger() Debugger

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

func (s *Del) Cmd() (prepare string, args []any)

Cmd build SQL statement.

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

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

GetContext get context.

func (*Del) GetWay

func (s *Del) GetWay() *Way

GetWay get current *Way.

func (*Del) SetWay added in v3.0.1

func (s *Del) SetWay(way *Way) *Del

SetWay use the specified *Way object.

func (*Del) Table

func (s *Del) Table(table string, args ...any) *Del

Table set table name.

func (*Del) TableCmder

func (s *Del) TableCmder(cmder TableCmder) *Del

TableCmder Set table script.

func (*Del) Where

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

Where set where.

type Filter

type Filter interface {
	Cmder

	// Clean Clear the existing conditional filtering of the current object.
	Clean() 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(prepare string, args ...any) Filter

	// Or Use logical operator `OR` to combine custom conditions.
	Or(prepare string, args ...any) Filter

	// Group Add a new condition group, which is connected by the `AND` logical operator by default.
	Group(group func(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 any) Filter

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

	// LessThan Implement conditional filtering: column < value .
	LessThan(column string, value any) Filter

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

	// Equal Implement conditional filtering: column = value .
	Equal(column string, value any, useNull ...bool) Filter

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

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

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

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

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

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

	// Like Implement conditional filtering: column LIKE value.
	Like(column string, value any) Filter

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

	// InQuery Implement conditional filtering: column IN (subquery).
	InQuery(column string, subquery Cmder) Filter

	// InColsQuery Implement conditional filtering: ( column1, column2, column3... ) IN ( subquery ) .
	InColsQuery(columns []string, subquery Cmder) Filter

	// ExistsQuery Implement conditional filtering: EXISTS (subquery).
	ExistsQuery(subquery Cmder) Filter

	// NotEqual Implement conditional filtering: column <> value .
	NotEqual(column string, value any, useNotNull ...bool) Filter

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

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

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

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

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

	// AllQuantifier Implement conditional filtering: column {=||<>||>||>=||<||<=} ALL ( subquery ) .
	AllQuantifier(fc func(tmp Quantifier)) Filter

	// AnyQuantifier Implement conditional filtering: column {=||<>||>||>=||<||<=} ANY ( subquery ) .
	AnyQuantifier(fc func(tmp Quantifier)) Filter

	// GetWay For get *Way.
	GetWay() *Way

	// SetWay For set *Way.
	SetWay(way *Way) Filter

	// Compare Implement conditional filtering: column1 {=||<>||>||>=||<||<=} column2 .
	Compare(column1 string, compare string, column2 string, args ...any) Filter

	// CompareEqual Implement conditional filtering: column1 = column2 .
	CompareEqual(column1 string, column2 string, args ...any) Filter

	// CompareNotEqual Implement conditional filtering: column1 <> column2 .
	CompareNotEqual(column1 string, column2 string, args ...any) Filter

	// CompareGreaterThan Implement conditional filtering: column1 > column2 .
	CompareGreaterThan(column1 string, column2 string, args ...any) Filter

	// CompareGreaterThanEqual Implement conditional filtering: column1 >= column2 .
	CompareGreaterThanEqual(column1 string, column2 string, args ...any) Filter

	// CompareLessThan Implement conditional filtering: column1 < column2.
	CompareLessThan(column1 string, column2 string, args ...any) Filter

	// CompareLessThanEqual Implement conditional filtering: column1 <= column2 .
	CompareLessThanEqual(column1 string, column2 string, args ...any) Filter
}

Filter Implement SQL statement conditional filtering (general conditional filtering).

func F

func F() Filter

F New a Filter.

func GetFilter

func GetFilter() Filter

func ParcelFilter

func ParcelFilter(tmp Filter) Filter

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

type Get

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

Get for SELECT.

func NewGet

func NewGet(way *Way) *Get

NewGet for SELECT.

func (*Get) Alias

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

Alias for table alias name, remember 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) Cmd

func (s *Get) Cmd() (prepare string, args []any)

Cmd build SQL statement.

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 results for count.

func (*Get) CountCmd

func (s *Get) CountCmd(columns ...string) (string, []any)

CountCmd build SQL statement for count.

func (*Get) CountGet

func (s *Get) CountGet(result any, countColumn ...string) (int64, error)

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

func (*Get) CountQuery

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

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

func (*Get) Desc

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

Desc set order by column Desc.

func (*Get) Exists

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

Exists Determine whether the query result exists.

func (*Get) Get

func (s *Get) Get(result any) error

Get execute the built SQL statement and scan query results.

func (*Get) GetContext

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

GetContext get context.

func (*Get) GetSelect

func (s *Get) GetSelect() QueryColumns

GetSelect Get select object.

func (*Get) GetWay

func (s *Get) GetWay() *Way

GetWay get current *Way.

func (*Get) Group

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

Group set group columns.

func (*Get) Having

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

Having set filter of group results.

func (*Get) Join

func (s *Get) Join(custom func(join QueryJoin)) *Get

Join for `INNER JOIN`, `LEFT JOIN`, `RIGHT 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 executes the built SQL statement and scan query results.

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 ...any) error

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

func (*Get) Select

func (s *Get) Select(columns ...string) *Get

Select Set the column list for select.

func (*Get) SetSelect

func (s *Get) SetSelect(queryColumns QueryColumns) *Get

SetSelect Set select object.

func (*Get) SetWay added in v3.0.1

func (s *Get) SetWay(way *Way) *Get

SetWay use the specified *Way object.

func (*Get) Subquery

func (s *Get) Subquery(subquery Cmder, alias string) *Get

Subquery table is a subquery.

func (*Get) Table

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

Table set table name.

func (*Get) ViewMap

func (s *Get) ViewMap() ([]map[string]any, error)

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

func (*Get) Where

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

Where set where.

func (*Get) With

func (s *Get) With(alias string, script Cmder) *Get

With for with query.

type InsertOnConflict

type InsertOnConflict interface {
	// OnConflict The column causing the conflict, such as a unique key or primary key, which can be a single column or multiple columns.
	OnConflict(onConflicts ...string) InsertOnConflict

	// Do The SQL statement that needs to be executed when a data conflict occurs. By default, nothing is done.
	Do(prepare string, args ...any) InsertOnConflict

	// DoUpdateSet SQL update statements executed when data conflicts occur.
	DoUpdateSet(fc func(u InsertOnConflictUpdateSet)) InsertOnConflict

	// Cmd The SQL statement and its parameter list that are finally executed.
	Cmd() (prepare string, args []any)

	// InsertOnConflict Executes the SQL statement constructed by the current object.
	InsertOnConflict() (int64, error)
}

InsertOnConflict Implement the following SQL statement: INSERT INTO ... ON CONFLICT (column_a[, column_b, column_c...]) DO NOTHING /* If a conflict occurs, the insert operation is ignored. */ INSERT INTO ... ON CONFLICT (column_a[, column_b, column_c...]) DO UPDATE SET column1 = EXCLUDED.column1, column2 = EXCLUDED.column2, column3 = EXCLUDED.column3, column4 = 'fixed value' ... /* If a conflict occurs, the existing row is updated with the new value */

func NewInsertOnConflict

func NewInsertOnConflict(way *Way, insertPrepare string, insertArgs []any) InsertOnConflict

type InsertOnConflictUpdateSet

type InsertOnConflictUpdateSet interface {
	UpdateSet

	// 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) InsertOnConflictUpdateSet
}

InsertOnConflictUpdateSet Implement the following SQL statement: INSERT INTO ... ON CONFLICT ( column_a[, column_b, column_c...] ) DO UPDATE SET column1 = EXCLUDED.column1, column2 = EXCLUDED.column2, column3 = EXCLUDED.column3, column4 = 'fixed value' ...

func NewInsertOnConflictUpdateSet

func NewInsertOnConflictUpdateSet(way *Way) InsertOnConflictUpdateSet

type InsertValue

type InsertValue interface {
	IsEmpty

	Cmder

	SetSubquery(subquery Cmder) InsertValue

	SetValues(values ...[]any) InsertValue

	Set(index int, value any) InsertValue

	Del(indexes ...int) InsertValue

	LenValues() int

	GetValues() [][]any
}

InsertValue Constructing insert values.

func NewInsertValue

func NewInsertValue() InsertValue

type IsEmpty

type IsEmpty interface {
	IsEmpty() bool
}

IsEmpty Check if an object value is empty.

type JoinFunc added in v3.1.0

type JoinFunc func(leftAlias string, rightAlias string) JoinOn

JoinFunc Constructing conditions for join queries.

type JoinOn added in v3.1.0

type JoinOn interface {
	Cmder

	// Filter JOIN ON Condition.
	Filter() Filter

	// On Using custom JOIN ON conditions.
	On(on func(on Filter)) JoinOn

	// Equal Use equal value JOIN ON condition.
	Equal(leftAlias string, leftColumn string, rightAlias string, rightColumn string) JoinOn

	// Using Use USING instead of ON.
	Using(using ...string) JoinOn
}

type Limiter

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

Limiter limit and offset.

type Manual

type Manual struct {
	// Prepare to adjust the SQL statement format to meet the current database SQL statement format.
	Prepare func(prepare string) string

	// Replace Helpers for handling different types of databases.
	Replace Replace
}

Manual For handling different types of databases.

func Mysql

func Mysql() *Manual

func Postgresql

func Postgresql() *Manual

func Sqlite

func Sqlite() *Manual

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

func (s *Mod) Cmd() (prepare string, args []any)

Cmd build SQL statement.

func (*Mod) ColumnsValues

func (s *Mod) ColumnsValues(columns []string, values []any) *Mod

ColumnsValues SET column = value by slice, require len(columns) == len(values).

func (*Mod) Comment

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

Comment set comment.

func (*Mod) Compare

func (s *Mod) Compare(old, new any, except ...string) *Mod

Compare For compare old and new to automatically calculate the need to update columns.

func (*Mod) Context

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

Context set context.

func (*Mod) Decr

func (s *Mod) Decr(column string, value any) *Mod

Decr SET column = column - value.

func (*Mod) Default

func (s *Mod) Default(custom func(mod *Mod)) *Mod

Default SET column = expr .

func (*Mod) ExceptPermit

func (s *Mod) ExceptPermit(custom func(except UpsertColumns, permit UpsertColumns)) *Mod

ExceptPermit Set a list of columns that are not allowed to be updated and a list of columns that are only allowed to be updated.

func (*Mod) Expr

func (s *Mod) Expr(expr string, args ...any) *Mod

Expr update column using custom expression.

func (*Mod) GetContext

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

GetContext get context.

func (*Mod) GetUpdateSet

func (s *Mod) GetUpdateSet() (prepare string, args []any)

GetUpdateSet prepare args of SET.

func (*Mod) GetWay

func (s *Mod) GetWay() *Way

GetWay get current *Way.

func (*Mod) Incr

func (s *Mod) Incr(column string, value any) *Mod

Incr SET column = column + value.

func (*Mod) Mod

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

Mod execute the built SQL statement.

func (*Mod) Set

func (s *Mod) Set(column string, value any) *Mod

Set column = value.

func (*Mod) SetWay added in v3.0.1

func (s *Mod) SetWay(way *Way) *Mod

SetWay use the specified *Way object.

func (*Mod) Table

func (s *Mod) Table(table string, args ...any) *Mod

Table set table name.

func (*Mod) Update

func (s *Mod) Update(update any) *Mod

Update Value of update should be one of anyStruct, *anyStruct, map[string]any.

func (*Mod) Where

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

Where set where.

type Quantifier

type Quantifier interface {
	GetQuantifier() string

	SetQuantifier(quantifierString string) Quantifier

	Equal(column string, subquery Cmder) Quantifier

	NotEqual(column string, subquery Cmder) Quantifier

	GreaterThan(column string, subquery Cmder) Quantifier

	GreaterThanEqual(column string, subquery Cmder) Quantifier

	LessThan(column string, subquery Cmder) Quantifier

	LessThanEqual(column string, subquery Cmder) Quantifier
}

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

type QueryColumns

type QueryColumns interface {
	IsEmpty

	Cmder

	Index(column string) int

	Exists(column string) bool

	Add(column string, args ...any) QueryColumns

	AddAll(columns ...string) QueryColumns

	DelAll(columns ...string) QueryColumns

	Len() int

	Get() ([]string, map[int][]any)

	Set(columns []string, columnsArgs map[int][]any) QueryColumns

	Use(queryColumns ...QueryColumns) QueryColumns

	// Queried Get all columns of the query results.
	Queried(excepts ...string) []string
}

QueryColumns Used to build the list of columns to be queried.

func NewQueryColumns

func NewQueryColumns(way *Way) QueryColumns

type QueryGroup

type QueryGroup interface {
	IsEmpty

	Cmder

	Group(columns ...string) QueryGroup

	Having(having func(having Filter)) QueryGroup
}

QueryGroup Constructing query groups.

func NewQueryGroup

func NewQueryGroup(way *Way) QueryGroup

type QueryJoin

type QueryJoin interface {
	Cmder

	GetMaster() TableCmder

	SetMaster(master TableCmder) QueryJoin

	NewTable(table string, alias string, args ...any) TableCmder

	NewSubquery(subquery Cmder, alias string) TableCmder

	On(onList ...func(o JoinOn, leftAlias string, rightAlias string)) JoinFunc

	Using(columns ...string) JoinFunc

	OnEqual(leftColumn string, rightColumn string) JoinFunc

	Join(joinTypeString string, leftTable TableCmder, rightTable TableCmder, on JoinFunc) QueryJoin

	InnerJoin(leftTable TableCmder, rightTable TableCmder, on JoinFunc) QueryJoin

	LeftJoin(leftTable TableCmder, rightTable TableCmder, on JoinFunc) QueryJoin

	RightJoin(leftTable TableCmder, rightTable TableCmder, on JoinFunc) QueryJoin

	// Queries Get query columns.
	Queries() QueryColumns

	// TableColumn Build *TableColumn based on TableCmder.
	TableColumn(table TableCmder) *TableColumn

	// TableSelect Add the queried column list based on the table's alias prefix.
	TableSelect(table TableCmder, columns ...string) []string

	// SelectGroupsColumns Add the queried column list based on the table's alias prefix.
	SelectGroupsColumns(columns ...[]string) QueryJoin

	// SelectTableColumnAlias Batch set multiple columns of the specified table and set aliases for all columns.
	SelectTableColumnAlias(table TableCmder, columnAndColumnAlias ...string) QueryJoin
}

QueryJoin Constructing multi-table join queries.

func NewQueryJoin

func NewQueryJoin(way *Way) QueryJoin

type QueryLimit

type QueryLimit interface {
	IsEmpty

	Cmder

	Limit(limit int64) QueryLimit

	Offset(offset int64) QueryLimit

	Page(page int64, limit ...int64) QueryLimit
}

QueryLimit Constructing query limits.

func NewQueryLimit

func NewQueryLimit() QueryLimit

type QueryOrder

type QueryOrder interface {
	IsEmpty

	Cmder

	Asc(columns ...string) QueryOrder

	Desc(columns ...string) QueryOrder
}

QueryOrder Constructing query orders.

func NewQueryOrder

func NewQueryOrder(way *Way) QueryOrder

type QueryWith

type QueryWith interface {
	IsEmpty

	Cmder

	// Set Setting common table expression.
	Set(alias string, cmder Cmder, columns ...string) QueryWith

	// Del Removing common table expression.
	Del(alias string) QueryWith
}

QueryWith CTE: Common Table Expression.

func NewQueryWith

func NewQueryWith() QueryWith

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 Replace

type Replace interface {
	Get(key string) string

	Set(key string, value string) Replace

	Del(key string) Replace

	Map() map[string]string

	Use(mapping map[string]string) Replace

	// Gets Batch getting.
	Gets(keys []string) []string

	// Sets Batch setting.
	Sets(mapping map[string]string) Replace
}

Replace For replacement identifiers in SQL statements. Replace by default, concurrent reads and writes are not safe. If you need concurrent read and write security, you can implement Replace by yourself.

func NewReplace

func NewReplace() Replace

type 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(args ...any) (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 ...any) (int64, error)

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

func (*Stmt) Execute

func (s *Stmt) Execute(args ...any) (sql.Result, error)

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

func (*Stmt) ExecuteContext

func (s *Stmt) ExecuteContext(ctx context.Context, args ...any) (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 ...any) 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 ...any) error

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

func (*Stmt) QueryRow

func (s *Stmt) QueryRow(query func(rows *sql.Row) error, args ...any) (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 ...any) error

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

func (*Stmt) TakeAll

func (s *Stmt) TakeAll(result any, args ...any) 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 any, args ...any) error

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

type StringMutex added in v3.2.0

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

StringMutex maps string keys to a fixed set of sync.Mutex locks using hashing.

func NewStringMutex added in v3.2.0

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

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

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

func (*StringMutex) Len added in v3.2.0

func (s *StringMutex) Len() int

Len returns the number of mutexes.

type TableCmder

type TableCmder interface {
	IsEmpty

	Cmder

	// Alias Setting aliases for script statements.
	Alias(alias string) TableCmder

	// GetAlias Getting aliases for script statements.
	GetAlias() string
}

TableCmder Used to construct expressions that can use table aliases and their corresponding parameter lists.

func NewCmderGet

func NewCmderGet(alias string, get *Get) TableCmder

func NewTableCmder

func NewTableCmder(prepare string, args []any) TableCmder

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 UpdateSet

type UpdateSet interface {
	IsEmpty

	Cmder

	Update(update string, args ...any) UpdateSet

	Set(column string, value any) UpdateSet

	Decr(column string, decr any) UpdateSet

	Incr(column string, incr any) UpdateSet

	SetMap(columnValue map[string]any) UpdateSet

	SetSlice(columns []string, values []any) UpdateSet

	Len() int

	GetUpdate() (updates []string, args [][]any)

	UpdateIndex(prepare string) int

	UpdateExists(prepare string) bool
}

UpdateSet Constructing update sets.

func NewUpdateSet

func NewUpdateSet(way *Way) UpdateSet

type UpsertColumns

type UpsertColumns interface {
	IsEmpty

	Cmder

	Add(columns ...string) UpsertColumns

	Del(columns ...string) UpsertColumns

	DelUseIndex(indexes ...int) UpsertColumns

	ColumnIndex(column string) int

	ColumnExists(column string) bool

	Len() int

	SetColumns(columns []string) UpsertColumns

	GetColumns() []string

	GetColumnsMap() map[string]*struct{}
}

UpsertColumns Constructing insert columns.

func NewUpsertColumns

func NewUpsertColumns(way *Way) UpsertColumns

type Way

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

Way Quick insert, delete, update, select helper.

func NewWay

func NewWay(db *sql.DB) *Way

func (*Way) Add

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

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

func (*Way) BatchUpdate

func (s *Way) BatchUpdate(prepare string, argsList [][]any) (affectedRows int64, err error)

func (*Way) BatchUpdateContext

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

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

func (s *Way) CmderExec(cmder Cmder) (int64, error)

func (*Way) CmderExecContext

func (s *Way) CmderExecContext(ctx context.Context, cmder Cmder) (int64, error)

func (*Way) CmderExecute

func (s *Way) CmderExecute(cmder Cmder) (sql.Result, error)

func (*Way) CmderExecuteContext

func (s *Way) CmderExecuteContext(ctx context.Context, cmder Cmder) (sql.Result, error)

func (*Way) CmderQuery

func (s *Way) CmderQuery(cmder Cmder, query func(rows *sql.Rows) error) error

func (*Way) CmderQueryContext

func (s *Way) CmderQueryContext(ctx context.Context, cmder Cmder, query func(rows *sql.Rows) error) error

func (*Way) CmderQueryRow

func (s *Way) CmderQueryRow(cmder Cmder, query func(row *sql.Row) error) error

func (*Way) CmderQueryRowContext

func (s *Way) CmderQueryRowContext(ctx context.Context, cmder Cmder, query func(row *sql.Row) error) error

func (*Way) CmderTakeAll

func (s *Way) CmderTakeAll(cmder Cmder, result any) error

func (*Way) CmderTakeAllContext

func (s *Way) CmderTakeAllContext(ctx context.Context, cmder Cmder, result any) error

func (*Way) Commit

func (s *Way) Commit() error

Commit -> Transaction commit.

func (*Way) Debug added in v3.2.0

func (s *Way) Debug(cmder Cmder) *Way

Debug Debugging output SQL script.

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 ...any) (int64, error)

Exec -> Execute the execute sql statement.

func (*Way) ExecContext

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

ExecContext -> Execute the execute sql statement.

func (*Way) Execute

func (s *Way) Execute(prepare string, args ...any) (sql.Result, error)

Execute -> Execute the execute sql statement.

func (*Way) ExecuteContext

func (s *Way) ExecuteContext(ctx context.Context, prepare string, args ...any) (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) GetCfg

func (s *Way) GetCfg() *Cfg

func (*Way) GetDatabase

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

func (*Way) GetLogger

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

func (*Way) GetReader

func (s *Way) GetReader() Reader

func (*Way) Getter

func (s *Way) Getter(caller Caller, query func(rows *sql.Rows) error, prepare string, args ...any) 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 ...any) (err error)

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

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

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

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

func (*Way) NewAddOne

func (s *Way) NewAddOne(prepare string, args []any) AddOneReturnSequenceValue

NewAddOne Insert one and get the last insert sequence value.

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, remember 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, remember to call *Stmt.Close().

func (*Way) Query

func (s *Way) Query(query func(rows *sql.Rows) error, prepare string, args ...any) 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 ...any) error

QueryContext -> Execute the query sql statement.

func (*Way) QueryRow

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

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

func (*Way) QueryRowContext

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

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

func (*Way) Read

func (s *Way) Read() *Way

func (*Way) Replace

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

Replace For a replacement key.

func (*Way) Replaces

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

Replaces For replacement keys.

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 ...any) error

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

func (*Way) SetCfg

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

func (*Way) SetDatabase

func (s *Way) SetDatabase(db *sql.DB) *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 ...any) (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 ...any) (int64, error)

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

func (*Way) T

func (s *Way) T() *TableColumn

T Table empty alias

func (*Way) TA

func (s *Way) TA() *TableColumn

TA Table alias `a`

func (*Way) TB

func (s *Way) TB() *TableColumn

TB Table alias `b`

func (*Way) TC

func (s *Way) TC() *TableColumn

TC Table alias `c`

func (*Way) TD

func (s *Way) TD() *TableColumn

TD Table alias `d`

func (*Way) TE

func (s *Way) TE() *TableColumn

TE Table alias `e`

func (*Way) TF

func (s *Way) TF() *TableColumn

TF Table alias `f`

func (*Way) TG

func (s *Way) TG() *TableColumn

TG Table alias `g`

func (*Way) TakeAll

func (s *Way) TakeAll(result any, prepare string, args ...any) error

TakeAll -> Query prepared and get all query results.

func (*Way) TakeAllContext

func (s *Way) TakeAllContext(ctx context.Context, result any, prepare string, args ...any) 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) 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) WindowFunc

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

WindowFunc New a window function object.

type WindowFunc

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

WindowFunc SQL window function.

func NewWindowFunc

func NewWindowFunc(way *Way, aliases ...string) *WindowFunc

func (*WindowFunc) Alias

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

Alias Set the alias of the column that uses the window function.

func (*WindowFunc) Asc

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

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

func (*WindowFunc) Avg

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

Avg AVG() Returns the average of all rows in the window.

func (*WindowFunc) Count

func (s *WindowFunc) Count(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()...

Jump to

Keyboard shortcuts

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