sqlx

package module
v0.39.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2024 License: Apache-2.0 Imports: 18 Imported by: 1

README

SQL builder for Go 1.18+ Build Status GoDoc License

Package sqlx provides a set of flexible and powerful SQL builders, not ORM, which is inspired by go-sqlbuilder. The built result can be used by DB.Query() and DB.Exec()

Install

$ go get -u github.com/xgfone/go-sqlx

Usage

package main

import (
	"fmt"

	"github.com/xgfone/go-op"
	"github.com/xgfone/go-sqlx"
)

func main() {
	builder := sqlx.Select("*").From("table")
	builder.Where(op.Equal("id", 123), op.Between("age", 20, 30))

	// You can set the dialect by hand, which is DefaultDialect by default.
	// DefaultDialect is the MySQL dialect, but you can modify it.
	// builder.SetDialect(Sqlite3)

	sql, args := builder.Build()
	fmt.Println(sql)
	fmt.Println(args)

	// Output:
	// SELECT * FROM `table` WHERE (`id`=? AND `age` BETWEEN ? AND ?)
	// [123 20 30]
}

You can use sqlx.DB, which is the proxy of builder and sql.DB, it will automatically set the dialect by the sql driver name. For example,

// Set the dialect to MySQL.
db, _ := sqlx.Open("mysql", "user:password@tcp(127.0.0.1:3306)/db")
builder := db.Select("*").From("table").Where(op.Equal("id", 123))

sql, args := builder.Build()
rows, err := db.Query(sql, args...)

// Or
// rows, err := builder.Query()
Intercept SQL
package main

import (
	"fmt"

	"github.com/xgfone/go-op"
	"github.com/xgfone/go-sqlx"
)

func main() {
	// Open DB connecting the mysql server and set the dialect to MySQL.
	db, err := sqlx.Open("mysql", "user:password@tcp(127.0.0.1:3306)/db")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer db.Close()

	// Set the interceptor to print the sql statement.
	db.Interceptor = sqlx.InterceptorFunc(func(sql string, args []any) (string, []any, error) {
		fmt.Println(sql)
		return sql, args, nil
	})

	// Build the SELECT SQL statement
	builder := db.Select("*").From("table")
	builder.Where(op.Equal("id", 123))
	rows, err := builder.Query()
	// ...

	// Interceptor will output:
	// SELECT * FROM `table` WHERE `id`=?
}

Documentation

Overview

Package sqlx is a set of the simple, flexible and powerful SQL builders with zero-config.

Index

Examples

Constants

View Source
const (
	// DateZero is the ZERO of the sql date.
	DateZero = "0000-00-00"

	// TimeZero is the ZERO of the sql time.
	TimeZero = "00:00:00"

	// DateTimeZero is the ZERO of the sql datetime.
	DateTimeZero = "0000-00-00 00:00:00"
)
View Source
const SliceSep = ","

SliceSep is used to combine a string slice to a string.

Variables

View Source
var DefaultArgsCap = 32

DefaultArgsCap is the default capacity to be allocated for ArgsBuilder.

View Source
var DefaultBufferCap = 256

DefaultBufferCap is the default capacity to be allocated for buffer from pool.

View Source
var DefaultConfigs = []Config{MaxOpenConns(0), ConnMaxIdleTime(time.Minute * 5)}

DefaultConfigs is the default configs.

View Source
var DefaultDB = new(DB)

DefaultDB is the default global DB.

View Source
var DefaultDeletedAt = op.Key("deleted_at")
View Source
var DefaultDialect = MySQL

DefaultDialect is the default dialect.

View Source
var DefaultSliceCap = 16
View Source
var DefaultSqlCollector = NewSqlCollector()

DefaultSqlCollector is the default sql collector.

View Source
var Sep = "_"

Sep is the separator by the select struct.

Functions

func BindToMapBool added in v0.35.0

func BindToMapBool[M ~map[K]bool, K comparable](rows Rows, initcap int) (M, error)

BindToMapBool scans one column as key, and insert it with the value true into m.

NOTICE: It will close the rows.

func BindToMapEmptyStruct added in v0.35.0

func BindToMapEmptyStruct[M ~map[K]struct{}, K comparable](rows Rows, initcap int) (M, error)

BindToMapEmptyStruct scans one column as key, and insert it with the value struct{}{} into m.

NOTICE: It will close the rows.

func BindToMapKV added in v0.35.0

func BindToMapKV[M ~map[K]V, K comparable, V any](rows Rows, initcap int) (m M, err error)

BindToMapKV scans two columns as key and value, and inserts them into m.

NOTICE: It will close the rows.

func BuildOp added in v0.27.0

func BuildOp(ab *ArgsBuilder, op op.Op) string

BuildOp builds the operation.

func BuildOper added in v0.27.0

func BuildOper(ab *ArgsBuilder, op op.Oper) string

BuildOper is equal to BuildOp(ab, op.Operation()).

func CheckErrNoRows

func CheckErrNoRows(err error) (exist bool, e error)

CheckErrNoRows extracts the error sql.ErrNoRows as the bool, which returns

  • (true, nil) if err is equal to nil
  • (false, nil) if err is equal to sql.ErrNoRows
  • (false, err) if err is equal to others

func Count added in v0.30.0

func Count(field string) string

Count returns a COUNT(field).

func CountDistinct added in v0.30.0

func CountDistinct(field string) string

CountDistinct returns a COUNT(DISTINCT field).

func DecodeMap added in v0.39.0

func DecodeMap[M ~map[string]T, T any](m *M, src any) error

DecodeMap decodes a map from string or []byte.

func DecodeStrings added in v0.39.0

func DecodeStrings[S ~[]string](s *S, src any, sep string) error

DecodeStrings decodes a string slice from string or []byte.

func EncodeMap added in v0.39.0

func EncodeMap[M ~map[string]T, T any](m M) (string, error)

EncodeMap encodes a map to string.

func RegisterDialect

func RegisterDialect(dialect Dialect, force bool)

RegisterDialect registers the Dialect with the name.

If the name has been registered, it will panic. But you can set force to true to ignore it.

func RegisterOpBuilder added in v0.27.0

func RegisterOpBuilder(op string, builder OpBuilder)

RegisterOpBuilder registers the operation builder.

func ScanColumnsToStruct

func ScanColumnsToStruct(scan func(...any) error, columns []string, s any) (err error)

ScanColumnsToStruct scans the columns into the fields of the struct s, which supports the tag named "sql" to modify the field name.

If the value of the tag is "-", however, the field will be ignored. If the tag contains the attribute "notpropagate", for the embeded struct, do not scan the fields of the embeded struct.

func ScanRow

func ScanRow(scan func(dests ...any) error, dests ...any) error

ScanRow uses the function scan to scan the sql row into dests, which may be used as a proxy of the function sql.Row.Scan or sql.Rows.Scan.

If the dest value is the basic builtin types as follow, it will be wrapped to support the sql NULL and the converting from other types.

*time.Duration:
    string:    time.ParseDuration(src)
    []byte:    time.ParseDuration(string(src))
    int64:     time.Duration(src) * time.Millisecond
    float64:   time.Duration(src * float64(time.Second))
*time.Time:
    int64:     time.Unix(src, 0).In(Location)
    float64:   time.Unix(Integer, Fraction).In(Location)
    string:    time.ParseInLocation(DatetimeLayout, src, Location))
    []byte:    time.ParseInLocation(DatetimeLayout, string(src), Location))
    time.Time: src
*bool:
     bool:     src
     int64:    src!=0
     float64:  src!=0
     string:   strconv.ParseBool(src)
     []byte:
               len(src)==1: src[0] != '\x00'
               len(src)!=1: strconv.ParseBool(string(src))
*string:
    string:    src
    []byte:    string(src)
    bool:      "true" or "false"
    int64:     strconv.FormatInt(src, 10)
    float64:   strconv.FormatFloat(src, 'f', -1, 64)
    time.Time: src.In(Location).Format(DatetimeLayout)
*float32, *float64:
    bool:      true=>1, false=>0
    int64:     floatXX(src)
    float64:   floatXX(src)
    string:    strconv.ParseFloat(src, 64)
    []byte:    strconv.ParseFloat(string(src), 64)
*int, *int8, *int16, *int32, *int64:
	bool:      true=>1, false=>0
    int64:     intXX(src)
    float64:   intXX(src)
    string:    strconv.ParseInt(src, 10, 64)
    []byte:    strconv.ParseInt(string(src), 10, 64)
    time.Time: src.Unix() only for int/int64
*uint, *uint8, *uint16, *uint32, *uint64:
	bool:      true=>1, false=>0
    int64:     uintXX(src)
    float64:   uintXX(src)
    string:    strconv.ParseUint(src, 10, 64)
    []byte:    strconv.ParseUint(string(src), 10, 64)
    time.Time: src.Unix() only for uint/uint64

func SetConnURLLocation

func SetConnURLLocation(connURL string, loc *time.Location) string

SetConnURLLocation sets the argument "loc" in the connection url if missing.

If loc is nil, use Location instead.

func Sum added in v0.31.0

func Sum(field string) string

Sum returns a SUM(field).

func Today added in v0.35.0

func Today() time.Time

Today returns the today time, that's, 00:00:00 of the current day.

func TryBindToMapBool added in v0.35.0

func TryBindToMapBool[M ~map[K]bool, K comparable](rows Rows, err error, initcap int) (m M, e error)

TryBindToMapBool is the same as BindToMapBool, but calls it only if err==nil.

func TryBindToMapEmptyStruct added in v0.35.0

func TryBindToMapEmptyStruct[M ~map[K]struct{}, K comparable](rows Rows, err error, initcap int) (m M, e error)

TryBindToMapEmptyStruct is the same as BindToMapEmptyStruct, but calls it only if err==nil.

func TryBindToMapKV added in v0.35.0

