hey

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2024 License: MIT Imports: 11 Imported by: 1

README

What is hey?

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

INSTALL

go get github.com/cd365/hey@latest

EXAMPLE

package heyexample

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

	"github.com/cd365/hey"
	model "github.com/cd365/hey/_example"
	"github.com/cd365/hey/pgsql"
	_ "github.com/lib/pq"
)

var (
	t   = model.NewMember()
	db  *sql.DB
	way *hey.Way
)

func init() {
	dsn := fmt.Sprintf(
		"postgres://%s:%s@%s:%s/hey",
		os.Getenv("PGSQL_USERNAME"),
		os.Getenv("PGSQL_PASSWORD"),
		os.Getenv("PGSQL_HOST"),
		os.Getenv("PGSQL_PORT"),
	)
	dbc, err := sql.Open("postgres", dsn)
	if err != nil {
		panic(err)
	}
	db = dbc
	opts := []hey.Opts{
		hey.WithPrepare(pgsql.Prepare),
	}
	opts = append(opts, hey.WithLogger(func(log *hey.LogSQL) {
		if log.Args == nil {
			return
		}
		query := pgsql.PrepareString(log.Prepare, log.Args.Args)
		costs := log.Args.EndAt.Sub(log.Args.StartAt)
		fmt.Println(query, costs.String())
	}))
	way = hey.NewWay(db, opts...)
}

func Insert() {
	fields := []string{t.MemberId, t.Username, t.Email, t.Mobile, t.Nickname}
	values := []any{time.Now().UnixNano(), "username1", "email1@gmail.com", "123123123", "nickname1"}
	{
		create := &model.AddMember{
			MemberId: time.Now().UnixNano(),
			Username: "Alice",
		}
		permit := fields[:]
		permit = append(permit, t.AddAt, t.ModAt)
		now := time.Now()
		_, err := way.Add(t.Table()).
			Context(context.TODO()).
			Comment("Add 1.").
			Except(t.Id).
			// Except(t.ModAt).
			Permit(permit...).
			Create(create).
			FieldValue(t.Category, 123).
			Default(func(a *hey.Add) { a.FieldValue(t.AddAt, now.Unix()).FieldValue(t.ModAt, now.Unix()) }).
			Add()
		if err != nil {
			panic(err)
		}
	}
	{
		create := map[string]any{
			t.MemberId: time.Now().UnixNano(),
			t.Username: "Alice",
			t.Nickname: "777",
			t.AddAt:    time.Now().Unix(),
		}
		permit := fields[:]
		permit = append(permit, t.AddAt)
		_, err := way.Add(t.Table()).
			Context(context.TODO()).
			Comment("Add 2.").
			Except(t.Nickname).
			Permit(permit...).
			Create(create).
			Add()
		if err != nil {
			panic(err)
		}
	}
	{
		add := way.Add(t.Table()).
			Comment("Add 3.").
			Except(t.Id).
			FieldsValues(fields, [][]any{values})
		_, err := add.Add()
		if err != nil {
			panic(err)
		}
	}
	{
		now := time.Now()
		if !way.TxNil() {
			now = way.Now()
		}
		add := way.Add(t.Table())
		add.Comment("Add 4.")
		add.FieldValue(t.MemberId, time.Now().UnixNano())
		add.FieldValue(t.Username, "Alice")
		add.FieldValue(t.AddAt, now.Unix())
		add.FieldValue(t.ModAt, now.Unix())
		_, err := add.Add()
		if err != nil {
			panic(err)
		}
	}
	{

		fields0 := fields[:]
		fields1 := []string{
			"CASE WHEN member_id > 0 THEN member_id + 10 ELSE member_id END AS member_id",
			t.Username,
			t.Email,
			t.Mobile,
			t.Nickname,
		}
		add := way.Add(t.Table()).
			Comment("Add 5.")
		get := way.Get(t.Table()).
			Column(fields1...).
			// Where(way.F().Between(t.MemberId, 10000, 10010)).
			Desc(t.Id).Limit(10)
		add.ValuesSubQueryGet(get, fields0...)
		add.OnConflict(
			pgsql.InsertOnConflict(
				[]string{t.MemberId},
				fields0,
			))
		_, err := add.Add()
		if err != nil {
			fmt.Println(err.Error())
		}
	}
	{
		var id int64
		create := map[string]any{
			t.MemberId: time.Now().UnixNano(),
			t.Username: "Jerry",
		}
		now := time.Now()
		err := way.Add(t.Table()).
			Comment("Add 6.").
			Except(t.Id).
			// Except(t.ModAt).
			Create(create).
			Default(func(a *hey.Add) { a.FieldValue(t.AddAt, now.Unix()).FieldValue(t.ModAt, now.Unix()) }).
			Returning(func(row *sql.Row) error {
				return row.Scan(&id)
			}, t.Id)
		if err != nil {
			panic(err)
		}

		// Does the current driver support getting the insert id?
		// create[t.MemberId] = time.Now().UnixNano()
		// _, err := way.Add(t.Table()).
		// 	Except(t.Id).
		//  Comment("Add 7.").
		// 	Create(create).
		// 	UseResult(func(result sql.Result) error {
		// 		if cid, err := result.LastInsertId(); err != nil {
		// 			return err
		// 		} else {
		// 			id = cid
		// 		}
		// 		return nil
		// 	}).Add()
		// if err != nil {
		// 	panic(err)
		// }
	}
	{
		create := &model.AddMember{
			MemberId: time.Now().UnixNano(),
			Username: "Alice",
			Nickname: "Alice123",
			Email:    "alice@gmail.com",
		}
		_, err := way.Add(t.Table()).
			Context(context.TODO()).
			Comment("Add 8.").
			Except(t.Id).
			Create(create).
			// ON CONFLICT DO NOTHING
			OnConflict(pgsql.InsertOnConflict(
				[]string{t.MemberId}, // conflict columns
				nil,                  // update columns(value empty do nothing)
			)).
			// ON CONFLICT DO UPDATE SET ...
			// OnConflict(pgsql.InsertOnConflict(
			// 	[]string{t.MemberId}, // conflict columns
			// 	[]string{
			// 		t.Username,
			// 		t.Nickname,
			// 		t.Email,
			// 	}, // update columns(value empty do nothing)
			// )).
			Add()
		if err != nil {
			panic(err)
		}
	}
	{
		create := &model.AddMember{
			MemberId: time.Now().UnixNano(),
			Username: "Alice",
			Nickname: "Alice123",
			Email:    "alice@gmail.com",
		}
		_, err := way.Add(t.Table()).
			Context(context.TODO()).
			Comment("Add 9.").
			Except(t.Id).
			Create(create).
			// ON CONFLICT DO NOTHING
			// OnConflict(pgsql.InsertOnConflict(
			// 	[]string{t.MemberId}, // conflict columns
			// 	nil,                  // update columns(value empty do nothing)
			// )).
			// ON CONFLICT DO UPDATE SET ...
			OnConflict(pgsql.InsertOnConflict(
				[]string{t.MemberId}, // conflict columns
				[]string{
					t.Username,
					t.Nickname,
					t.Email,
				}, // update columns(value empty do nothing)
			)).
			Add()
		if err != nil {
			panic(err)
		}
	}
}

// Delete // The delete statement is usually used less frequently and only requires setting the table to be deleted and the corresponding conditions.
func Delete() {
	del := way.Del(t.Table()).Comment("Del 1.")
	where := way.F()
	// where.Equal(t.Id, 1)
	get := way.Get(t.Table()).Column(t.Id).Where(way.F().GreaterThanEqual(t.Id, 1000)).Limit(10).Asc(t.MemberId)
	where.InGet(t.Id, get)
	_, err := del.Where(where).Del()
	if err != nil {
		panic(err)
	}
}

func Update() {
	var id int64
	{
		err := way.Get(t.Table()).Column(t.Id).Limit(1).ScanOne(&id)
		if err != nil {
			panic(err)
		}
	}

	idEqual := way.F().Equal(t.Id, id)

	{
		now := way.Now()
		except := []string{t.Id}
		except = append(except, t.AddAt)
		mod := way.Mod(t.Table()).Comment("Mod 1.").
			Except(except...)
		mod.Set(t.Nickname, "123")
		mod.Default(func(u *hey.Mod) { u.Set(t.ModAt, now.Unix()) })
		mod.Decr(t.Category, 1)
		mod.Expr(t.State, fmt.Sprintf("%s = %s * ?", t.State, t.State), 2)
		// mod.FieldsValues([]string{t.Nickname}, []any{"112233"})
		mod.Where(idEqual)
		_, err := mod.Mod()
		if err != nil {
			panic(err)
		}
	}
	{
		now := way.Now()
		except := []string{t.Id}
		except = append(except, t.AddAt)
		mod := way.Mod(t.Table()).Comment("Mod 2.").
			Except(except...)
		// Updated through the structure question, the structure attribute (the corresponding field of the table) should be a pointer type.
		mod.Modify(map[string]any{
			t.Nickname: "789",
			t.ModAt:    now.Unix(),
		})
		mod.Where(idEqual)
		_, err := mod.Mod()
		if err != nil {
			panic(err)
		}
	}
	{
		now := way.Now()
		except := []string{t.Id}
		except = append(except, t.AddAt)
		mod := way.Mod(t.Table()).Comment("Mod 3.").Except(except...)
		update := &model.Member{
			Nickname: "123",
		}
		updateNew := update.COPY()
		updateNew.Nickname = "112233"
		mod.Update(update, updateNew)
		mod.Except(t.Category)
		mod.Default(func(u *hey.Mod) { u.Set(t.ModAt, now.Unix()).Set(t.Category, 5) })
		mod.Where(idEqual)
		_, err := mod.Mod()
		if err != nil {
			panic(err)
		}
	}
	{
		now := way.Now()
		except := []string{t.Id}
		except = append(except, t.AddAt)
		mod := way.Mod(t.Table()).Comment("Mod 4.").
			Except(except...)
		mod.SetCase(t.Category, func(c *hey.Case) {
			c.If(func(f hey.Filter) {
				f.GreaterThan(t.Category, 0)
			}, "category + 1")
			c.If(func(f hey.Filter) {
				f.LessThan(t.Category, 0)
			}, "category - 1")
			c.Else("category + ?", 0)
		})
		mod.Default(func(u *hey.Mod) { u.Set(t.ModAt, now.Unix()) })
		mod.Where(idEqual)
		_, err := mod.Mod()
		if err != nil {
			panic(err)
		}
	}
}