func TryBindToMapKV[M ~map[K]V, K comparable, V any](rows Rows, err error, initcap int) (m M, e error)

TryBindToMapKV is the same as BindToMapKV, but calls it only if err==nil.

Types

type ArgsBuilder

type ArgsBuilder struct {
	Dialect
	// contains filtered or unexported fields
}

ArgsBuilder is used to build the arguments.

func GetArgsBuilderFromPool added in v0.34.0

func GetArgsBuilderFromPool(dialect Dialect) *ArgsBuilder

GetArgsBuilderFromPool acquires an ArgsBuilder with the dialect from pool.

func (*ArgsBuilder) Add

func (a *ArgsBuilder) Add(arg any) (placeholder string)

Add appends the argument and returns the its placeholder.

If arg is the type of sql.NamedArg, it will use @arg.Name as the placeholder and arg.Value as the value.

func (*ArgsBuilder) Args

func (a *ArgsBuilder) Args() (args []any)

Args returns the added arguments.

func (*ArgsBuilder) Release added in v0.34.0

func (a *ArgsBuilder) Release()

Release puts itself into the pool if it is acquired from the pool.

func (*ArgsBuilder) Reset added in v0.34.0

func (a *ArgsBuilder) Reset()

Reset resets the args to empty.

func (*ArgsBuilder) WithDialect added in v0.34.0

func (a *ArgsBuilder) WithDialect(dialect Dialect) *ArgsBuilder

WithDialect sets the dialect and returns itself.

type Base

type Base struct {
	Id int64 `sql:"id,omitempty" json:",omitempty"`

	CreatedAt time.Time `sql:"created_at,omitempty"`
	UpdatedAt time.Time `sql:"updated_at,omitempty"`
	DeletedAt time.Time `sql:"deleted_at,omitempty" json:"-"`
}

Base is the common columns of the sql table.

type Config

type Config func(db *sql.DB)

Config is used to configure the DB.

func ConnMaxIdleTime

func ConnMaxIdleTime(d time.Duration) Config

ConnMaxIdleTime returns a Config to set the maximum idle time of the connection.

func ConnMaxLifetime

func ConnMaxLifetime(d time.Duration) Config

ConnMaxLifetime returns a Config to set the maximum lifetime of the connection.

func MaxIdleConns

func MaxIdleConns(n int) Config

MaxIdleConns returns a Config to set the maximum number of the idle connection.

func MaxOpenConns

func MaxOpenConns(maxnum int) Config

MaxOpenConns returns a Config to set the maximum number of the open connection.

If maxnum is equal to 0, it is runtime.NumCPU()*2 by default.

type DB

type DB struct {
	Dialect
	Executor
	Interceptor
}

DB is the wrapper of the sql.DB.

func Open

func Open(driverName, dataSourceName string, configs ...Config) (*DB, error)

Open opens a database specified by its database driver name and a driver-specific data source name,

func (*DB) Delete

func (db *DB) Delete(tables ...string) *DeleteBuilder

Delete returns a DELETE SQL builder.

func (*DB) Exec added in v0.26.0

func (db *DB) Exec(query string, args ...any) (r sql.Result, err error)

Exec is equal to db.ExecContext(context.Background(), query, args...).

func (*DB) ExecContext

func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (r sql.Result, err error)

ExecContext executes the sql statement.

func (*DB) GetDialect added in v0.26.0

func (db *DB) GetDialect() Dialect

GetDialect returns the dialect of the db.

If not set, return DefaultDialect instead.

func (*DB) Insert

func (db *DB) Insert() *InsertBuilder

Insert returns a INSERT SQL builder.

func (*DB) Intercept added in v0.26.0

func (db *DB) Intercept(sql string, args []any) (string, []any, error)

func (*DB) NewTable

func (db *DB) NewTable(name string) Table

NewTable returns a new Table with the db.

func (*DB) Query added in v0.26.0

func (db *DB) Query(query string, args ...any) (rows *sql.Rows, err error)

Query is equal to db.QueryContext(context.Background(), query, args...).

func (*DB) QueryContext

func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (rows *sql.Rows, err error)

QueryContext executes the query sql statement.

func (*DB) QueryRow added in v0.26.0

func (db *DB) QueryRow(query string, args ...any) *sql.Row

QueryRow is equal to db.QueryRowContext(context.Background(), query, args...)

func (*DB) QueryRowContext

func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row

QueryRowContext executes the row query sql statement.

func (*DB) QueryRows added in v0.32.0

func (db *DB) QueryRows(query string, args ...any) (Rows, error)

QueryRows executes the query sql statement and returns Rows instead of *sql.Rows.

func (*DB) QueryRowsContext added in v0.32.0

func (db *DB) QueryRowsContext(ctx context.Context, query string, args ...any) (rows Rows, err error)

QueryRowsContext executes the query sql statement and returns Rows instead of *sql.Rows.

func (*DB) QueryRowx added in v0.32.0

func (db *DB) QueryRowx(query string, args ...any) Row

QueryRowx executes the row query sql statement and returns Row instead of *sql.Row.

func (*DB) QueryRowxContext added in v0.32.0

func (db *DB) QueryRowxContext(ctx context.Context, query string, args ...any) Row

QueryRowxContext executes the row query sql statement and returns Row instead of *sql.Row.

func (*DB) Reset added in v0.37.0

func (db *DB) Reset(other *DB)

Set resets the current db to other.

func (*DB) Select

func (db *DB) Select(column string) *SelectBuilder

Select is equal todb.SelectAlias(column, "").

func (*DB) SelectAlias added in v0.27.0

func (db *DB) SelectAlias(column, alias string) *SelectBuilder

SelectAlias is equal to SelectAlias(column, alias).

func (*DB) SelectStruct

func (db *DB) SelectStruct(s any) *SelectBuilder

SelectStruct is equal to db.SelectStructWithTable(s, "").

func (*DB) SelectStructWithTable added in v0.27.0

func (db *DB) SelectStructWithTable(s any, table string) *SelectBuilder

SelectStructWithTable is equal to SelectStructWithTable(s, table...).

func (*DB) Selects

func (db *DB) Selects(columns ...string) *SelectBuilder

Selects is equal to db.Select(columns[0]).Select(columns[1])...

func (*DB) Update

func (db *DB) Update(table ...string) *UpdateBuilder

Update returns a UPDATE SQL builder.

type DeleteBuilder

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

DeleteBuilder is used to build the DELETE statement.

Example
// No Where
delete1 := Delete().From("table")

// With Where
delete2 := Delete().From("table").
	Where(
		op.Greater("c1", 123),
		op.IsNotNull("c2"),
	).
	Where(
		op.Or(
			op.Less("c3", 456),
			op.In("c4", []string{"a", "b"}),
		),
	)

sql1, args1 := delete1.Build() // Use the default dialect.
sql2, args2 := delete2.Build() // Use the PostgreSQL dialect.

fmt.Println(sql1)
fmt.Println(args1.Args())
fmt.Println(sql2)
fmt.Println(args2.Args())
Output:

DELETE FROM `table`
[]
DELETE FROM `table` WHERE (`c1`>? AND `c2` IS NOT NULL AND (`c3`<? OR `c4` IN (?, ?)))
[123 456 a b]

func Delete

func Delete(tables ...string) *DeleteBuilder

Delete is short for NewDeleteBuilder.

func NewDeleteBuilder

func NewDeleteBuilder(tables ...string) *DeleteBuilder

NewDeleteBuilder returns a new DELETE builder.

func (*DeleteBuilder) Build

func (b *DeleteBuilder) Build() (sql string, args *ArgsBuilder)

Build builds the DELETE FROM TABLE sql statement.

func (*DeleteBuilder) Comment added in v0.37.0

func (b *DeleteBuilder) Comment(comment string) *DeleteBuilder

Comment set the comment, which will be appended to the end of the built SQL statement.

func (*DeleteBuilder) Exec

func (b *DeleteBuilder) Exec() (sql.Result, error)

Exec builds the sql and executes it by *sql.DB.

func (*DeleteBuilder) ExecContext

func (b *DeleteBuilder) ExecContext(ctx context.Context) (sql.Result, error)

ExecContext builds the sql and executes it by *sql.DB.

func (*DeleteBuilder) From

func (b *DeleteBuilder) From(table string, alias ...string) *DeleteBuilder

From is equal to b.FromAlias(table, "").

func (*DeleteBuilder) FromAlias added in v0.27.0

func (b *DeleteBuilder) FromAlias(table string, alias string) *DeleteBuilder

From appends the "FROM table AS alias" statement.

If alias is empty, use "FROM table" instead.

func (*DeleteBuilder) JoinFull

func (b *DeleteBuilder) JoinFull(table, alias string, ons ...JoinOn) *DeleteBuilder

JoinFull appends the "FULL JOIN table ON on..." statement.

func (*DeleteBuilder) JoinFullOuter

func (b *DeleteBuilder) JoinFullOuter(table, alias string, ons ...JoinOn) *DeleteBuilder

JoinFullOuter appends the "FULL OUTER JOIN table ON on..." statement.

func (*DeleteBuilder) JoinLeft

func (b *DeleteBuilder) JoinLeft(table, alias string, ons ...JoinOn) *DeleteBuilder

JoinLeft appends the "LEFT JOIN table ON on..." statement.

func (*DeleteBuilder) JoinLeftOuter

func (b *DeleteBuilder) JoinLeftOuter(table, alias string, ons ...JoinOn) *DeleteBuilder

JoinLeftOuter appends the "LEFT OUTER JOIN table ON on..." statement.

func (*DeleteBuilder) JoinRight

func (b *DeleteBuilder) JoinRight(table, alias string, ons ...JoinOn) *DeleteBuilder

JoinRight appends the "RIGHT JOIN table ON on..." statement.

func (*DeleteBuilder) JoinRightOuter

func (b *DeleteBuilder) JoinRightOuter(table, alias string, ons ...JoinOn) *DeleteBuilder

JoinRightOuter appends the "RIGHT OUTER JOIN table ON on..." statement.

func (*DeleteBuilder) SetDB

func (b *DeleteBuilder) SetDB(db *DB) *DeleteBuilder

SetDB sets the db.

func (*DeleteBuilder) String

func (b *DeleteBuilder) String() string

String is the same as b.Build(), except args.

func (*DeleteBuilder) Table

func (b *DeleteBuilder) Table(table string) *DeleteBuilder

Table appends the table name to delete the rows from it.

func (*DeleteBuilder) Where

func (b *DeleteBuilder) Where(andConditions ...op.Condition) *DeleteBuilder

Where sets the "WHERE" conditions.

func (*DeleteBuilder) WhereNamedArgs

func (b *DeleteBuilder) WhereNamedArgs(andArgs ...sql.NamedArg) *DeleteBuilder

WhereNamedArgs is the same as Where, but uses the NamedArg as the condition.

type Dialect

type Dialect interface {
	// Name returns the name of the dialect.
	Name() string

	// Placeholder returns the format of the ith argument,
	// such as "?" for MySQL and "$i" for PostgreSQL.
	//
	// Notice: i starts with 1.
	Placeholder(i int) string

	// Quote returns the quotation format of sql string,
	// such as `s` for MySQL and "s" for PostgreSQL.
	Quote(s string) string

	// LimitOffset returns the LIMIT OFFSET statement,
	// such as "LIMIT n" or "LIMIT n OFFSET m" for MySQL and PostgreSQL.
	LimitOffset(limit, offset int64) string
}

Dialect represents a dialect of the SQL.

var (
	MySQL    Dialect = dialect{mysqlDialect}
	Sqlite3  Dialect = dialect{sqlite3Dialect}
	Postgres Dialect = dialect{pqDialect}
)

Predefine some dialects.

func GetDialect

func GetDialect(name string) Dialect

GetDialect returns the dialect named name. Return nil instead if not exist.

type Executor

type Executor interface {
	io.Closer

	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Executor is used to execute the sql statement.

type InsertBuilder

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

InsertBuilder is used to build the INSERT statement.

Example
// Single Value
insert1 := Insert().Into("table").Columns("c1", "c2", "c3").
	Values("v1", "v2", "v3")

// Many Values
insert2 := Insert().Into("table").Columns("c1", "c2", "c3").
	Values("v1", "v2", "v3").
	Values("v4", "v5", "v6").
	Values("v7", "v8", "v9")

// No Value, which will build a single value placeholder.
insert3 := Insert().Into("table").Columns("c1", "c2", "c3")

// No Column
insert4 := Insert().Into("table").Values("v1", "v2", "v3")
insert5 := Insert().Into("table").Values("v11", "v12").Values("v21", "v22")

sql1, args1 := insert1.SetDB(&DB{Dialect: Postgres}).Build() // Use the PostgreSQL dialect.
sql2, args2 := insert2.SetDB(&DB{Dialect: Postgres}).Build() // Use the PostgreSQL dialect.
sql3, args3 := insert3.Build()                               // Use the default dialect.
sql4, args4 := insert4.Build()                               // Use the default dialect.
sql5, args5 := insert5.Build()                               // Use the default dialect.

fmt.Println(sql1)
fmt.Println(args1.Args())

fmt.Println(sql2)
fmt.Println(args2.Args())

fmt.Println(sql3)
fmt.Println(args3.Args())

fmt.Println(sql4)
fmt.Println(args4.Args())

fmt.Println(sql5)
fmt.Println(args5.Args())
Output:

INSERT INTO "table" ("c1", "c2", "c3") VALUES ($1, $2, $3)
[v1 v2 v3]
INSERT INTO "table" ("c1", "c2", "c3") VALUES ($1, $2, $3), ($4, $5, $6), ($7, $8, $9)
[v1 v2 v3 v4 v5 v6 v7 v8 v9]
INSERT INTO `table` (`c1`, `c2`, `c3`) VALUES (?, ?, ?)
[]
INSERT INTO `table` VALUES (?, ?, ?)
[v1 v2 v3]
INSERT INTO `table` VALUES (?, ?), (?, ?)
[v11 v12 v21 v22]

func Insert

func Insert() *InsertBuilder

Insert is short for NewInsertBuilder.

func NewInsertBuilder

func NewInsertBuilder() *InsertBuilder

NewInsertBuilder returns a new INSERT builder.

func (*InsertBuilder) Build

func (b *InsertBuilder) Build() (sql string, args *ArgsBuilder)

Build builds the INSERT INTO TABLE sql statement.

func (*InsertBuilder) Columns

func (b *InsertBuilder) Columns(columns ...string) *InsertBuilder

Columns sets the inserted columns.

func (*InsertBuilder) Comment added in v0.37.0

func (b *InsertBuilder) Comment(comment string) *InsertBuilder

Comment set the comment, which will be appended to the end of the built SQL statement.

func (*InsertBuilder) Exec

func (b *InsertBuilder) Exec() (sql.Result, error)

Exec builds the sql and executes it by *sql.DB.

func (*InsertBuilder) ExecContext

func (b *InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error)

ExecContext builds the sql and executes it by *sql.DB.

func (*InsertBuilder) IgnoreInto

func (b *InsertBuilder) IgnoreInto(table string) *InsertBuilder

IgnoreInto sets the table name with "INSERT IGNORE INTO".

func (*InsertBuilder) Into

func (b *InsertBuilder) Into(table string) *InsertBuilder

Into sets the table name with "INSERT INTO".

func (*InsertBuilder) NamedValues

func (b *InsertBuilder) NamedValues(nvs ...sql.NamedArg) *InsertBuilder

NamedValues is the same as Values. But it will set it if the columns are not set.

Example
v1 := sql.Named("column1", "value1")
v2 := sql.Named("column2", "value2")
v3 := sql.Named("column3", "value3")

insert := Insert().Into("table").NamedValues(v1, v2, v3)
sql, args := insert.Build()

fmt.Println(sql)
fmt.Println(args.Args())
Output:

INSERT INTO `table` (`column1`, `column2`, `column3`) VALUES (?, ?, ?)
[value1 value2 value3]

func (*InsertBuilder) Ops added in v0.27.0

func (b *InsertBuilder) Ops(ops ...op.Op) *InsertBuilder

Ops is the same as Values. But it will set it if the columns are not set.

func (*InsertBuilder) ReplaceInto

func (b *InsertBuilder) ReplaceInto(table string) *InsertBuilder

ReplaceInto sets the table name with "REPLACE INTO".

REPLACE INTO is a MySQL extension to the SQL standard.

func (*InsertBuilder) SetDB

func (b *InsertBuilder) SetDB(db *DB) *InsertBuilder

SetDB sets the db.

func (*InsertBuilder) String

func (b *InsertBuilder) String() string

String is the same as b.Build(), except args.

func (*InsertBuilder) Struct

func (b *InsertBuilder) Struct(s any) *InsertBuilder

Struct is the same as NamedValues, but extracts the fields of the struct as the named values to be inserted, which supports the tag named "sql" to modify the column name.

  1. If the value of the tag is "-", however, the field will be ignored.
  2. If the tag value contains "omitempty", the ZERO field will be ignored.
  3. If the tag contains the attribute "notpropagate", for the embeded struct, do not scan the fields of the embeded struct.
Example
type S struct {
	DefaultField  string
	ModifiedField string `sql:"field"`
	ZeroField     string `sql:",omitempty"`
	IgnoredField  string `sql:"-"`
}

s := S{DefaultField: "v1", IgnoredField: "v2"}
insert := Insert().Into("table").Struct(s)
sql, args := insert.Build()

fmt.Println(sql)
fmt.Println(args.Args())
Output:

INSERT INTO `table` (`DefaultField`, `field`) VALUES (?, ?)
[v1 ]

func (*InsertBuilder) Values

func (b *InsertBuilder) Values(values ...any) *InsertBuilder

Values appends the inserted values.

type Interceptor

type Interceptor interface {
	Intercept(sql string, args []any) (string, []any, error)
}

Interceptor is used to intercept the executed sql statement and arguments and return a new one.

type InterceptorFunc added in v0.26.0

type InterceptorFunc func(sql string, args []any) (string, []any, error)

InterceptorFunc is an interceptor function.

func (InterceptorFunc) Intercept added in v0.26.0

func (f InterceptorFunc) Intercept(sql string, args []any) (string, []any, error)

Intercept implements the interface Interceptor.

type Interceptors added in v0.36.0

type Interceptors []Interceptor

Interceptors is a set of Interceptors.

func (Interceptors) Intercept added in v0.36.0

func (is Interceptors) Intercept(sql string, args []any) (string, []any, error)

Intercept implements the interface Interceptor.

type JoinOn

type JoinOn struct {
	Left  string
	Right string
}

JoinOn is the join on statement.

func On

func On(left, right string) JoinOn

On returns a JoinOn instance.

type Map added in v0.39.0

type Map[T any] map[string]T

Map is a map value type, which is encoded to a string or decoded from a []byte or string.

func (*Map[T]) Scan added in v0.39.0

func (m *Map[T]) Scan(src any) error

Scan implements the interface sql.Scanner to scan a sql value to the map.

func (Map[T]) Value added in v0.39.0

func (m Map[T]) Value() (driver.Value, error)

Value implements the interface driver.Valuer to encode the map to a sql value(string).

type OpBuilder added in v0.27.0

type OpBuilder interface {
	Build(*ArgsBuilder, op.Op) string
}

OpBuilder is an operation builder to build a sql statement based on op.

func GetOpBuilder added in v0.27.0

func GetOpBuilder(op string) OpBuilder

GetOpBuilder returns the op builder by the op.

Return nil instead if no the op builder.

type OpBuilderFunc added in v0.27.0

type OpBuilderFunc func(ab *ArgsBuilder, op op.Op) string

OpBuilderFunc is a operation build function.

func (OpBuilderFunc) Build added in v0.27.0

func (f OpBuilderFunc) Build(ab *ArgsBuilder, op op.Op) string

Build implements the interface OpBuilder.

type Opener

type Opener func(driverName, dataSourceName string) (*sql.DB, error)

Opener is used to open a *sql.DB.

var DefaultOpener Opener = sql.Open

DefaultOpener is used to open a *sql.DB.

type Oper added in v0.34.0

type Oper[T any] struct {
	Table Table

	// SoftCondition is used by the method SoftXxxx as the WHERE condition.
	//
	// Default: op.IsNotDeletedCond
	SoftCondition op.Condition

	// SoftDeleteUpdater is used by SoftDelete to delete the records.
	//
	// Default: op.KeyDeletedAt.Set(time.Now())
	SoftDeleteUpdater func(context.Context) op.Updater
}

Oper is used to collect a set of SQL DML & DQL operations based on a table.

func NewOper added in v0.34.0

func NewOper[T any](table string) Oper[T]

NewOper returns a new Oper with the table name.

func NewOperWithTable added in v0.34.0

func NewOperWithTable[T any](table Table) Oper[T]

NewOperWithTable returns a new Oper with the table.

func (Oper[T]) Add added in v0.34.0

func (o Oper[T]) Add(obj T) (err error)

Add is equal to o.AddContext(context.Background(), obj).

func (Oper[T]) AddContext added in v0.34.0

func (o Oper[T]) AddContext(ctx context.Context, obj T) (err error)

AddContext inserts the struct as the record into the sql table.

func (Oper[T]) AddContextWithId added in v0.34.0

func (o Oper[T]) AddContextWithId(ctx context.Context, obj T) (id int64, err error)

AddContextWithId is the same as AddContext, but also returns the inserted id.

func (Oper[T]) AddWithId added in v0.34.0

func (o Oper[T]) AddWithId(obj T) (id int64, err error)

AddWithId is equal to o.AddContextWithId(context.Background(), obj).

func (Oper[T]) Count added in v0.34.0

func (o Oper[T]) Count(conds ...op.Condition) (total int, err error)

Count is equal to o.CountContext(context.Background(), conds...).

func (Oper[T]) CountContext added in v0.35.0

func (o Oper[T]) CountContext(ctx context.Context, conds ...op.Condition) (total int, err error)

CountContext is used to count the number of records by the condition.

func (Oper[T]) CountDistinct added in v0.34.0

func (o Oper[T]) CountDistinct(field string, conds ...op.Condition) (total int, err error)

CountDistinct is equal to o.CountDistinctContext(context.Background(), field, conds...).

func (Oper[T]) CountDistinctContext added in v0.35.0

func (o Oper[T]) CountDistinctContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)