func Select() {
	result := make([]*model.Member, 0)
	{
		get := way.Get(t.Table()).Comment("Get 1.")
		get.Limit(1).Desc(t.Id)
		err := get.Get(&result)
		if err != nil {
			panic(err)
		}
	}
	{
		get := way.Get(t.Table()).Comment("Get 2.")
		get.Column(t.Id)
		get.Limit(1).Desc(t.Id)
		err := get.Get(&result)
		if err != nil {
			panic(err)
		}
	}
	{
		get := way.Get(t.Table()).Comment("Get 3.")
		get.Column(t.Id)
		get.Where(way.F().Equal(t.Id, 10010))
		get.Limit(1).Desc(t.Id)
		err := get.Get(&result)
		if err != nil {
			panic(err)
		}
	}
	{
		a := way.AliasA()
		b := way.AliasB()
		get := way.Get(t.Table()).Comment("Get 4.")
		get.Alias(a.V())
		get.Column(a.V(t.Id), b.V(t.MemberId))
		get.InnerJoin(func(j *hey.GetJoin) {
			j.Table(t.Table()).Alias(b.V()).Using(t.Id)
		})
		get.Where(way.F().Equal(a.V(t.Id), 10010))
		get.Limit(1).Desc(t.Id)
		err := get.Get(&result)
		if err != nil {
			panic(err)
		}
	}
	{
		a := way.AliasA()
		b := way.AliasB()
		get := way.Get(t.Table()).Comment("Get 5.")
		get.Alias(a.V())
		get.Column(a.V(t.Id), b.V(t.MemberId))
		get.InnerJoin(func(j *hey.GetJoin) {
			j.Table(t.Table()).Alias(b.V()).OnEqual(a.V(t.MemberId), b.V(t.MemberId))
		})
		get.Where(way.F().Equal(a.V(t.Id), 10010))
		get.Limit(1).Desc(t.Id)
		err := get.Get(&result)
		if err != nil {
			panic(err)
		}
	}

	{
		a := way.AliasA()
		column := hey.PrefixColumn(a.V(), t.Id, t.MemberId)
		get := way.Get(t.Table()).Comment("Get 6.")
		get.Alias(a.V())
		get.Column(column...)
		get.AddColCase(func(c *hey.Case) {
			c.If(func(f hey.Filter) {
				f.Equal(a.V(t.Gender), 1)
			}, "'Male'")
			c.If(func(f hey.Filter) {
				f.Equal(a.V(t.Gender), 2)
			}, "'Female'")
			c.Else("'Unknown'")
			c.Alias(t.Gender)
		})
		get.Where(way.F().Equal(a.V(t.Id), 10010))
		get.Limit(1).Desc(a.V(t.Id))
		err := get.Get(&result)
		if err != nil {
			panic(err)
		}
	}
	{
		a := way.AliasA()
		column := hey.PrefixColumn(a.V(), t.MemberId)
		column = append(column, a.SUM(t.State))
		get := way.Get(t.Table()).Comment("Get 7.")
		get.Alias(a.V())
		get.Column(column...)
		get.Where(way.F().Between(a.V(t.Id), 10010, 20020).GreaterThanEqual(a.V(t.State), 0))
		get.Group(a.V(t.MemberId))
		get.Having(way.F().GreaterThanEqual(a.Sum(t.State), 0).OrGroup(func(g hey.Filter) {
			g.LessThanEqual(a.Sum(t.State), -2)
		}))
		get.Limit(10).Offset(1).Desc(a.V(t.MemberId))
		err := get.Get(&result)
		if err != nil {
			panic(err)
		}
	}
}

func Where() {
	{
		f := hey.F()

		// Recommended
		f.Equal(t.Id, 1)

		// Not recommended, but original writing is supported
		f.And("id = 1")
		f.Or("id = ?", 2)
	}
	{
		f := hey.F()
		f.Equal(t.Id, 1)
		fmt.Println(f.SQL())
	}
	{
		f := hey.F()
		f.Equal(t.Id, 1).Between(t.Id, 1, 2).IsNull(t.Id)
		fmt.Println(f.SQL())
	}
	{
		f := hey.F()
		f.Equal(t.Id, 1).Between(t.Id, 1, 2).
			OrGroup(func(g hey.Filter) {
				g.Equal(t.Id, 7).Between(t.Id, 8, 9)
			})
		fmt.Println(f.SQL())
	}
	{
		f := hey.F()
		f.Group(func(g hey.Filter) {
			g.Equal(t.Id, 1).Between(t.Id, 1, 2)
		}).OrGroup(func(g hey.Filter) {
			g.Equal(t.Id, 7).Between(t.Id, 8, 9)
		})
		fmt.Println(f.SQL())
	}
	{
		f := hey.F()
		f.And(t.Id + " > 0")
		f.And("field1 < 9")
		f.Group(func(g hey.Filter) {
			g.NotBetween(t.Id, 6, 8)
			// g.Not().And("id BETWEEN ? AND ?", 6, 8)
		})
		fmt.Println(f.SQL())
	}
	{
		f := hey.F()
		f.Equal(t.Id, 1)
		fmt.Println(f.SQL())
		fmt.Println(f.IsEmpty())
		f.Clean()
		fmt.Println(f.IsEmpty())
		f.InCols(
			[]string{t.MemberId, t.Category, t.State},
			[][]interface{}{
				{1, 1, 1},
				{2, 2, 2},
				{3, 3, 3},
				// ...
			}...)
		fmt.Println(f.SQL())
	}
	{
		f := hey.F()
		f.Group(func(g hey.Filter) {
			g.GreaterThan(t.MemberId, 0)
		})
		f1 := hey.F()
		f1.Equal(t.Id, 1)
		f1.Use(f)
		fmt.Println(f1.SQL())
	}
	{
		f := hey.F()
		f.Group(func(g hey.Filter) {
			g.GreaterThan(t.MemberId, 0)
			g.IsNotNull(t.Id)
		})
		f1 := hey.F().New(f)
		fmt.Println(f1.SQL())
	}
	{
		f := hey.F()
		f.In(t.Id, 1, 2, 3)
		f.Group(func(g hey.Filter) {
			g.InSql(t.Id, "SELECT id FROM table WHERE field1 BETWEEN ? AND ?", 1, 10)
			g.OrGroup(func(g hey.Filter) {
				g.InSql(t.Id, "SELECT id FROM table WHERE field2 BETWEEN 100 AND 200")
			})
		})
		fmt.Println(f.SQL())
	}
	{
		get1 := hey.NewGet(nil)
		get1.Table(t.Table()).Column(t.Id).Where(hey.F().Between(t.MemberId, 1, 10))
		get2 := hey.NewGet(nil)
		get2.Table(t.Table()).Column(t.Id).Where(hey.F().Between(t.Category, 100, 200))
		get := hey.NewGet(nil).UnionAll(get1, get2)
		f := hey.F()
		f.In(t.Id, 1, 2, 3)
		f.OrGroup(func(g hey.Filter) {
			g.Not().InGet(t.Id, get)
		})
		fmt.Println(f.SQL())
	}
	{
		f := hey.F()
		f.Like(t.MemberId, "%k%")
		fmt.Println(f.SQL())
	}
	{
		f := hey.F()
		f.IsNotNull(t.Id)
		fmt.Println(f.SQL())
	}
}

func Transaction() {
	err := way.TxTry(func(tx *hey.Way) error {
		err := tx.Get(t.Table()). /* ... */ ScanOne()
		if err != nil {
			return err
		}
		_, err = tx.Add(t.Table()). /* ... */ Add()
		if err != nil {
			return err
		}
		_, err = tx.Del(t.Table()). /* ... */ Del()
		if err != nil {
			return err
		}
		_, err = tx.Mod(t.Table()). /* ... */ Mod()
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		panic(err)
	}
}

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
	StateNo  = "NO"
	StateYes = "YES"
	StateOn  = "ON"
	StateOff = "OFF"
)
View Source
const (
	// DefaultTag Mapping of default database column name and struct tag.
	DefaultTag = "db"

	// EmptyString Empty string value.
	EmptyString = ""
)
View Source
const (
	SqlDollar = "$"
	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"

	SqlAvg   = "AVG"
	SqlMax   = "MAX"
	SqlMin   = "MIN"
	SqlSum   = "SUM"
	SqlCount = "COUNT"

	SqlNot  = "NOT"
	SqlNull = "NULL"

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

	SqlAll = "ALL"
	SqlAny = "ANY"

	SqlLeftSmallBracket  = "("
	SqlRightSmallBracket = ")"

	SqlExpect    = "EXCEPT"
	SqlIntersect = "INTERSECT"

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

Variables

View Source
var (
	DefaultConfig = &Config{
		DeleteMustUseWhere: true,
		UpdateMustUseWhere: true,
	}
)
View Source
var (
	ErrNoAffectedRows = errors.New("hey: there are no affected rows")
)

Functions

func ArgString added in v1.1.0

func ArgString(i interface{}) string

ArgString Convert SQL statement parameters into text strings.

func BasicTypeValue added in v1.1.0

func BasicTypeValue(value interface{}) interface{}

func BuildCount added in v1.4.0

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

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

func BuildGet added in v1.4.0

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

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

func BuildOrderByLimitOffset added in v1.4.0

func BuildOrderByLimitOffset(s *Get) (prepare string)

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

func BuildTable added in v1.4.0

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

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

func BuildUnion added in v1.4.0

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

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

func BuildWith added in v1.4.0

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

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

func ConcatString added in v1.1.0

func ConcatString(sss ...string) string

ConcatString concatenate string.

func EqualAll added in v1.4.0

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

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

func EqualAny added in v1.4.0

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

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

func EvenSlice2Map added in v1.2.0

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

EvenSlice2Map even slice to map.

func ExpectGet added in v1.4.0

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

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

func GetCount added in v1.4.0

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

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

func GetCountGet added in v1.4.0

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

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

func GetCountQuery added in v1.4.0

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 added in v1.4.0

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

GetExists Determine whether the query result exists.

func GetGet added in v1.4.0

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

GetGet execute the built SQL statement and scan query result.

func GetQuery added in v1.4.0

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

GetQuery execute the built SQL statement and scan query result.

func GetScanAll added in v1.4.0

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 added in v1.4.0

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

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

func GetViewMap added in v1.4.0

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

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

func GreaterThanAll added in v1.4.0

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

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

func GreaterThanAny added in v1.4.0

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

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

func GreaterThanEqualAll added in v1.4.0

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

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

func GreaterThanEqualAny added in v1.4.0

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

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

func IntersectGet added in v1.4.0

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

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

func LastNotEmptyString added in v1.1.0

func LastNotEmptyString(sss []string) string

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

func LessThanAll added in v1.4.0

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

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

func LessThanAny added in v1.4.0

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

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

func LessThanEqualAll added in v1.4.0

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

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

func LessThanEqualAny added in v1.4.0

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

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

func MergeMap added in v1.2.0

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

MergeMap merge multiple maps.

func MergeSlice added in v1.2.0

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

MergeSlice merge multiple slices.

func MustAffectedRows added in v1.2.0

func MustAffectedRows(affectedRows int64, err error) error

MustAffectedRows at least one row is affected.

func NotEqualAll added in v1.4.0

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

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

func NotEqualAny added in v1.4.0

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

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

func PrefixColumn added in v1.4.0

func PrefixColumn(table string, column ...string) []string

PrefixColumn Prefix the field list with the table name or table alias.

func PrepareString added in v1.3.0

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

PrepareString Merge executed SQL statements and parameters.

func PutCase added in v1.4.0

func PutCase(i *Case)

PutCase put *Case in the pool.

func PutFilter added in v1.4.0

func PutFilter(f Filter)

func PutIdent added in v1.4.0

func PutIdent(i *Ident)

PutIdent put *Ident in the pool.

func RemoveDuplicate

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

RemoveDuplicate remove duplicate element.

func RemoveDuplicates added in v1.1.0

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

RemoveDuplicates remove duplicate element.

func RemoveSliceMemberByIndex added in v1.1.1

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

RemoveSliceMemberByIndex delete slice member by index.

func ScanAll added in v1.3.0

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

ScanAll Iteratively scan from query results.

func ScanOne added in v1.3.0

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

ScanOne Scan at most once from the query results.

func ScanSliceStruct

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

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

func ScanViewMap added in v1.3.0

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

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

func Slice2MapNewKey added in v1.2.0

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

Slice2MapNewKey make map by slice, create key.

func Slice2MapNewVal added in v1.2.0

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

Slice2MapNewVal make map by slice, create value.

func SliceIter added in v1.2.0

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

SliceIter slice iteration.

func SliceMatchMap added in v1.2.0

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

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

func SqlAlias added in v1.1.0

func SqlAlias(name string, alias string) string

SqlAlias sql alias name.

func SqlPrefix added in v1.1.0

func SqlPrefix(prefix string, name string) string

SqlPrefix sql prefix name.

func StructInsert added in v1.0.1

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

StructInsert object should be one of struct{}, *struct{}, []struct, []*struct{}, *[]struct{}, *[]*struct{}. get fields and values based on struct tag.

func StructModify

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

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

func StructObtain added in v1.1.0

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

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

func StructUpdate added in v1.0.1

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

StructUpdate compare origin and latest for update.

Types

type Add added in v1.0.1

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

Add for INSERT.

func NewAdd added in v1.0.1

func NewAdd(way *Way) *Add

NewAdd for INSERT.

func (*Add) Add added in v1.0.1

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

Add execute the built SQL statement.

func (*Add) Comment added in v1.0.1

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

Comment set comment.

func (*Add) Context added in v1.0.1

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

Context set context.

func (*Add) Create added in v1.0.1

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

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

func (*Add) Default added in v1.4.0

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

Default Add field = value .

func (*Add) Except added in v1.0.1

func (s *Add) Except(except ...string) *Add

Except exclude some columns from insert one or more rows.

func (*Add) FieldValue added in v1.1.0

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

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

func (*Add) FieldsValues added in v1.1.0

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

FieldsValues set fields and values.

func (*Add) OnConflict added in v1.1.0

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

OnConflict on conflict do something.

func (*Add) Permit added in v1.4.0

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

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

func (*Add) Returning added in v1.2.1

func (s *Add) Returning(fc func(row *sql.Row) error, returning ...string) error

Returning insert a row and return the data.

func (*Add) SQL added in v1.0.1

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

SQL build SQL statement.

func (*Add) Table added in v1.0.1

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

Table set table name.

func (*Add) UseResult added in v1.2.1

func (s *Add) UseResult(fc func(result sql.Result) error) *Add

UseResult provide sql.Result object.

func (*Add) ValuesSubQuery added in v1.0.1

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

ValuesSubQuery values is a query SQL statement.

func (*Add) ValuesSubQueryGet added in v1.0.1

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

ValuesSubQueryGet values is a query SQL statement.

func (*Add) Way added in v1.2.0

func (s *Add) Way() *Way

Way get current *Way.

type Caller added in v1.1.0

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

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

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

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

type Case added in v1.4.0

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

Case Implementing SQL CASE.

func GetCase added in v1.4.0

func GetCase() *Case

GetCase get *Case from pool.

func (*Case) Alias added in v1.4.0

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

Alias AS alias .

func (*Case) Else added in v1.4.0

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

Else Expressions of else.

func (*Case) If added in v1.4.0

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

If CASE WHEN condition THEN expressions.

func (*Case) SQL added in v1.4.0

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

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

type Config added in v1.1.0

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

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

Config Configure of Way.

type Del added in v1.0.1

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

Del for DELETE.

func NewDel added in v1.0.1

func NewDel(way *Way) *Del

NewDel for DELETE.

func (*Del) Comment added in v1.0.1

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

Comment set comment.

func (*Del) Context added in v1.0.1

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

Context set context.

func (*Del) Del added in v1.0.1

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

Del execute the built SQL statement.

func (*Del) F added in v1.2.0

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

F make new Filter.

func (*Del) SQL added in v1.0.1

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

SQL build SQL statement.

func (*Del) Table added in v1.0.1

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

Table set table name.

func (*Del) Way added in v1.2.0

func (s *Del) Way() *Way

Way get current *Way.

func (*Del) Where added in v1.0.1

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

Where set where.

type Filter

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

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

	// IsEmpty Is the current object an empty object?
	IsEmpty() bool

	// Not Negate the result of the current conditional filter object. Multiple negations are allowed.
	Not() Filter

	// And Use logical operator `AND` to combine custom conditions.
	And(expr string, args ...interface{}) Filter

	// Or Use logical operator `OR` to combine custom conditions.
	Or(expr string, args ...interface{}) Filter

	// Group Add a new condition group, which is connected by the `AND` logical operator by default.
	Group(group func(g Filter)) Filter

	// OrGroup Add a new condition group, which is connected by the `OR` logical operator by default.
	OrGroup(group func(g Filter)) Filter

	// Use Implement import a set of conditional filter objects into the current object.
	Use(fs ...Filter) Filter

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Filter Implement SQL statement condition filtering.

func F added in v1.2.0

func F() Filter

F New a Filter.

func GetFilter added in v1.4.0

func GetFilter() Filter

type Get added in v1.0.1

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

Get for SELECT.

func NewGet added in v1.0.1

func NewGet(way *Way) *Get

NewGet for SELECT.

func (*Get) AddCol added in v1.0.1

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

AddCol append the columns list of query.

func (*Get) AddColCase added in v1.4.0

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

AddColCase append the columns list of query.

func (*Get) Alias added in v1.0.1

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

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

func (*Get) Asc added in v1.1.0

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

Asc set order by column ASC.

func (*Get) Column added in v1.0.1

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

Column set the columns list of query.

func (*Get) Comment added in v1.0.1

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

Comment set comment.

func (*Get) Context added in v1.0.1

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

Context set context.

func (*Get) Count added in v1.0.1

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

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

func (*Get) CountGet added in v1.1.0

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

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

func (*Get) CountQuery added in v1.1.0

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

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

func (*Get) CrossJoin added in v1.4.0

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

CrossJoin for cross join.

func (*Get) Desc added in v1.1.0

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

Desc set order by column Desc.

func (*Get) Distinct added in v1.4.0

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

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

func (*Get) Exists added in v1.3.1

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

Exists Determine whether the query result exists.

func (*Get) F added in v1.2.0

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

F make new Filter.

func (*Get) FullJoin added in v1.0.1

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

FullJoin for full join.

func (*Get) Get added in v1.0.1

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

Get execute the built SQL statement and scan query result.

func (*Get) Group added in v1.0.1

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

Group set group columns.

func (*Get) Having added in v1.0.1

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

Having set filter of group result.

func (*Get) InnerJoin added in v1.0.1

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

InnerJoin for inner join.

func (*Get) Joins added in v1.1.0

func (s *Get) Joins(joins ...*GetJoin) *Get

Joins for join one or more tables.

func (*Get) LeftJoin added in v1.0.1

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

LeftJoin for left join.

func (*Get) Limit added in v1.0.1

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

Limit set limit.

func (*Get) Limiter added in v1.1.0

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

Limiter set limit and offset at the same time.

func (*Get) Offset added in v1.0.1

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

Offset set offset.

func (*Get) Order added in v1.0.1

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 added in v1.0.1

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

Query execute the built SQL statement and scan query result.

func (*Get) Raw added in v1.4.0

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

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

func (*Get) RightJoin added in v1.0.1

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

RightJoin for right join.

func (*Get) SQL added in v1.0.1

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

SQL build SQL statement.

func (*Get) SQLCount added in v1.0.1

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

SQLCount build SQL statement for count.

func (*Get) ScanAll added in v1.3.0

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 added in v1.3.0

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

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

func (*Get) SubQuery added in v1.1.0

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

SubQuery table is a query SQL statement.

func (*Get) SubQueryGet added in v1.1.0

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

SubQueryGet table is a query SQL statement.

func (*Get) Table added in v1.0.1

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

Table set table name.

func (*Get) Union added in v1.1.0

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

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

func (*Get) UnionAll added in v1.1.0

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

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

func (*Get) ViewMap added in v1.3.0

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

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

func (*Get) Way added in v1.2.0

func (s *Get) Way() *Way

Way get current *Way.

func (*Get) Where added in v1.0.1

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

Where set where.

func (*Get) With added in v1.1.0

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

With for with query.

type GetJoin added in v1.0.1

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

GetJoin join SQL statement.

func CrossJoin added in v1.4.0

func CrossJoin(table ...string) *GetJoin

func FullJoin

func FullJoin(table ...string) *GetJoin

func InnerJoin

func InnerJoin(table ...string) *GetJoin

func LeftJoin

func LeftJoin(table ...string) *GetJoin

func RightJoin

func RightJoin(table ...string) *GetJoin

func (*GetJoin) Alias added in v1.0.1

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

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

func (*GetJoin) On added in v1.0.1

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

On join query condition.

func (*GetJoin) OnEqual added in v1.0.1

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

OnEqual join query condition, support multiple fields.

func (*GetJoin) SQL added in v1.0.1

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

SQL build SQL statement.

func (*GetJoin) SubQuery added in v1.1.0

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

SubQuery table is a query SQL statement.

func (*GetJoin) SubQueryGet added in v1.1.0

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

SubQueryGet table is a query SQL statement.

func (*GetJoin) Table added in v1.0.1

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

Table set table name.

func (*GetJoin) Using added in v1.1.0

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

Using join query condition.

type GetWith added in v1.4.0

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

GetWith CTE: Common Table Expression.

func NewWith added in v1.4.0

func NewWith() *GetWith

func (*GetWith) Recursive added in v1.4.0

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

func (*GetWith) SQL added in v1.4.0

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

func (*GetWith) With added in v1.4.0

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

func (*GetWith) WithGet added in v1.4.0

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

type Ident added in v1.2.0

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

Ident sql identifier.

func GetIdent added in v1.4.0

func GetIdent(alias ...string) *Ident

GetIdent get *Ident from pool.

func (*Ident) AVG added in v1.2.0

func (s *Ident) AVG(field string) string

AVG AVG([prefix.]xxx) AS xxx.

func (*Ident) Avg added in v1.2.0

func (s *Ident) Avg(field string, alias ...string) string

Avg AVG([prefix.]xxx)[ AS xxx|custom].

func (*Ident) COUNT added in v1.2.0

func (s *Ident) COUNT(field string, alias ...string) string

COUNT COUNT([prefix.]xxx) AS count|custom.

func (*Ident) Field added in v1.3.1

func (s *Ident) Field(field ...string) []string

Field Batch set field prefix.

func (*Ident) MAX added in v1.2.0

func (s *Ident) MAX(field string) string

MAX MAX([prefix.]xxx) AS xxx.

func (*Ident) MIN added in v1.2.0

func (s *Ident) MIN(field string) string

MIN MIN([prefix.]xxx) AS xxx.

func (*Ident) Max added in v1.2.0

func (s *Ident) Max(field string, alias ...string) string

Max MAX([prefix.]xxx)[ AS xxx|custom].

func (*Ident) Min added in v1.2.0

func (s *Ident) Min(field string, alias ...string) string

Min MIN([prefix.]xxx)[ AS xxx|custom].

func (*Ident) SUM added in v1.2.0

func (s *Ident) SUM(field string) string

SUM SUM([prefix.]xxx) AS xxx.

func (*Ident) Sum added in v1.2.0

func (s *Ident) Sum(field string, alias ...string) string

Sum SUM([prefix.]xxx)[ AS xxx|custom].

func (*Ident) V added in v1.2.0

func (s *Ident) V(sss ...string) string

V returns expressions in different formats based on the length of the parameter. length=0: prefix value length=1: prefix.name length>1: prefix.name AS alias_name (the alias value must not be empty, otherwise it will not be used)

type Limiter added in v1.1.0

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

Limiter limit and offset.

type LogArgs added in v1.1.0

type LogArgs struct {
	// Args SQL parameter list.
	Args []interface{}

	// StartAt The start time of the SQL statement.
	StartAt time.Time

	// EndAt The end time of the SQL statement.
	EndAt time.Time
}

LogArgs Record executed args of prepare.

type LogSQL added in v1.3.3

type LogSQL struct {
	// TxId Transaction ID.
	TxId string

	// TxMsg Transaction descriptors.
	TxMsg string

	// Prepare Preprocess the SQL statements that are executed.
	Prepare string

	// Error An error encountered when executing SQL.
	Error error

	// Args SQL parameter list.
	Args *LogArgs
}

LogSQL Record executed prepare args.

type LogTrans added in v1.3.3

type LogTrans struct {
	// Transaction id.
	TxId string

	// Transaction message.
	TxMsg string

	// Transaction start at.
	StartAt time.Time

	// Transaction end at.
	EndAt time.Time

	// Transaction result COMMIT || ROLLBACK.
	State string

	// Error.
	Error error
}

LogTrans Record executed transaction.

type Mod added in v1.0.1

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

Mod for UPDATE.

func NewMod added in v1.0.1

func NewMod(way *Way) *Mod

NewMod for UPDATE.

func (*Mod) Comment added in v1.0.1

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

Comment set comment.

func (*Mod) Context added in v1.0.1

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

Context set context.

func (*Mod) Decr added in v1.0.1

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

Decr SET field = field - value.

func (*Mod) Default added in v1.4.0

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

Default SET field = expr .

func (*Mod) Except added in v1.0.1

func (s *Mod) Except(except ...string) *Mod

Except exclude some fields from update.

func (*Mod) Expr added in v1.1.0

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

Expr update field using custom expr.

func (*Mod) F added in v1.2.0

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

F make new Filter.

func (*Mod) FieldsValues added in v1.1.0

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

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

func (*Mod) Incr added in v1.0.1

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

Incr SET field = field + value.

func (*Mod) Mod added in v1.0.1

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

Mod execute the built SQL statement.

func (*Mod) Modify added in v1.1.0

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

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

func (*Mod) Permit added in v1.4.0

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

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

func (*Mod) SQL added in v1.0.1

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

SQL build SQL statement.

func (*Mod) Set added in v1.0.1

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

Set field = value.

func (*Mod) SetCase added in v1.4.0

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

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

func (*Mod) SetSQL added in v1.1.0

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

SetSQL prepare args of set.

func (*Mod) Table added in v1.0.1

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

Table set table name.

func (*Mod) Update added in v1.1.0

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

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

func (*Mod) Way added in v1.2.0

func (s *Mod) Way() *Way

Way get current *Way.

func (*Mod) Where added in v1.0.1

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

Where set where.

type Opts added in v1.1.0

type Opts func(s *Way)

Opts Custom attribute value of *Way.

func WithConfig added in v1.1.0

func WithConfig(config *Config) Opts

WithConfig -> Uses custom configure.

func WithLogger added in v1.1.0

func WithLogger(log func(log *LogSQL)) Opts

WithLogger -> Uses custom logger.

func WithPrepare added in v1.1.0

func WithPrepare(fix func(prepare string) string) Opts

WithPrepare -> Uses custom fix prepare.

func WithReader added in v1.3.0

func WithReader(reader Reader) Opts

WithReader -> uses reader for query.

func WithScan added in v1.3.0

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

WithScan -> Uses scan for query data.

func WithTag added in v1.1.0

func WithTag(tag string) Opts

WithTag -> Uses custom tag.

func WithTxLogger added in v1.1.0

func WithTxLogger(txLog func(log *LogTrans)) Opts

WithTxLogger -> Uses custom transaction logger.

func WithTxOpts added in v1.1.0

func WithTxOpts(txOpts *sql.TxOptions) Opts

WithTxOpts -> Uses custom global default transaction isolation level.

type PrepareArgs added in v1.1.0

type PrepareArgs struct {
	Prepare string

	Args []interface{}
}

PrepareArgs Statements to be executed and corresponding parameter list.

type Reader added in v1.3.0

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 added in v1.3.0

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 Stmt added in v1.1.0

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

Stmt Prepare handle.

func (*Stmt) Close added in v1.1.0

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

Close -> Close prepare handle.

func (*Stmt) Exec added in v1.1.0

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

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

func (*Stmt) ExecContext added in v1.1.0

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

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

func (*Stmt) Execute added in v1.2.1

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

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

func (*Stmt) ExecuteContext added in v1.2.1

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

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

func (*Stmt) Query added in v1.1.0

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

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

func (*Stmt) QueryContext added in v1.1.0

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

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

func (*Stmt) QueryRow added in v1.2.1

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

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

func (*Stmt) QueryRowContext added in v1.2.1

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

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

func (*Stmt) TakeAll added in v1.3.0

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

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

func (*Stmt) TakeAllContext added in v1.3.0

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

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

type SubQuery

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

func NewSubQuery added in v1.0.1

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

func (*SubQuery) SQL added in v1.0.1

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

type TxArgs added in v1.3.0

type TxArgs struct {
	// Use the specified database connection, default nil.
	Conn *sql.Conn

	// Use the specified transaction isolation level, default *Way.txOpts.
	Opts *sql.TxOptions

	// Try calling transaction multiple times, default 1.
	Times int
}

TxArgs Optional args for begin a transaction.

type Way

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

Way Quick insert, delete, update, select helper.

func NewWay

func NewWay(db *sql.DB, opts ...Opts) *Way

NewWay Instantiate a helper.

func (*Way) Add added in v1.0.1

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

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

func (*Way) AliasA added in v1.2.0

func (s *Way) AliasA() *Ident

AliasA SQL identifier prefix a.

func (*Way) AliasB added in v1.2.0

func (s *Way) AliasB() *Ident

AliasB SQL identifier prefix b.

func (*Way) AliasC added in v1.2.0

func (s *Way) AliasC() *Ident

AliasC SQL identifier prefix c.

func (*Way) AliasD added in v1.2.0

func (s *Way) AliasD() *Ident

AliasD SQL identifier prefix d.

func (*Way) AliasE added in v1.2.0

func (s *Way) AliasE() *Ident

AliasE SQL identifier prefix e.

func (*Way) AliasF added in v1.2.0

func (s *Way) AliasF() *Ident

AliasF SQL identifier prefix f.

func (*Way) AliasG added in v1.2.0

func (s *Way) AliasG() *Ident

AliasG SQL identifier prefix g.

func (*Way) Begin added in v1.4.0

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

Begin -> Open transaction(no transaction logging).

func (*Way) BeginWithConn added in v1.4.0

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

BeginWithConn -> Open transaction(no transaction logging).

func (*Way) Commit added in v1.4.0

func (s *Way) Commit() error

Commit -> Transaction commit.

func (*Way) DB

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

DB -> Get the database connection pool object in the current instance.

func (*Way) Del added in v1.0.1

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

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

func (*Way) Exec

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

Exec -> Execute the execute sql statement.

func (*Way) ExecContext

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

ExecContext -> Execute the execute sql statement.

func (*Way) Execute added in v1.2.1

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

Execute -> Execute the execute sql statement.

func (*Way) ExecuteContext added in v1.2.1

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

ExecuteContext -> Execute the execute sql statement.

func (*Way) F added in v1.1.0

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

F -> Quickly initialize a filter.

func (*Way) Get added in v1.0.1

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

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

func (*Way) Getter added in v1.1.0

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

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

func (*Way) GetterContext added in v1.1.0

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

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

func (*Way) Ident added in v1.2.0

func (s *Way) Ident(prefix ...string) *Ident

Ident -> SQL identifier.

func (*Way) IsRead added in v1.3.0

func (s *Way) IsRead() bool

IsRead -> Is an object for read?

func (*Way) Mod added in v1.0.1

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

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

func (*Way) Now added in v1.1.0

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

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

func (*Way) Prepare

func (s *Way) Prepare(prepare string, caller ...Caller) (*Stmt, error)

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

func (*Way) PrepareContext added in v1.1.0

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

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

func (*Way) Query

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

Query -> Execute the query sql statement.

func (*Way) QueryContext

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

QueryContext -> Execute the query sql statement.

func (*Way) QueryRow added in v1.2.1

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

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

func (*Way) QueryRowContext added in v1.2.1

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

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

func (*Way) Read added in v1.3.0

func (s *Way) Read() *Way

Read -> Get an object for read.

func (*Way) Rollback added in v1.4.0

func (s *Way) Rollback() error

Rollback -> Transaction rollback.

func (*Way) ScanAll added in v1.0.1

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

ScanAll -> Iteratively scan from query results.

func (*Way) ScanOne added in v1.3.0

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

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

func (*Way) Setter added in v1.1.0

func (s *Way) Setter(prepare string, caller ...Caller) (int64, error)

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

func (*Way) SetterContext added in v1.1.0

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

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

func (*Way) Tag added in v1.0.1

func (s *Way) Tag() string

Tag -> Get tag value.

func (*Way) TakeAll added in v1.3.0

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

TakeAll -> Query prepared and get all query results.

func (*Way) TakeAllContext added in v1.3.0

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

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

func (*Way) TxMsg added in v1.1.0

func (s *Way) TxMsg(msg string) *Way

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

func (*Way) TxNil

func (s *Way) TxNil() bool

TxNil -> Whether the current instance has not opened a transaction.

func (*Way) TxTry added in v1.1.0

func (s *Way) TxTry(fc func(tx *Way) error, args ...*TxArgs) error

TxTry -> Batch execute SQL through transactions, In args, only the last transaction parameter is valid.

func (*Way) TxTryCtx added in v1.1.0

func (s *Way) TxTryCtx(ctx context.Context, fc func(tx *Way) error, args ...*TxArgs) (err error)

TxTryCtx -> Batch execute SQL through transactions, In args, only the last transaction parameter is valid.

type WindowFunc added in v1.3.1

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

WindowFunc SQL window function.

func NewWindowFunc added in v1.3.1

func NewWindowFunc(alias ...string) *WindowFunc

func (*WindowFunc) Alias added in v1.3.1

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

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

func (*WindowFunc) Asc added in v1.3.1

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 added in v1.3.1

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

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

func (*WindowFunc) Count added in v1.3.1

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

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

func (*WindowFunc) DenseRank added in v1.3.1

func (s *WindowFunc) DenseRank() *WindowFunc

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

func (*WindowFunc) Desc added in v1.3.1

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 added in v1.3.1

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

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

func (*WindowFunc) Lag added in v1.3.1

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 added in v1.3.1

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

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

func (*WindowFunc) Lead added in v1.3.1

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 added in v1.3.1

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

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

func (*WindowFunc) Min added in v1.3.1

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

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

func (*WindowFunc) NthValue added in v1.3.1

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 added in v1.3.1

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 added in v1.3.1

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 added in v1.3.1

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 added in v1.3.1

func (s *WindowFunc) Result() string

Result Query column expressions.

func (*WindowFunc) RowNumber added in v1.3.1

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 added in v1.3.1

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

Sum SUM() Returns the sum of all rows in the window.

func (*WindowFunc) WindowFrame added in v1.3.1

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

WindowFrame Set custom window frame clause.

func (*WindowFunc) WithFunc added in v1.3.1

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

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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