CountDistinctContext is the same as Count, but excluding the same field records.

func (Oper[T]) Delete added in v0.34.0

func (o Oper[T]) Delete(conds ...op.Condition) (err error)

Delete is equal to o.DeleteContext(context.Background(), conds...).

func (Oper[T]) DeleteById added in v0.36.0

func (o Oper[T]) DeleteById(id int64) error

DeleteById is equal to o.Delete(op.KeyId.Eq(id)).

func (Oper[T]) DeleteContext added in v0.34.0

func (o Oper[T]) DeleteContext(ctx context.Context, conds ...op.Condition) error

DeleteContext executes a DELETE statement to delete the records from table.

func (Oper[T]) Exist added in v0.34.0

func (o Oper[T]) Exist(conds ...op.Condition) (exist bool, err error)

Exist is equal to o.ExistContext(context.Background(), conds...).

func (Oper[T]) ExistContext added in v0.35.0

func (o Oper[T]) ExistContext(ctx context.Context, conds ...op.Condition) (exist bool, err error)

ExistContext is used to check whether the records qualified by the conditions exist.

func (Oper[T]) Get added in v0.34.0

func (o Oper[T]) Get(sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)

Get is equal to o.GetContext(context.Background(), sort, conds...).

func (Oper[T]) GetById added in v0.36.0

func (o Oper[T]) GetById(id int64) (v T, ok bool, err error)

GetById is equal to o.Get(nil, op.KeyId.Eq(id)).

func (Oper[T]) GetContext added in v0.34.0

func (o Oper[T]) GetContext(ctx context.Context, sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)

GetContext just queries a first record from table.

func (Oper[T]) GetRow added in v0.36.0

func (o Oper[T]) GetRow(ctx context.Context, columns any, sort op.Sorter, conds ...op.Condition) Row

GetRow is equal to o.GetRowContext(ctx, columns, sort, conds...).

func (Oper[T]) GetRowContext added in v0.36.0

func (o Oper[T]) GetRowContext(ctx context.Context, columns any, sort op.Sorter, conds ...op.Condition) Row

GetRowContext builds a SELECT statement and returns a Row.

func (Oper[T]) GetRows added in v0.35.0

func (o Oper[T]) GetRows(columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (Rows, error)

GetRows is equal to o.GetRowsContext(context.Background(), columns, sort, page, conds...).

func (Oper[T]) GetRowsContext added in v0.35.0

func (o Oper[T]) GetRowsContext(ctx context.Context, columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (rows Rows, err error)

GetRowsContext builds a SELECT statement and returns a Rows.

func (Oper[T]) Gets added in v0.34.0

func (o Oper[T]) Gets(sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)

Gets is equal to o.GetsContext(context.Background(), sort, page, conds...).

func (Oper[T]) GetsContext added in v0.34.0

func (o Oper[T]) GetsContext(ctx context.Context, sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)

GetsContext queries a set of results from table.

Any of sort, page and conds is equal to nil.

func (Oper[T]) MakeSlice added in v0.34.0

func (o Oper[T]) MakeSlice(cap int64) []T

MakeSlice makes a slice with the cap.

If cap is equal to 0, use DefaultSliceCap instead.

func (Oper[T]) Query added in v0.36.0

func (o Oper[T]) Query(page, pageSize int64, conds ...op.Condition) ([]T, error)

Query is equal to o.QueryContext(context.Background(), page, pageSize, conds...).

func (Oper[T]) QueryContext added in v0.36.0

func (o Oper[T]) QueryContext(ctx context.Context, page, pageSize int64, conds ...op.Condition) ([]T, error)

QueryContext is a simplified GetsContext, which is equal to

o.GetsContext(ctx, op.KeyId.OrderDesc(), op.Paginate(page, pageSize), conds...)

page starts with 1. And if page or pageSize is less than 1, ignore the pagination.

func (Oper[T]) Select added in v0.36.0

func (o Oper[T]) Select(columns any, conds ...op.Condition) *SelectBuilder

Select returns a SELECT builder, which sets the selected columns and the where condtions.

columns supports one of types as follow:

string
[]string
struct

func (Oper[T]) SoftCount added in v0.34.0

func (o Oper[T]) SoftCount(conds ...op.Condition) (total int, err error)

SoftCount is equal to o.SoftCountContext(context.Background(), conds...).

func (Oper[T]) SoftCountContext added in v0.36.0

func (o Oper[T]) SoftCountContext(ctx context.Context, conds ...op.Condition) (total int, err error)

SoftCountContext is the same as CountContext, but appending SoftCondition into the conditions.

func (Oper[T]) SoftCountDistinct added in v0.34.0

func (o Oper[T]) SoftCountDistinct(field string, conds ...op.Condition) (total int, err error)

SoftCountDistinct is equal to o.SoftCountDistinctContext(context.Background(), field, conds...).

func (Oper[T]) SoftCountDistinctContext added in v0.36.0

func (o Oper[T]) SoftCountDistinctContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)

SoftCountDistinctContext is the same as CountDistinctContext, but appending SoftCondition into the conditions.

func (Oper[T]) SoftDelete added in v0.34.0

func (o Oper[T]) SoftDelete(conds ...op.Condition) error

SoftDelete is equal to o.SoftDeleteContext(context.Background(), conds...).

func (Oper[T]) SoftDeleteById added in v0.34.0

func (o Oper[T]) SoftDeleteById(id int64) error

SoftDeleteById is equal to o.SoftDelete(op.KeyId.Eq(id)).

func (Oper[T]) SoftDeleteContext added in v0.34.0

func (o Oper[T]) SoftDeleteContext(ctx context.Context, conds ...op.Condition) error

SoftDeleteContext soft deletes the records from the table, which only marks the records deleted.

func (Oper[T]) SoftExist added in v0.34.0

func (o Oper[T]) SoftExist(conds ...op.Condition) (exist bool, err error)

SoftExist is equal to o.SoftExistContext(context.Background(), conds... ).

func (Oper[T]) SoftExistContext added in v0.36.0

func (o Oper[T]) SoftExistContext(ctx context.Context, conds ...op.Condition) (exist bool, err error)

SoftExistContext is the same as ExistContext, but appending SoftCondition into the conditions.

func (Oper[T]) SoftGet added in v0.34.0

func (o Oper[T]) SoftGet(sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)

SoftGet is equal to o.SoftGetContext(context.Background(), sort, conds...).

func (Oper[T]) SoftGetById added in v0.34.0

func (o Oper[T]) SoftGetById(id int64) (v T, ok bool, err error)

SoftGetById is equal to o.SoftGet(nil, op.KeyId.Eq(id)).

func (Oper[T]) SoftGetContext added in v0.34.0

func (o Oper[T]) SoftGetContext(ctx context.Context, sort op.Sorter, conds ...op.Condition) (obj T, ok bool, err error)

SoftGetContext is the same as GetContext, but appending SoftCondition into the conditions.

func (Oper[T]) SoftGetRows added in v0.35.0

func (o Oper[T]) SoftGetRows(columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (Rows, error)

SoftGetRows is equal to o.SoftGetRowsContext(context.Background(), columns, sort, page, conds...).

func (Oper[T]) SoftGetRowsContext added in v0.35.0

func (o Oper[T]) SoftGetRowsContext(ctx context.Context, columns any, sort op.Sorter, page op.Paginator, conds ...op.Condition) (Rows, error)

SoftGetRowsContext is the same as GetRowsContext, but appending SoftCondition into the conditions.

func (Oper[T]) SoftGets added in v0.34.0

func (o Oper[T]) SoftGets(sort op.Sorter, page op.Paginator, conds ...op.Condition) ([]T, error)

SoftGets is equal to o.SoftGetsContext(context.Background(), sort, page, conds...).

func (Oper[T]) SoftGetsContext added in v0.34.0

func (o Oper[T]) SoftGetsContext(ctx context.Context, sort op.Sorter, page op.Paginator, conds ...op.Condition) ([]T, error)

SoftGetsContext is the same as GetsContext, but appending SoftCondition into the conditions.

func (Oper[T]) SoftQuery added in v0.34.0

func (o Oper[T]) SoftQuery(page, pageSize int64, conds ...op.Condition) ([]T, error)

SoftQuery is equal to o.SoftQueryContext(context.Background(), page, pageSize, conds...).

func (Oper[T]) SoftQueryContext added in v0.36.0

func (o Oper[T]) SoftQueryContext(ctx context.Context, page, pageSize int64, conds ...op.Condition) ([]T, error)

SoftQueryContext is the same as QueryContext, but appending SoftCondition into the conditions.

func (Oper[T]) SoftSelect added in v0.36.0

func (o Oper[T]) SoftSelect(columns any, conds ...op.Condition) *SelectBuilder

SoftSelect is the same as Select, but appends SoftCondition into the conditions.

func (Oper[T]) SoftSum added in v0.35.0

func (o Oper[T]) SoftSum(field string, conds ...op.Condition) (total int, err error)

SoftSum is equal to o.SoftSumContext(context.Background(), field, conds...).

func (Oper[T]) SoftSumContext added in v0.36.0

func (o Oper[T]) SoftSumContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)

SoftSumContext is the same as SumContext, but appending SoftCondition into the conditions.

func (Oper[T]) SoftUpdate added in v0.34.0

func (o Oper[T]) SoftUpdate(updater op.Updater, conds ...op.Condition) (err error)

SoftUpdate is equal to o.SoftUpdateContext(context.Background(), updater, conds...).

func (Oper[T]) SoftUpdateById added in v0.34.0

func (o Oper[T]) SoftUpdateById(id int64, updaters ...op.Updater) error

SoftUpdateById is equal to o.SoftUpdate(op.Batch(updaters...), op.KeyId.Eq(id)).

func (Oper[T]) SoftUpdateContext added in v0.34.0

func (o Oper[T]) SoftUpdateContext(ctx context.Context, updater op.Updater, conds ...op.Condition) error

SoftUpdateContext is the same as UpdateContext, but appending SoftCondition into the conditions.

func (Oper[T]) Sum added in v0.35.0

func (o Oper[T]) Sum(field string, conds ...op.Condition) (int, error)

Sum is equal to o.SumContext(context.Background(), field, conds...).

func (Oper[T]) SumContext added in v0.35.0

func (o Oper[T]) SumContext(ctx context.Context, field string, conds ...op.Condition) (total int, err error)

SumContext is used to sum the field values of the records by the condition.

func (Oper[T]) Update added in v0.34.0

func (o Oper[T]) Update(updater op.Updater, conds ...op.Condition) error

Update is equal to o.UpdateContext(context.Background(), updater, conds...).

func (Oper[T]) UpdateById added in v0.36.0

func (o Oper[T]) UpdateById(id int64, updaters ...op.Updater) error

UpdateById is equal to o.Update(op.Batch(updaters...), op.KeyId.Eq(id)).

func (Oper[T]) UpdateContext added in v0.34.0

func (o Oper[T]) UpdateContext(ctx context.Context, updater op.Updater, conds ...op.Condition) error

UpdateContext updates the sql table records.

If updater is nil, do nothing.

func (Oper[T]) WithDB added in v0.34.0

func (o Oper[T]) WithDB(db *DB) Oper[T]

WithDB returns a new Oper with the new db.

func (Oper[T]) WithSoftCondition added in v0.34.0

func (o Oper[T]) WithSoftCondition(softcond op.Condition) Oper[T]

WithSoftCondition returns a new Oper with the soft condition.

func (Oper[T]) WithSoftDeleteUpdater added in v0.34.0

func (o Oper[T]) WithSoftDeleteUpdater(softDeleteUpdater func(context.Context) op.Updater) Oper[T]

WithSoftDeleteUpdater returns a new Oper with the soft delete udpater.

func (Oper[T]) WithTable added in v0.34.0

func (o Oper[T]) WithTable(table Table) Oper[T]

WithTable returns the a new Oper with the new table.

type Operation added in v0.27.0

type Operation[T any] struct {
	Table

	// EnableUpdater is used by Enable to enable the table records.
	//
	// Default: op.KeyIsDisabled.Set(0)
	EnableUpdater op.Updater

	// DisableUpdater is used by Disable to disable the table records.
	//
	// Default: op.KeyIsDisabled.Set(1)
	DisableUpdater op.Updater

	// SoftDeleteUpdater is used by DeleteUpdateContext to delete the records.
	//
	// Default: DefaultDeletedAt.Set(time.Now())
	SoftDeleteUpdater func(context.Context) op.Updater
}

Operation is used to manage a set of operations.

DEPRECATED!!! Please use Oper instead.

func NewOperation added in v0.27.0

func NewOperation[T any](table string) Operation[T]

NewOperation returns a new operation with the table name.

func NewOperationWithTable added in v0.27.0

func NewOperationWithTable[T any](table Table) Operation[T]

NewOperationWithTable returns a new operation with the table.

func (Operation[T]) Add added in v0.27.0

func (o Operation[T]) Add(obj T) (err error)

Add is equal to o.AddContext(context.Background(), obj).

func (Operation[T]) AddContext added in v0.27.0

func (o Operation[T]) AddContext(ctx context.Context, obj T) (err error)

AddContext inserts the struct as the record into the sql table.

func (Operation[T]) AddContextWithId added in v0.27.0

func (o Operation[T]) AddContextWithId(ctx context.Context, obj T) (id int64, err error)

AddContextWithId is the same as AddContext, but also returns the inserted id.

func (Operation[T]) AddWithId added in v0.32.0

func (o Operation[T]) AddWithId(obj T) (id int64, err error)

AddWithId is equal to o.AddContextWithId(context.Background(), obj).

func (Operation[T]) Count added in v0.33.0

func (o Operation[T]) Count(conds ...op.Condition) (total int, err error)

Count is a simple convenient function to count the number of table records, which is equal to

o.Select(Count("*")).Where(conds...).Where(op.IsNotDeletedCond).BindRow(&total)

func (Operation[T]) CountDistinct added in v0.33.0

func (o Operation[T]) CountDistinct(field string, conds ...op.Condition) (total int, err error)

CountDistinct is a simple convenient function to count the number of table records with the distinct field, which is equal to

o.Select(CountDistinct(field)).Where(conds...).Where(op.IsNotDeletedCond).BindRow(&total)

func (Operation[T]) DeleteById added in v0.33.0

func (o Operation[T]) DeleteById(id int64) error

DeleteById is a simple convenient function to delete the table records by the primary key id, which is equal to

o.UpdateRemove(op.KeyId.Eq(id), op.IsNotDeletedCond)

func (Operation[T]) DisableById added in v0.33.0

func (o Operation[T]) DisableById(id int64) (err error)

DisableById is a simple convenient function to disable a table record by the primary key id, which is equal to

o.Update(o.DisableUpdater, op.KeyId.Eq(id), op.IsNotDeletedCond)

func (Operation[T]) EnableById added in v0.33.0

func (o Operation[T]) EnableById(id int64) (err error)

EnableById is a simple convenient function to enable a table record by the primary key id, which is equal to

o.Update(o.EnableUpdater, op.KeyId.Eq(id), op.IsNotDeletedCond)

func (Operation[T]) Exist added in v0.34.0

func (o Operation[T]) Exist(conds ...op.Condition) (exist bool, err error)

func (Operation[T]) Get added in v0.27.0

func (o Operation[T]) Get(conds ...op.Condition) (obj T, ok bool, err error)

Get is equal to o.GetContext(context.Background(), conds...).

func (Operation[T]) GetById added in v0.33.0

func (o Operation[T]) GetById(id int64) (v T, ok bool, err error)

GetById is a simple convenient function to query a table record by the primary key id, which is equal to

o.Get(op.KeyId.Eq(id), op.IsNotDeletedCond)

func (Operation[T]) GetContext added in v0.27.0

func (o Operation[T]) GetContext(ctx context.Context, conds ...op.Condition) (obj T, ok bool, err error)

GetContext just queries a result.

func (Operation[T]) Gets added in v0.27.0

func (o Operation[T]) Gets(sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)

Gets is equal to o.GetsContext(context.Background(), sort, page, conds...).

func (Operation[T]) GetsContext added in v0.27.0

func (o Operation[T]) GetsContext(ctx context.Context, sort op.Sorter, page op.Paginator, conds ...op.Condition) (objs []T, err error)

GetsContext queyies a set of results.

Any of sort, page and conds is equal to nil.

func (Operation[T]) MakeSlice added in v0.27.0

func (o Operation[T]) MakeSlice(cap int64) []T

MakeSlice makes a slice with the cap.

If cap is equal to 0, use DefaultSliceCap instead.

func (Operation[T]) Query added in v0.33.0

func (o Operation[T]) Query(page, pageSize int64, conds ...op.Condition) ([]T, error)

Query is a simple convenient function to query the table records with the pagination, which is equal to

o.Gets(op.KeyId.OrderDesc(), op.Paginate(page, pageSize), op.And(conds...), op.IsNotDeletedCond)

page starts with 1.

func (Operation[T]) Remove added in v0.27.0

func (o Operation[T]) Remove(conds ...op.Condition) (err error)

Remove is equal to o.RemoveContext(context.Background(), conds...).

func (Operation[T]) RemoveContext added in v0.27.0

func (o Operation[T]) RemoveContext(ctx context.Context, conds ...op.Condition) (err error)

RemoveContext deletes some records from the sql table.

func (Operation[T]) Update added in v0.27.0

func (o Operation[T]) Update(updater op.Updater, conds ...op.Condition) error

Update is equal to o.UpdateContext(context.Background(), updater, conds...).

func (Operation[T]) UpdateById added in v0.33.0

func (o Operation[T]) UpdateById(id int64, updaters ...op.Updater) error

UpdateById is a simple convenient function to update the table records by the primary key id, which is equal to

o.Update(op.Batch(updaters...), op.KeyId.Eq(id), op.IsNotDeletedCond)

func (Operation[T]) UpdateContext added in v0.27.0

func (o Operation[T]) UpdateContext(ctx context.Context, updater op.Updater, conds ...op.Condition) error

UpdateContext updates the sql table records.

func (Operation[T]) UpdateRemove added in v0.27.0

func (o Operation[T]) UpdateRemove(conds ...op.Condition) (err error)

UpdateRemove is equal to o.UpdateRemoveContext(context.Background(), conds...).

func (Operation[T]) UpdateRemoveContext added in v0.27.0

func (o Operation[T]) UpdateRemoveContext(ctx context.Context, conds ...op.Condition) (err error)

UpdateRemoveContext is the same as RemoveContext, but uses soft delete instead.

func (Operation[T]) WithDB added in v0.27.0

func (o Operation[T]) WithDB(db *DB) Operation[T]

WithDB returns a new operation with the new db.

func (Operation[T]) WithSoftDeleteUpdater added in v0.27.0

func (o Operation[T]) WithSoftDeleteUpdater(softDeleteUpdater func(context.Context) op.Updater) Operation[T]

WithSoftDeleteUpdater returns a new operation with the soft delete udpater.

func (Operation[T]) WithTable added in v0.27.0

func (o Operation[T]) WithTable(table Table) Operation[T]

WithTable returns the a new operation with the new table.

type Order

type Order string

Order represents the order used by ORDER BY.

const (
	Asc  Order = "ASC"
	Desc Order = "DESC"
)

Predefine some orders used by ORDER BY.

type Row

type Row struct {
	Columns []string // Only used by ScanStruct
	*sql.Row
}

Row is used to wrap sql.Row.

func NewRow

func NewRow(row *sql.Row, columns ...string) Row

NewRow returns a new Row.

func (Row) Bind added in v0.35.0

func (r Row) Bind(dests ...any) (ok bool, err error)

Bind is the same as Scan, but returns (false, nil) if Scan returns sql.ErrNoRows.

func (Row) BindStruct added in v0.35.0

func (r Row) BindStruct(s any) (ok bool, err error)

Bind is the same as BindStruct, but returns (false, nil) if Scan returns sql.ErrNoRows.

func (Row) Scan

func (r Row) Scan(dests ...any) (err error)

Scan implements the interface sql.Scanner, which is the proxy of sql.Row and supports that the sql value is NULL.

func (Row) ScanStruct

func (r Row) ScanStruct(s any) (err error)

ScanStruct is the same as Scan, but the columns are scanned into the struct s, which uses ScanColumnsToStruct.

func (Row) ScanStructWithColumns

func (r Row) ScanStructWithColumns(s any, columns ...string) (err error)

ScanStructWithColumns is the same as Scan, but the columns are scanned into the struct s by using ScanColumnsToStruct.

type Rows

type Rows struct {
	Columns []string // Only used by ScanStruct
	*sql.Rows
}

Rows is used to wrap sql.Rows.

func NewRows

func NewRows(rows *sql.Rows, columns ...string) Rows

NewRows returns a new Rows.

func (Rows) BindSlice added in v0.35.0

func (r Rows) BindSlice(slice any) (err error)

BindSlice is the same as ScanSlice, but closes sql.Rows.

func (Rows) Scan

func (r Rows) Scan(dests ...any) (err error)

Scan implements the interface sql.Scanner, which is the proxy of sql.Rows and supports that the sql value is NULL.

func (Rows) ScanSlice

func (r Rows) ScanSlice(slice any) (err error)

ScanSlice is used to scan the row set into the slice.

func (Rows) ScanStruct

func (r Rows) ScanStruct(s any) (err error)

ScanStruct is the same as Scan, but the columns are scanned into the struct s, which uses ScanColumnsToStruct.

func (Rows) ScanStructWithColumns

func (r Rows) ScanStructWithColumns(s any, columns ...string) (err error)

ScanStructWithColumns is the same as Scan, but the columns are scanned into the struct s by using ScanColumnsToStruct.

func (Rows) TryBindSlice added in v0.35.0

func (r Rows) TryBindSlice(slice any, err error) error

TryBindSlice is the same as BindSlice, which binds rows to slice only if err is equal to nil.

type SelectBuilder

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

SelectBuilder is used to build the SELECT statement.

Example
sel1 := Select("*").From("table").Where(op.Equal("id", 123)).Comment("abc")
sel2 := Select("*").FromAlias("table", "alias").Where(op.Equal("id", 123))
sel3 := SelectAlias("id", "c1").SelectAlias("name", "c2").FromAlias("table", "alias").Where(op.Equal("id", 123))
sel4 := Select("A.id").Select("B.name").FromAlias("table1", "A").FromAlias("table2", "B").Where(op.EqualKey("A.id", "B.id"))

sql1, args1 := sel1.Build()
sql2, args2 := sel2.Build()
sql3, args3 := sel3.Build()
sql4, args4 := sel4.Build()

fmt.Println(sql1)
fmt.Println(args1.Args())

fmt.Println(sql2)
fmt.Println(args2.Args())

fmt.Println(sql3)
fmt.Println(args3.Args())

fmt.Println(sql4)
fmt.Println(args4.Args())
Output:

SELECT * FROM `table` WHERE `id`=? /* abc */
[123]
SELECT * FROM `table` AS `alias` WHERE `id`=?
[123]
SELECT `id` AS `c1`, `name` AS `c2` FROM `table` AS `alias` WHERE `id`=?
[123]
SELECT `A`.`id`, `B`.`name` FROM `table1` AS `A`, `table2` AS `B` WHERE `A`.`id`=`B`.`id`
[]

func NewSelectBuilder

func NewSelectBuilder() *SelectBuilder

NewSelectBuilder returns a new SELECT builder.

func Select

func Select(column string) *SelectBuilder

Select is equal to SelectAlias(column, "").

func SelectAlias added in v0.27.0

func SelectAlias(column, alias string) *SelectBuilder

SelectAlias is equal to NewSelectBuilder().SelectAlias(column, alias).

func SelectStruct

func SelectStruct(s any) *SelectBuilder

SelectStruct is equal to SelectStructWithTable(s, "").

func SelectStructWithTable added in v0.27.0

func SelectStructWithTable(s any, table string) *SelectBuilder

SelectStruct is equal to NewSelectBuilder().SelectStructWithTable(s, table).

func Selects

func Selects(columns ...string) *SelectBuilder

Selects is equal to Select(columns[0]).Select(columns[1])...

func (*SelectBuilder) BindRow

func (b *SelectBuilder) BindRow(dest ...any) (bool, error)

BindRow is equal to b.BindRowContext(context.Background(), dest...).

func (*SelectBuilder) BindRowContext

func (b *SelectBuilder) BindRowContext(c context.Context, dest ...any) (bool, error)

BindRowContext is convenient function, which is equal to b.QueryRowContext(c).Bind(dest...).

func (*SelectBuilder) BindRowStruct

func (b *SelectBuilder) BindRowStruct(dest any) (bool, error)

BindRowStruct is equal to b.BindRowStructContext(context.Background(), dest).

func (*SelectBuilder) BindRowStructContext

func (b *SelectBuilder) BindRowStructContext(c context.Context, dest any) (bool, error)

BindRowStructContext is convenient function, which is equal to b.QueryRowContext(c).BindStruct(dest).

func (*SelectBuilder) BindRows

func (b *SelectBuilder) BindRows(slice any) error

BindRows is equal to b.BindRowsContext(context.Background(), slice).

func (*SelectBuilder) BindRowsContext

func (b *SelectBuilder) BindRowsContext(ctx context.Context, slice any) error

BindRowsContext is the same QueryContext, but scans the result set into the slice.

Notice: slice must be a pointer to a slice. And the element of the slice may be a struct or type implemented the interface sql.Scanner.

func (*SelectBuilder) Build

func (b *SelectBuilder) Build() (sql string, args *ArgsBuilder)

Build builds the SELECT sql statement.

func (*SelectBuilder) Comment added in v0.37.0

func (b *SelectBuilder) Comment(comment string) *SelectBuilder

Comment set the comment, which will be appended to the end of the built SQL statement.

func (*SelectBuilder) Distinct

func (b *SelectBuilder) Distinct() *SelectBuilder

Distinct marks SELECT as DISTINCT.

func (*SelectBuilder) From

func (b *SelectBuilder) From(table string) *SelectBuilder

From is equal to b.FromAlias(table, "").

func (*SelectBuilder) FromAlias added in v0.27.0

func (b *SelectBuilder) FromAlias(table, alias string) *SelectBuilder

FromAlias appends the FROM table name in SELECT with the alias.

If alias is empty, ignore it.

func (*SelectBuilder) Froms

func (b *SelectBuilder) Froms(tables ...string) *SelectBuilder

Froms is the same as b.From(table0).From(table1)...

func (*SelectBuilder) GroupBy

func (b *SelectBuilder) GroupBy(columns ...string) *SelectBuilder

GroupBy resets the GROUP BY columns.

Example
s := Select("*").From("table").Where(op.Equal("id", 123)).GroupBy("area")
sql, args := s.Build()

fmt.Println(sql)
fmt.Println(args.Args())
Output:

SELECT * FROM `table` WHERE `id`=? GROUP BY `area`
[123]

func (*SelectBuilder) Having

func (b *SelectBuilder) Having(exprs ...string) *SelectBuilder

Having appends the HAVING expression.

func (*SelectBuilder) Join

func (b *SelectBuilder) Join(table, alias string, ons ...JoinOn) *SelectBuilder

Join appends the "JOIN table ON on..." statement.

Example
s := Select("*").From("table1").Join("table2", "", On("table1.id", "table2.id")).
	Where(op.Equal("table1.id", 123)).OrderByAsc("table1.time").Limit(10).Offset(100)
sql, args := s.Build()

fmt.Println(sql)
fmt.Println(args.Args())
Output:

SELECT * FROM `table1` JOIN `table2` ON `table1`.`id`=`table2`.`id` WHERE `table1`.`id`=? ORDER BY `table1`.`time` ASC LIMIT 10 OFFSET 100
[123]

func (*SelectBuilder) JoinFull

func (b *SelectBuilder) JoinFull(table, alias string, ons ...JoinOn) *SelectBuilder

JoinFull appends the "FULL JOIN table ON on..." statement.

func (*SelectBuilder) JoinFullOuter

func (b *SelectBuilder) JoinFullOuter(table, alias string, ons ...JoinOn) *SelectBuilder

JoinFullOuter appends the "FULL OUTER JOIN table ON on..." statement.

func (*SelectBuilder) JoinLeft

func (b *SelectBuilder) JoinLeft(table, alias string, ons ...JoinOn) *SelectBuilder

JoinLeft appends the "LEFT JOIN table ON on..." statement.

func (*SelectBuilder) JoinLeftOuter

func (b *SelectBuilder) JoinLeftOuter(table, alias string, ons ...JoinOn) *SelectBuilder

JoinLeftOuter appends the "LEFT OUTER JOIN table ON on..." statement.

func (*SelectBuilder) JoinRight

func (b *SelectBuilder) JoinRight(table, alias string, ons ...JoinOn) *SelectBuilder

JoinRight appends the "RIGHT JOIN table ON on..." statement.

func (*SelectBuilder) JoinRightOuter

func (b *SelectBuilder) JoinRightOuter(table, alias string, ons ...JoinOn) *SelectBuilder

JoinRightOuter appends the "RIGHT OUTER JOIN table ON on..." statement.

func (*SelectBuilder) Limit

func (b *SelectBuilder) Limit(limit int64) *SelectBuilder

Limit sets the LIMIT to limit.

Example
s := Select("*").From("table").Where(op.Equal("id", 123)).
	OrderByAsc("time").Limit(10).Offset(100)
sql, args := s.Build()

fmt.Println(sql)
fmt.Println(args.Args())
Output:

SELECT * FROM `table` WHERE `id`=? ORDER BY `time` ASC LIMIT 10 OFFSET 100
[123]

func (*SelectBuilder) Offset

func (b *SelectBuilder) Offset(offset int64) *SelectBuilder

Offset sets the OFFSET to offset.

func (*SelectBuilder) OrderBy

func (b *SelectBuilder) OrderBy(column string, order Order) *SelectBuilder

OrderBy appends the column used by ORDER BY.

Example
s1 := Select("*").From("table").Where(op.Equal("id", 123)).OrderBy("time", Asc)
s2 := Select("*").From("table").Where(op.Equal("id", 123)).OrderBy("time", Desc)

sql1, args1 := s1.Build()
sql2, args2 := s2.Build()

fmt.Println(sql1)
fmt.Println(args1.Args())

fmt.Println(sql2)
fmt.Println(args2.Args())
Output:

SELECT * FROM `table` WHERE `id`=? ORDER BY `time` ASC
[123]
SELECT * FROM `table` WHERE `id`=? ORDER BY `time` DESC
[123]

func (*SelectBuilder) OrderByAsc

func (b *SelectBuilder) OrderByAsc(column string) *SelectBuilder

OrderByAsc appends the column used by ORDER BY ASC.

func (*SelectBuilder) OrderByDesc

func (b *SelectBuilder) OrderByDesc(column string) *SelectBuilder

OrderByDesc appends the column used by ORDER BY DESC.

func (*SelectBuilder) Paginate

func (b *SelectBuilder) Paginate(pageNum, pageSize int64) *SelectBuilder

Paginate is equal to b.Limit(pageSize).Offset((pageNum-1) * pageSize).

pageNum starts with 1. If pageNum or pageSize is less than 1, do nothing.

func (*SelectBuilder) Paginator added in v0.27.0

func (b *SelectBuilder) Paginator(page op.Paginator) *SelectBuilder

Paginator sets the paginator, which is the same as b.Paginate.

func (*SelectBuilder) Query

func (b *SelectBuilder) Query() (Rows, error)

Query builds the sql and executes it.

func (*SelectBuilder) QueryContext

func (b *SelectBuilder) QueryContext(ctx context.Context) (Rows, error)

QueryContext builds the sql and executes it.

func (*SelectBuilder) QueryRow

func (b *SelectBuilder) QueryRow() Row

QueryRow builds the sql and executes it.

func (*SelectBuilder) QueryRowContext

func (b *SelectBuilder) QueryRowContext(ctx context.Context) Row

QueryRowContext builds the sql and executes it.

func (*SelectBuilder) Select

func (b *SelectBuilder) Select(column string) *SelectBuilder

Select appends the selected column in SELECT.

func (*SelectBuilder) SelectAlias added in v0.27.0

func (b *SelectBuilder) SelectAlias(column, alias string) *SelectBuilder

Select appends the selected column in SELECT with the alias.

If alias is empty, it will be ignored.

func (*SelectBuilder) SelectCount added in v0.30.0

func (b *SelectBuilder) SelectCount(field string) *SelectBuilder

SelectCount appends the selected COUNT(field) column in SELECT.

func (*SelectBuilder) SelectCountDistinct added in v0.30.0

func (b *SelectBuilder) SelectCountDistinct(field string) *SelectBuilder

SelectCountDistinct appends the selected COUNT(DISTINCT field) column in SELECT.

func (*SelectBuilder) SelectStruct

func (b *SelectBuilder) SelectStruct(s any) *SelectBuilder

SelectStruct is equal to b.SelectStructWithTable(s, "").

Example
type S struct {
	DefaultField  string
	ModifiedField string `sql:"field"`
	IgnoredField  string `sql:"-"`
}

s := S{}
sb := SelectStructWithTable(s, "A")
columns := sb.SelectedColumns()
fmt.Println(columns)

err := ScanColumnsToStruct(func(values ...any) error {
	for i, v := range values {
		vp := v.(*string)
		switch i {
		case 0:
			*vp = "a"
		case 1:
			*vp = "b"
		default:
			fmt.Printf("unknown %dth column value\n", i)
		}
	}
	return nil
}, columns, &s)

if err != nil {
	fmt.Println(err)
} else {
	fmt.Println(s.DefaultField)
	fmt.Println(s.ModifiedField)
	fmt.Println(s.IgnoredField)
}
Output:

[DefaultField field]
a
b

func (*SelectBuilder) SelectStructWithTable added in v0.27.0

func (b *SelectBuilder) SelectStructWithTable(s any, table string) *SelectBuilder

SelectStructWithTable reflects and extracts the fields of the struct as the selected columns, which supports the tag named "sql" to modify the column name.

If the value of the tag is "-", however, the field will be ignored. If the tag contains the attribute "notpropagate", for the embeded struct, do not scan the fields of the embeded struct.

func (*SelectBuilder) SelectedColumns

func (b *SelectBuilder) SelectedColumns() []string

SelectedColumns is the same as SelectedFullColumns, but returns the short names instead.

func (*SelectBuilder) SelectedFullColumns

func (b *SelectBuilder) SelectedFullColumns() []string

SelectedFullColumns returns the full names of the selected columns.

Notice: if the column has the alias, the alias will be returned instead.

func (*SelectBuilder) Selects

func (b *SelectBuilder) Selects(columns ...string) *SelectBuilder

Selects is equal to b.Select(columns[0]).Select(columns[1])...

func (*SelectBuilder) SetDB

func (b *SelectBuilder) SetDB(db *DB) *SelectBuilder

SetDB sets the db.

func (*SelectBuilder) Sort added in v0.27.0

func (b *SelectBuilder) Sort(sorts ...op.Sorter) *SelectBuilder

Sort appends the sorts.

func (*SelectBuilder) String

func (b *SelectBuilder) String() string

String is the same as b.Build(), except args.

func (*SelectBuilder) Sum added in v0.31.0

func (b *SelectBuilder) Sum(field string) *SelectBuilder

SelectSum appends the selected SUM(field) column in SELECT.

func (*SelectBuilder) Where

func (b *SelectBuilder) Where(andConditions ...op.Condition) *SelectBuilder

Where sets the WHERE conditions.

func (*SelectBuilder) WhereNamedArgs

func (b *SelectBuilder) WhereNamedArgs(andArgs ...sql.NamedArg) *SelectBuilder

WhereNamedArgs is the same as Where, but uses the NamedArg as the condition.

type SqlCollector added in v0.36.0

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

SqlCollector is used to collect the executed sqls.

func NewSqlCollector added in v0.36.0

func NewSqlCollector() *SqlCollector

NewSqlCollector returns a new SqlCollector with enabled==true.

func (*SqlCollector) Intercept added in v0.36.0

func (c *SqlCollector) Intercept(sql string, args []any) (string, []any, error)

Intercept implements the interface Interceptor.

func (*SqlCollector) SetEnableFunc added in v0.36.0

func (c *SqlCollector) SetEnableFunc(enablef func() bool) *SqlCollector

SetEnableFunc sets whether to collect the executed sql.

It's not thread-safe and should be called after using.

func (*SqlCollector) SetEnabled added in v0.36.0

func (c *SqlCollector) SetEnabled(enabled bool) *SqlCollector

SetEnabled sets whether to collect the executed sql.

It's thread-safe. But It will have no effect if enablef is set.

func (*SqlCollector) SetFilterFunc added in v0.36.0

func (c *SqlCollector) SetFilterFunc(filterf func(sql string) bool) *SqlCollector

SetFilterFunc sets a filter function to decide to collect the sql only if filter returns true.

It's not thread-safe and should be called after using.

func (*SqlCollector) Sqls added in v0.36.0

func (c *SqlCollector) Sqls() []string

Sqls returns the executed sqls.

type Strings added in v0.39.0

type Strings []string

String is a string slice value type, which is encoded to a string or decoded from a []byte or string.

func (*Strings) Scan added in v0.39.0

func (vs *Strings) Scan(src any) error

Scan implements the interface sql.Scanner to scan a sql value to the map.

func (Strings) Value added in v0.39.0

func (vs Strings) Value() (driver.Value, error)

Value implements the interface driver.Valuer to encode the map to a sql value(string).

type Table

type Table struct {
	Name string
	*DB
}

Table represents a SQL table.

func NewTable

func NewTable(name string) Table

NewTable returns a new Table with the name.

func (Table) DeleteFrom

func (t Table) DeleteFrom(conds ...op.Condition) *DeleteBuilder

DeleteFrom returns a DELETE FROM builder.

func (Table) GetDB

func (t Table) GetDB() *DB

GetDB returns the set DB. Or returns DefaultDB instead if not set.

func (Table) InsertInto

func (t Table) InsertInto() *InsertBuilder

InsertInto returns a INSERT INTO builder.

func (Table) Select

func (t Table) Select(column string) *SelectBuilder

Select is equal to t.GetDB().Select(column).

func (Table) SelectAlias added in v0.27.0

func (t Table) SelectAlias(column, alias string) *SelectBuilder

SelectAlias is equal to t.GetDB().SelectAlias(column, alias).

func (Table) SelectStruct

func (t Table) SelectStruct(s any) *SelectBuilder

SelectStruct is equal to t.GetDB().SelectStructWithTable(s, "").

func (Table) SelectStructWithTable added in v0.27.0

func (t Table) SelectStructWithTable(s any, table string) *SelectBuilder

SelectStructWithTable is equal to t.GetDB().SelectStructWithTable(s, table).

func (Table) Selects

func (t Table) Selects(columns ...string) *SelectBuilder

Selects is equal to t.GetDB().Selects(columns...).

func (*Table) SetDB

func (t *Table) SetDB(db *DB)

SetDB reset the db.

func (Table) String added in v0.27.0

func (t Table) String() string

String returns the table name.

func (Table) Update

func (t Table) Update(updaters ...op.Updater) *UpdateBuilder

Update returns a UPDATE builder.

func (Table) WithDB

func (t Table) WithDB(db *DB) Table

WithDB returns a new Table with the given db.

type Time

type Time struct {
	Layout string // If empty, use defaults.TimeFormat instead when formatting time.
	time.Time
}

Time is used to read/write the time.Time from/to DB.

func Now

func Now() Time

Now returns the current Time.

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements the interface json.Marshaler.

func (*Time) Scan

func (t *Time) Scan(src any) (err error)

Scan implements the interface sql.Scanner.

func (*Time) SetFormat

func (t *Time) SetFormat(layout string)

SetFormat sets the format layout.

func (Time) String

func (t Time) String() string

func (Time) Value

func (t Time) Value() (driver.Value, error)

Value implements the interface driver.Valuer.

type UpdateBuilder

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

UpdateBuilder is used to build the UPDATE statement.

Example
// No Where
update1 := Update().Table("table").
	Set(op.Add("c1", 11), op.Sub("c2", 22)).
	Set(op.Mul("c3", 33), op.Div("c4", 44))

// With Where
update2 := Update().Table("table").
	Set(op.Set("c1", "v1"), op.Inc("c2"), op.Dec("c3")).
	Where(op.Equal("c4", "v4"), op.NotEqual("c5", "v5")).
	Where(op.Like("c6", "v6"), op.NotLike("c7", "v7%")).
	Where(op.Between("c8", 11, 22))

sql1, args1 := update1.Build()
sql2, args2 := update2.SetDB(&DB{Dialect: Postgres}).Build()

fmt.Println(sql1)
fmt.Println(args1.Args())
fmt.Println(sql2)
fmt.Println(args2.Args())
Output:

UPDATE `table` SET `c1`=`c1`+?, `c2`=`c2`-?, `c3`=`c3`*?, `c4`=`c4`/?
[11 22 33 44]
UPDATE "table" SET "c1"=$1, "c2"="c2"+1, "c3"="c3"-1 WHERE ("c4"=$2 AND "c5"<>$3 AND "c6" LIKE $4 AND "c7" NOT LIKE $5 AND "c8" BETWEEN $6 AND $7)
[v1 v4 v5 %v6% v7% 11 22]

func NewUpdateBuilder

func NewUpdateBuilder(table ...string) *UpdateBuilder

NewUpdateBuilder returns a new UPDATE builder.

func Update

func Update(table ...string) *UpdateBuilder

Update is short for NewUpdateBuilder.

func (*UpdateBuilder) Build

func (b *UpdateBuilder) Build() (sql string, args *ArgsBuilder)

Build builds the "UPDATE" sql statement.

func (*UpdateBuilder) Comment added in v0.37.0

func (b *UpdateBuilder) Comment(comment string) *UpdateBuilder

Comment set the comment, which will be appended to the end of the built SQL statement.

func (*UpdateBuilder) Exec

func (b *UpdateBuilder) Exec() (sql.Result, error)

Exec builds the sql and executes it by *sql.DB.

func (*UpdateBuilder) ExecContext

func (b *UpdateBuilder) ExecContext(ctx context.Context) (sql.Result, error)

ExecContext builds the sql and executes it by *sql.DB.

func (*UpdateBuilder) From

func (b *UpdateBuilder) From(table string, alias ...string) *UpdateBuilder

From is equal to b.FromAlias(table, "").

func (*UpdateBuilder) FromAlias added in v0.27.0

func (b *UpdateBuilder) FromAlias(table string, alias string) *UpdateBuilder

From appends the "FROM table AS alias" statement.

If alias is empty, use "FROM table" instead.

func (*UpdateBuilder) JoinFull

func (b *UpdateBuilder) JoinFull(table, alias string, ons ...JoinOn) *UpdateBuilder

JoinFull appends the "FULL JOIN table ON on..." statement.

func (*UpdateBuilder) JoinFullOuter

func (b *UpdateBuilder) JoinFullOuter(table, alias string, ons ...JoinOn) *UpdateBuilder

JoinFullOuter appends the "FULL OUTER JOIN table ON on..." statement.

func (*UpdateBuilder) JoinLeft

func (b *UpdateBuilder) JoinLeft(table, alias string, ons ...JoinOn) *UpdateBuilder

JoinLeft appends the "LEFT JOIN table ON on..." statement.

func (*UpdateBuilder) JoinLeftOuter

func (b *UpdateBuilder) JoinLeftOuter(table, alias string, ons ...JoinOn) *UpdateBuilder

JoinLeftOuter appends the "LEFT OUTER JOIN table ON on..." statement.

func (*UpdateBuilder) JoinRight

func (b *UpdateBuilder) JoinRight(table, alias string, ons ...JoinOn) *UpdateBuilder

JoinRight appends the "RIGHT JOIN table ON on..." statement.

func (*UpdateBuilder) JoinRightOuter

func (b *UpdateBuilder) JoinRightOuter(table, alias string, ons ...JoinOn) *UpdateBuilder

JoinRightOuter appends the "RIGHT OUTER JOIN table ON on..." statement.

func (*UpdateBuilder) Set

func (b *UpdateBuilder) Set(updaters ...op.Updater) *UpdateBuilder

Set appends the "SET" statement to setters.

func (*UpdateBuilder) SetDB

func (b *UpdateBuilder) SetDB(db *DB) *UpdateBuilder

SetDB sets the DB to db.

func (*UpdateBuilder) SetNamedArg

func (b *UpdateBuilder) SetNamedArg(args ...sql.NamedArg) *UpdateBuilder

SetNamedArg is the same as Set, but uses the NamedArg as the Setter.

func (*UpdateBuilder) String

func (b *UpdateBuilder) String() string

String is the same as b.Build(), except args.

func (*UpdateBuilder) Table

func (b *UpdateBuilder) Table(table string) *UpdateBuilder

Table is equal to b.TableAlias(table, "")

func (*UpdateBuilder) TableAlias added in v0.27.0

func (b *UpdateBuilder) TableAlias(table string, alias string) *UpdateBuilder

Table appends the "UPDATE table AS alias" statement.

If alias is empty, use "UPDATE table" instead.

func (*UpdateBuilder) Where

func (b *UpdateBuilder) Where(andConditions ...op.Condition) *UpdateBuilder

Where appends the "WHERE" conditions.

func (*UpdateBuilder) WhereNamedArgs

func (b *UpdateBuilder) WhereNamedArgs(andArgs ...sql.NamedArg) *UpdateBuilder

WhereNamedArgs is the same as Where, but uses the NamedArg as the EQUAL condition.

Jump to

Keyboard shortcuts

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