builder

package
v0.1.19 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Example (Test)
var f frag.Fragment

f = Select(nil).From(
	TUser,
	Where(
		And(
			TUser.UserID.AsCond(Eq[UserID](100)),
			TUser.OrgID.Fragment("# = ? + 1", TOrg.OrgID),
		),
	),
	LeftJoin(TOrg).On(
		TUser.OrgID.AsCond(EqCol[OrgID](TOrg.OrgID)),
	),
	Limit(100).Offset(200),
)
Print(context.Background(), f)

f = Update(TUser).
	Set(
		TUser.Nickname.AssignBy(Value("new_name")),
	).
	Where(
		TUser.UserID.AsCond(Eq[UserID](100)),
	)
Print(context.Background(), f)

f = Insert().Into(TOrg).Values(
	ColsOf(TOrg.OrgID, TOrg.Name, TOrg.Belonged, TOrg.Manager),
	100, "org_name", 101, 102,
)
Print(context.Background(), f)

f = Delete().
	From(
		TUser,
		Where(TUser.UserID.AsCond(Eq[UserID](100))),
	)
Print(context.Background(), f)

f = Update(TUser).
	Set(TUser.Age.AssignBy(Inc(1))).
	Where(TUser.UserID.AsCond(Eq[UserID](100)))
Print(context.Background(), f)
Output:

SELECT * FROM t_user LEFT JOIN t_org ON t_user.f_org_id = t_org.f_org_id WHERE (t_user.f_user_id = ?) AND (t_user.f_org_id = t_org.f_org_id + 1) LIMIT 100 OFFSET 200
[100]
UPDATE t_user SET f_nick_name = ? WHERE f_user_id = ?
[new_name 100]
INSERT INTO t_org (f_org_id,f_name,f_belongs,manager) VALUES (?,?,?,?)
[100 org_name 101 102]
DELETE FROM t_user WHERE f_user_id = ?
[100]
UPDATE t_user SET f_age = f_age + ? WHERE f_user_id = ?
[1 100]

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrUpdateNeedLimitation = any(nil)

Functions

func Alias

func Alias(f frag.Fragment, name string) frag.Fragment

func AutoAlias

func AutoAlias(columns ...frag.Fragment) frag.Fragment

func ContextWithToggles

func ContextWithToggles(ctx context.Context, ts Toggles) context.Context

func DistinctOn

func DistinctOn(on ...frag.Fragment) frag.Fragment

DistinctOn mysql/sqlite unsupported Alternative:

SELECT `_id`, `score` FROM (

SELECT *, ROW_NUMBER() OVER (PARTITION BY `_id` ORDER BY `score` ASE) AS `row_no`
FROM `table`

) AS grouped WHERE `row_no` = 1

func GetColComputed

func GetColComputed(c Col) frag.Fragment

func HasToggle

func HasToggle(ctx context.Context, toggle ToggleType) bool

func KeyColumnsDefOf

func KeyColumnsDefOf(k Key) frag.Fragment

func NullsFirst

func NullsFirst() frag.Fragment

NullsFirst mysql/sqlite unsupported Alternative: ORDER BY `col` IS NULL

func NullsLast

func NullsLast() frag.Fragment

NullsLast mysql/sqlite unsupported Alternative: ORDER BY `col` IS NOT NULL

func TableNames

func TableNames(c Catalog) iter.Seq[string]

func TrimToggles

func TrimToggles(ctx context.Context, toggles ...ToggleType) context.Context

func WithToggles

func WithToggles(ctx context.Context, toggles ...ToggleType) context.Context

Types

type Addition

type Addition interface {
	frag.Fragment

	Type() AdditionType
}

func AsAddition

func AsAddition(t AdditionType, f frag.Fragment) Addition

func Comment

func Comment(lines ...string) Addition

func ForUpdate

func ForUpdate() Addition

ForUpdate pls be careful

func OnDuplicate

func OnDuplicate(assignments ...Assignment) Addition

func OrderBy

func OrderBy(os ...OrderAddition) Addition
Example
f := Select(nil).
	From(
		T("t_x"),
		OrderBy(
			AscOrder(C("F_a")),
			DescOrder(C("F_b")),
		),
		Where(
			And(
				CT[int]("F_a").AsCond(Eq(1)),
				CT[int]("F_b").Fragment("# = ?+1", CT[int]("F_a")),
			),
		),
		Comment("orders addition"),
	)
Print(context.Background(), f)

f = Select(nil).
	From(
		T("t_y"),
		AscOrder(C("F_id")),
		DescOrder(C("F_name")),
		Comment("order additions"),
	)
Print(context.Background(), f)
Output:

-- orders addition
SELECT * FROM t_x WHERE (f_a = ?) AND (f_b = f_a+1) ORDER BY (f_a) ASC,(f_b) DESC
[1]
-- order additions
SELECT * FROM t_y (f_id) ASC (f_name) DESC
[]

func Where

func Where(f frag.Fragment) Addition

type AdditionType

type AdditionType int8

type Additions

type Additions []Addition

func ExtractAdditions

func ExtractAdditions(t AdditionType, additions ...Addition) (filtered Additions)

func (Additions) Frag

func (as Additions) Frag(ctx context.Context) frag.Iter

func (Additions) IsNil

func (as Additions) IsNil() bool

type Assignment

type Assignment interface {
	frag.Fragment

	AssignmentMarker
}

func ColumnsAndValues

func ColumnsAndValues(cols frag.Fragment, values ...any) Assignment

ColumnsAndValues returns Assigment cols should be a Col or Cols

type AssignmentMarker

type AssignmentMarker interface {
	// contains filtered or unexported methods
}

type Assignments

type Assignments []Assignment

func (Assignments) Frag

func (as Assignments) Frag(ctx context.Context) frag.Iter

func (Assignments) IsNil

func (as Assignments) IsNil() bool

type Catalog

type Catalog interface {
	T(string) Table
	Tables() iter.Seq[Table]

	Add(...Table)
	Remove(string)
	Len() int
}

func CatalogFrom

func CatalogFrom(models ...internal.Model) Catalog

func NewCatalog

func NewCatalog() Catalog

type Col

type Col interface {
	frag.Fragment

	// Name presents database column name
	Name() string
	// FieldName presents name of definition of struct field
	FieldName() string
	// String returns full name like `table.column`
	String() string
	// Of change column table context to given argument
	Of(Table) Col
	// Fragment return a sql frag based current column
	Fragment(q string, args ...any) frag.Fragment
}

func C

func C(name string, options ...ColOption) Col

C creates a Col by name and ColOption

type ColComputed

type ColComputed interface {
	Computed() frag.Fragment
}

type ColDef

type ColDef interface {
	// Def returns column define
	Def() ColumnDef
}

type ColIter

type ColIter interface {
	// Cols iteration of columns
	Cols() iter.Seq[Col]
}

type ColModifier

type ColModifier interface {
	SetFieldName(string)
	SetComputed(frag.Fragment)
	SetDef(ColumnDef)
}

type ColOption

type ColOption func(ColModifier)

func WithColComputed

func WithColComputed(f frag.Fragment) ColOption

func WithColDef

func WithColDef(def *ColumnDef) ColOption

func WithColDefOf

func WithColDefOf(v any, tag reflect.StructTag) ColOption

func WithColFieldName

func WithColFieldName(name string) ColOption

type ColPick

type ColPick interface {
	// C picks a column by name
	C(string) Col
	// Pick columns
	Pick(...string) Cols
}

type ColValuer

type ColValuer[T any] func(v Col) frag.Fragment

func AsValue

func AsValue[T any](v TCol[T]) ColValuer[T]

func Between

func Between[T comparable](min, max T) ColValuer[T]

func Dec

func Dec[T any](v T) ColValuer[T]

func Eq

func Eq[T comparable](v T) ColValuer[T]

func EqCol

func EqCol[T comparable](v TCol[T]) ColValuer[T]

func Gt

func Gt[T comparable](v T) ColValuer[T]

func Gte

func Gte[T comparable](v T) ColValuer[T]

func In

func In[T any](vs ...T) ColValuer[T]

func Inc

func Inc[T any](v T) ColValuer[T]

func IsNotNull

func IsNotNull[T any]() ColValuer[T]

func IsNull

func IsNull[T any]() ColValuer[T]

func LLike

func LLike[T ~string](s T) ColValuer[T]

func Like

func Like[T ~string](s T) ColValuer[T]

func Lt

func Lt[T comparable](v T) ColValuer[T]

func Lte

func Lte[T comparable](v T) ColValuer[T]

func Neq

func Neq[T comparable](v T) ColValuer[T]

func NeqCol

func NeqCol[T comparable](v TCol[T]) ColValuer[T]

func NotBetween

func NotBetween[T comparable](min, max T) ColValuer[T]

func NotIn

func NotIn[T any](vs ...T) ColValuer[T]

func NotLike

func NotLike[T ~string](s T) ColValuer[T]

func RLike

func RLike[T ~string](s T) ColValuer[T]

func Value

func Value[T any](v T) ColValuer[T]

type ColWrapper

type ColWrapper interface {
	Unwrap() Col
}

type Cols

type Cols interface {
	ColPick
	ColIter

	// Of changes columns table context
	Of(Table) Cols
	// Len returns amount of column set
	Len() int

	frag.Fragment
}

func ColsIterOf

func ColsIterOf(cs ...iter.Seq[Col]) Cols

func ColsOf

func ColsOf(cs ...Col) Cols

func Columns

func Columns(names ...string) Cols

type ColsManager

type ColsManager interface {
	AddCol(...Col)
}

type ColumnDef

type ColumnDef = def.ColumnDef

func GetColDef

func GetColDef(c Col) ColumnDef

type CombinationAddition

type CombinationAddition interface {
	Addition

	All(SelectStatement) CombinationAddition
	Distinct(SelectStatement) CombinationAddition
}

func Expect

func Expect() CombinationAddition

func Intersect

func Intersect() CombinationAddition

func Union

func Union() CombinationAddition

type ComposedCondition

type ComposedCondition struct {
	ConditionMarker
	// contains filtered or unexported fields
}

func (*ComposedCondition) Frag

func (c *ComposedCondition) Frag(ctx context.Context) frag.Iter

func (*ComposedCondition) IsNil

func (c *ComposedCondition) IsNil() bool

type Condition

type Condition struct {
	ConditionMarker
	// contains filtered or unexported fields
}
Example
f := Xor(
	Or(
		And(
			nil,
			CT[int]("a").AsCond(Lt(1)),
			CT[string]("b").AsCond(LLike[string]("text")),
		),
		CT[int]("a").AsCond(Eq(2)),
	),
	CT[string]("b").AsCond(RLike[string]("g")),
)
Print(context.Background(), f)

f = Xor(
	Or(
		And(
			(*Condition)(nil),
			(*Condition)(nil),
			(*Condition)(nil),
			(*Condition)(nil),
			CT[int]("c").AsCond(In(1, 2)),
			CT[int]("c").AsCond(In(3, 4)),
			CT[int]("a").AsCond(Eq(1)),
			CT[string]("b").AsCond(Like("text")),
		),
		CT[int]("a").AsCond(Eq(2)),
	),
	CT[string]("b").AsCond(Like("g")),
)
Print(context.Background(), f)
Output:

(((a < ?) AND (b LIKE ?)) OR (a = ?)) XOR (b LIKE ?)
[1 %text 2 g%]
(((c IN (?,?)) AND (c IN (?,?)) AND (a = ?) AND (b LIKE ?)) OR (a = ?)) XOR (b LIKE ?)
[1 2 3 4 1 %text% 2 %g%]

func AsCond

func AsCond(f frag.Fragment) *Condition

func (*Condition) Frag

func (c *Condition) Frag(ctx context.Context) frag.Iter

func (*Condition) IsNil

func (c *Condition) IsNil() bool

type ConditionMarker

type ConditionMarker interface {
	// contains filtered or unexported methods
}

type Function

type Function struct {
	// contains filtered or unexported fields
}
Example
PrintQuery(context.Background(), Count())
PrintQuery(context.Background(), Count(C("a")))
PrintQuery(context.Background(), Avg(C("a")))
PrintQuery(context.Background(), AnyValue(C("a")))
PrintQuery(context.Background(), Min(C("a")))
PrintQuery(context.Background(), Max(C("a")))
PrintQuery(context.Background(), First(C("a")))
PrintQuery(context.Background(), Last(C("a")))
PrintQuery(context.Background(), Sum(C("a")))
PrintQuery(context.Background(), Func(""))
PrintQuery(context.Background(), Func("COUNT"))
Output:

COUNT(1)
COUNT(a)
AVG(a)
ANY_VALUE(a)
MIN(a)
MAX(a)
FIRST(a)
LAST(a)
SUM(a)

COUNT(*)

func AnyValue

func AnyValue(fragments ...frag.Fragment) *Function

func Avg

func Avg(fragments ...frag.Fragment) *Function

func Count

func Count(fragments ...frag.Fragment) *Function

func Distinct

func Distinct(fragments ...frag.Fragment) *Function

func First

func First(fragments ...frag.Fragment) *Function

func Func

func Func(name string, args ...frag.Fragment) *Function

func Last

func Last(fragments ...frag.Fragment) *Function

func Max

func Max(fragments ...frag.Fragment) *Function

func Min

func Min(fragments ...frag.Fragment) *Function

func Sum

func Sum(fragments ...frag.Fragment) *Function

func (*Function) Frag

func (f *Function) Frag(ctx context.Context) frag.Iter

func (*Function) IsNil

func (f *Function) IsNil() bool

type GroupByAddition

type GroupByAddition interface {
	Addition

	Having(cond frag.Fragment) GroupByAddition
}

func GroupBy

func GroupBy(groups ...frag.Fragment) GroupByAddition
Example
f := Select(ColsOf(C("F_a"), C("F_b"))).
	From(
		T("t_x"),
		Where(Where(CT[int]("F_a").AsCond(Eq(1)))),
		GroupBy(C("F_a"), C("F_b")).
			Having(CT[int]("F_a").AsCond(Eq(1))),
		Comment("group multi columns"),
	)
Print(context.Background(), f)
Output:

-- group multi columns
SELECT f_a,f_b FROM t_x WHERE f_a = ? GROUP BY f_a,f_b HAVING f_a = ?
[1 1]

type HasDatabase

type HasDatabase interface {
	Database() string
}

type HasSchema

type HasSchema interface {
	Schema() string
}

type JoinAddition

type JoinAddition interface {
	Addition

	On(condition frag.Fragment) JoinAddition
	Using(cols ...Col) JoinAddition
}

func CrossJoin

func CrossJoin(t frag.Fragment) JoinAddition

func FullJoin

func FullJoin(t frag.Fragment) JoinAddition

FullJoin mysql/sqlite unsupported

func InnerJoin

func InnerJoin(t frag.Fragment) JoinAddition

func Join

func Join(t frag.Fragment, methods ...string) JoinAddition
Example
f := Select(frag.Compose(", ",
	Alias(tUser.C("f_id"), "f_user_id"),
	Alias(tUser.C("f_org_id"), "f_org_id"),
	Alias(tOrg.C("f_name"), "f_org_name"),
)).From(
	tUser,
	Join(Alias(tOrg, "t_org")).On(
		And(
			CC[int64](tUser.C("f_org_id")).AsCond(EqCol(CC[int64](tOrg.C("f_org_id")))),
			CC[string](tOrg.C("f_name")).AsCond(Neq("abc")),
		),
	),
	Comment("join on"),
)
Print(context.Background(), f)

f = Select(nil).
	From(
		tUser,
		LeftJoin(tOrg).Using(tUser.C("f_org_id")),
		Comment("join using"),
	)
Print(context.Background(), f)

f = Select(
	frag.Compose(
		",",
		Alias(C("f_id").Of(tUser), "f_user_id"),
		Alias(C("f_org_id").Of(tOrg), "f_org_id"),
	),
).From(
	tUser,
	RightJoin(tOrg).On(
		CC[int64](tUser.C("f_org_id")).AsCond(EqCol(CC[int64](tOrg.C("f_org_id")))),
	),
	Comment("right join"),
)
Print(context.Background(), f)

f = Select(
	frag.Compose(
		",",
		Alias(C("f_id").Of(tUser), "f_user_id"),
		Alias(C("f_org_id").Of(tOrg), "f_org_id"),
	),
).From(
	tUser,
	FullJoin(tOrg).On(
		CC[int64](tUser.C("f_org_id")).AsCond(EqCol(CC[int64](tOrg.C("f_org_id")))),
	),
	Comment("full join"),
)
Print(context.Background(), f)

f = Select(
	frag.Compose(
		",",
		Alias(C("f_id").Of(tUser), "f_user_id"),
		Alias(C("f_org_id").Of(tOrg), "f_org_id"),
	),
).From(
	tUser,
	InnerJoin(tOrg).On(
		CC[int64](tUser.C("f_org_id")).AsCond(EqCol(CC[int64](tOrg.C("f_org_id")))),
	),
	Comment("inner join"),
)
Print(context.Background(), f)

f = Select(nil).
	From(tUser, CrossJoin(tOrg), Comment("cross join"))
Print(context.Background(), f)

f = Select(
	AutoAlias(
		tUser.C("f_id"),
		tOrg.C("f_name"),
	),
).From(
	tUser,
	FullJoin(tOrg).On(
		CC[int](tUser.C("f_org_id")).AsCond(EqCol(CC[int](tOrg.C("f_org_id")))),
	),
	Comment("full join + auto alias"),
)
Print(context.Background(), f)
Output:

-- join on
SELECT t_user.f_id AS f_user_id, t_user.f_org_id AS f_org_id, t_org.f_name AS f_org_name FROM t_user JOIN t_org AS t_org ON (t_user.f_org_id = t_org.f_org_id) AND (t_org.f_name <> ?)
[abc]
-- join using
SELECT * FROM t_user LEFT JOIN t_org USING (f_org_id)
[]
-- right join
SELECT t_user.f_id AS f_user_id,t_org.f_org_id AS f_org_id FROM t_user RIGHT JOIN t_org ON t_user.f_org_id = t_org.f_org_id
[]
-- full join
SELECT t_user.f_id AS f_user_id,t_org.f_org_id AS f_org_id FROM t_user FULL JOIN t_org ON t_user.f_org_id = t_org.f_org_id
[]
-- inner join
SELECT t_user.f_id AS f_user_id,t_org.f_org_id AS f_org_id FROM t_user INNER JOIN t_org ON t_user.f_org_id = t_org.f_org_id
[]
-- cross join
SELECT * FROM t_user CROSS JOIN t_org
[]
-- full join + auto alias
SELECT t_user.f_id AS t_user__f_id, t_org.f_name AS t_org__f_name FROM t_user FULL JOIN t_org ON t_user.f_org_id = t_org.f_org_id
[]

func LeftJoin

func LeftJoin(t frag.Fragment) JoinAddition

func RightJoin

func RightJoin(t frag.Fragment) JoinAddition

RightJoin sqlite unsupported

type Key

type Key interface {
	frag.Fragment
	ColIter

	Name() string
	Of(Table) Key
	IsPrimary() bool
	IsUnique() bool
	// String return [$table_name.]$index_name
	String() string
}

func K

func K(name string, cols Cols, opts ...KeyOption) Key

func PK

func PK(cols Cols, opts ...KeyOption) Key

func UK

func UK(name string, cols Cols, opts ...KeyOption) Key

type KeyColumnOption

type KeyColumnOption = def.KeyColumnOption

type KeyDef

type KeyDef interface {
	Method() string
	ColumnOptions() []def.KeyColumnOption
}

type KeyDefine

type KeyDefine = def.KeyDefine

type KeyIter

type KeyIter interface {
	Keys() iter.Seq[Key]
}

type KeyKind

type KeyKind = def.KeyKind

type KeyOption

type KeyOption func(*key)

func WithKeyColumnOptions

func WithKeyColumnOptions(opts ...KeyColumnOption) KeyOption

func WithKeyMethod

func WithKeyMethod(method string) KeyOption

func WithKeyUniqueness

func WithKeyUniqueness(unique bool) KeyOption

type KeyPick

type KeyPick interface {
	K(string) Key
}

type Keys

type Keys interface {
	KeyIter
	KeyPick

	Of(Table) Keys
}

type KeysManager

type KeysManager interface {
	AddKey(...Key)
}

type LimitAddition

type LimitAddition interface {
	Addition

	Offset(offset int64) LimitAddition
}

func Limit

func Limit(count int64) LimitAddition
Example
f := Select(nil).
	From(
		T("t_x"),
		Where(CT[int]("F_a").AsCond(Eq(1))),
		Limit(1),
		Comment("limit"),
	)
Print(context.Background(), f)

f = Select(nil).
	From(
		T("t_x"),
		Where(CT[int]("F_a").AsCond(Eq(1))),
		Limit(-1),
		Comment("without limit"),
	)
Print(context.Background(), f)

f = Select(nil).
	From(
		T("t_x"),
		Where(CT[int]("F_a").AsCond(Eq(1))),
		Limit(20).Offset(100),
		Comment("limit with offset", "comment line2"),
	)
Print(context.Background(), f)
Output:

-- limit
SELECT * FROM t_x WHERE f_a = ? LIMIT 1
[1]
-- without limit
SELECT * FROM t_x WHERE f_a = ?
[1]
-- limit with offset
-- comment line2
SELECT * FROM t_x WHERE f_a = ? LIMIT 20 OFFSET 100
[1]

type Model

type Model = internal.Model

type OnConflictAddition

type OnConflictAddition interface {
	Addition

	DoNothing() OnConflictAddition
	DoUpdateSet(...Assignment) OnConflictAddition
}

func OnConflict

func OnConflict(cols ColIter) OnConflictAddition

type OrderAddition

type OrderAddition interface {
	Addition
	frag.Fragment
	// contains filtered or unexported methods
}

func AscOrder

func AscOrder(by frag.Fragment, ex ...frag.Fragment) OrderAddition

AscOrder asc order

func DescOrder

func DescOrder(by frag.Fragment, ex ...frag.Fragment) OrderAddition

DescOrder desc order

func Order

func Order(by frag.Fragment, ex ...frag.Fragment) OrderAddition

Order default order

type ReturningAddition

type ReturningAddition interface {
	Addition
}

func Returning

func Returning(p frag.Fragment) ReturningAddition

type SelectStatement

type SelectStatement interface {
	frag.Fragment
	// contains filtered or unexported methods
}

type SqlCondition

type SqlCondition interface {
	frag.Fragment

	ConditionMarker
}

func And

func And(conditions ...frag.Fragment) SqlCondition

func Exists

func Exists(f frag.Fragment) SqlCondition

func Or

func Or(conditions ...frag.Fragment) SqlCondition

func Xor

func Xor(conditions ...frag.Fragment) SqlCondition

type StmtDelete

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

func Delete

func Delete() *StmtDelete
Example
f := Delete().From(
	T("t_x"),
	Where(CT[int]("F_a").AsCond(Eq(1))),
	Comment("delete"),
)
Print(context.Background(), f)
Output:

-- delete
DELETE FROM t_x WHERE f_a = ?
[1]

func (*StmtDelete) Frag

func (s *StmtDelete) Frag(ctx context.Context) frag.Iter

func (StmtDelete) From

func (s StmtDelete) From(t Table, additions ...Addition) *StmtDelete

func (*StmtDelete) IsNil

func (s *StmtDelete) IsNil() bool

type StmtInsert

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

func Insert

func Insert(modifiers ...string) *StmtInsert
Example
f := Insert().
	Into(
		T("t_user"),
		Comment("insert"),
	).
	Values(Columns("f_a", "f_b"), 1, 2)
Print(context.Background(), f)

f = Insert("IGNORE").
	Into(
		T("t_user"),
		Comment("insert ignore and multi"),
	).
	Values(Columns("f_a", "f_b"), 1, 2, 1, 2, 1, 2)
Print(context.Background(), f)

f = Insert().
	Into(
		T("t_user_migrated"),
		Comment("insert from selection"),
	).
	Values(
		Columns("f_a", "f_b"),
		Select(Columns("f_a", "f_b")).
			From(
				T("t_user_previous"),
				Where(CT[string]("f_status").AsCond(Eq("valid"))),
			),
	)
Print(context.Background(), f)

f = Insert().
	Into(
		T("t_user"),
		OnConflict(ColsOf(C("f_id"))).DoNothing(),
		Comment("insert on conflict do nothing"),
	).
	Values(ColsOf(C("f_id"), C("f_name")), 1, "saito")
Print(context.Background(), f)

f = Insert().
	Into(
		T("t_user"),
		OnConflict(ColsOf(C("f_id"))).
			DoUpdateSet(ColumnsAndValues(ColsOf(C("f_name")), "saito")),
		Comment("insert on conflict do update"),
	).
	Values(ColsOf(C("f_id"), C("f_name")), 1, "saito")
Print(context.Background(), f)

f = Insert().
	Into(
		T("t_user"),
		OnDuplicate(ColumnsAndValues(ColsOf(C("f_id")), C("f_id"))),
		Comment("insert on duplicate key do update"),
	).
	Values(ColsOf(C("f_id"), C("f_name")), 1, "saito")
Print(context.Background(), f)

f = Insert().
	Into(
		T("t_user"),
		OnConflict(ColsOf(C("f_id"))).
			DoUpdateSet(
				ColumnsAndValues(ColsOf(C("f_name")), "saito"),
				nil,
			),
		Comment("with nil assignment"),
	).
	Values(ColsOf(C("f_id"), C("f_name")), 1, "saito")
Print(context.Background(), f)
Output:

-- insert
INSERT INTO t_user (f_a,f_b) VALUES (?,?)
[1 2]
-- insert ignore and multi
INSERT IGNORE INTO t_user (f_a,f_b) VALUES (?,?),(?,?),(?,?)
[1 2 1 2 1 2]
-- insert from selection
INSERT INTO t_user_migrated (f_a,f_b) SELECT f_a,f_b FROM t_user_previous WHERE f_status = ?
[valid]
-- insert on conflict do nothing
INSERT INTO t_user (f_id,f_name) VALUES (?,?) ON CONFLICT (f_id) DO NOTHING
[1 saito]
-- insert on conflict do update
INSERT INTO t_user (f_id,f_name) VALUES (?,?) ON CONFLICT (f_id) DO UPDATE SET f_name = ?
[1 saito saito]
-- insert on duplicate key do update
INSERT INTO t_user (f_id,f_name) VALUES (?,?) ON DUPLICATE KEY UPDATE f_id = f_id
[1 saito]
-- with nil assignment
INSERT INTO t_user (f_id,f_name) VALUES (?,?) ON CONFLICT (f_id) DO UPDATE SET f_name = ?
[1 saito saito]

func (*StmtInsert) Frag

func (s *StmtInsert) Frag(ctx context.Context) frag.Iter

func (StmtInsert) Into

func (s StmtInsert) Into(t Table, additions ...Addition) *StmtInsert

func (*StmtInsert) IsNil

func (s *StmtInsert) IsNil() bool

func (StmtInsert) Values

func (s StmtInsert) Values(cols Cols, values ...any) *StmtInsert

type StmtSelect

type StmtSelect struct {
	SelectStatement
	// contains filtered or unexported fields
}

func Select

func Select(f frag.Fragment, modifiers ...frag.Fragment) *StmtSelect
Example
f := Select(
	nil,
	frag.Lit("SQL_CALC_FOUND_ROWS"),
).From(
	tUser,
	Where(CT[int]("F_created_at").AsCond(Gte(593650800))),
	Limit(10),
	Comment("select with modifier"),
)
Print(context.Background(), f)

f = Select(nil).From(
	tUser,
	Where(CT[int]("F_id").AsCond(In(1, 2, 3))),
	OrderBy(
		Order(tUser.C("f_id")),
		AscOrder(tUser.C("f_org_id"), NullsFirst()),
		DescOrder(tUser.C("f_name"), NullsLast()),
	),
	Comment("select with orders"),
)
Print(context.Background(), f)

f = Select(
	frag.Compose(",",
		DistinctOn(tUser.C("f_org_id")),
		tUser.C("f_id"),
		tUser.C("f_name"),
	),
).From(
	tUser,
	OrderBy(Order(C("f_created_at"))),
	Comment("select with distinct on"),
)
Print(context.Background(), f)

f = Select(nil).From(
	tUser,
	Where(CT[int]("F_id").AsCond(Eq(1))),
	ForUpdate(),
	Comment("select 1 row for update"),
)
Print(context.Background(), f)
Output:

-- select with modifier
SELECT SQL_CALC_FOUND_ROWS * FROM t_user WHERE f_created_at >= ? LIMIT 10
[593650800]
-- select with orders
SELECT * FROM t_user WHERE f_id IN (?,?,?) ORDER BY (f_id),(f_org_id) ASC NULLS FIRST,(f_name) DESC NULLS LAST
[1 2 3]
-- select with distinct on
SELECT DISTINCT ON (f_org_id),f_id,f_name FROM t_user ORDER BY (f_created_at)
[]
-- select 1 row for update
SELECT * FROM t_user WHERE f_id = ? FOR UPDATE
[1]

func (*StmtSelect) Frag

func (s *StmtSelect) Frag(ctx context.Context) frag.Iter

func (StmtSelect) From

func (s StmtSelect) From(t frag.Fragment, additions ...Addition) *StmtSelect

func (*StmtSelect) IsNil

func (s *StmtSelect) IsNil() bool

type StmtUpdate

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

func Update

func Update(t Table, modifiers ...string) *StmtUpdate
Example
var (
	f_id     = CT[int]("f_id")
	f_stu_id = CT[int]("f_stu_id")
	f_score  = CT[int]("f_score")
	f_class  = CT[string]("f_class")

	t_stu   = T("t_stu", f_id, f_score, f_class)
	t_class = T("t_class", f_stu_id, f_class)
)

f := Update(t_stu).
	Set(
		CC[int](t_stu.C("f_score")).AssignBy(Value(100)),
		CC[string](t_stu.C("f_class")).AssignBy(AsValue(CC[string](t_class.C("f_class")))),
	).
	From(t_class).
	Where(
		CC[string](t_stu.C(f_id.Name())).
			AsCond(EqCol(CC[string](t_class.C(f_stu_id.Name())))),
		Comment("update from postgres supported"),
	)
Print(context.Background(), f)

f = Update(t_stu).
	From(
		nil,
		Join(t_class).On(
			CC[string](t_stu.C(f_id.Name())).
				AsCond(EqCol(CC[string](t_class.C(f_stu_id.Name())))),
		),
		Comment("update join mysql supported"),
	).
	Set(
		CC[int](t_stu.C("f_score")).AssignBy(Value(100)),
		CC[string](t_stu.C("f_class")).AssignBy(AsValue(CC[string](t_class.C("f_class")))),
	)
Print(context.Background(), f)

sub := Select(f_class.Of(t_class)).From(
	t_class,
	Where(CC[int](f_stu_id.Of(t_class)).AsCond(EqCol(CC[int](f_id.Of(t_stu))))),
	Limit(1),
)
f = Update(t_stu).
	Set(
		CC[int](t_stu.C("f_score")).AssignBy(Value(100)),
		ColumnsAndValues(f_class.Of(t_stu), sub),
	).
	Where(
		Exists(sub),
		Comment("update with sub query and exists condition sqlite supported"),
	)
Print(context.Background(), f)

f = Update(t_stu).
	Set(
		CC[int](t_stu.C("f_score")).AssignBy(Value(100)),
	).
	Where(
		CC[int](t_stu.C("f_id")).AsCond(Eq(1)),
		Returning(nil),
		Comment("update with returning"),
	)
Print(context.Background(), f)

f = UpdateIgnore(t_stu).
	Set(CC[int](t_stu.C("f_score")).AssignBy(Value(100))).
	Where(
		CC[int](t_stu.C("f_id")).AsCond(Eq(1)),
		Comment("update ignore"),
	)
Print(context.Background(), f)
Output:

-- update from postgres supported
UPDATE t_stu SET f_score = ?, f_class = t_class.f_class FROM t_class WHERE t_stu.f_id = t_class.f_stu_id
[100]
-- update join mysql supported
UPDATE t_stu JOIN t_class ON t_stu.f_id = t_class.f_stu_id SET f_score = ?, f_class = t_class.f_class
[100]
-- update with sub query and exists condition sqlite supported
UPDATE t_stu SET f_score = ?, f_class = (SELECT f_class FROM t_class WHERE f_stu_id = f_id LIMIT 1) WHERE EXISTS (SELECT f_class FROM t_class WHERE f_stu_id = f_id LIMIT 1)
[100]
-- update with returning
UPDATE t_stu SET f_score = ? WHERE f_id = ? RETURNING *
[100 1]
-- update ignore
UPDATE IGNORE t_stu SET f_score = ? WHERE f_id = ?
[100 1]

func UpdateIgnore

func UpdateIgnore(t Table) *StmtUpdate

func (*StmtUpdate) Frag

func (s *StmtUpdate) Frag(ctx context.Context) frag.Iter

func (StmtUpdate) From

func (s StmtUpdate) From(from Table, additions ...Addition) *StmtUpdate

func (*StmtUpdate) IsNil

func (s *StmtUpdate) IsNil() bool

func (StmtUpdate) Set

func (s StmtUpdate) Set(assignments ...Assignment) *StmtUpdate

func (StmtUpdate) Where

func (s StmtUpdate) Where(cond frag.Fragment, additions ...Addition) *StmtUpdate

type SubQuery

type SubQuery func(Table) frag.Fragment

type TCol

type TCol[T any] interface {
	Col

	AsCond(ColValuer[T]) frag.Fragment
	AssignBy(...ColValuer[T]) Assignment
}

TCol make column can computed

func CC

func CC[T any](c Col, options ...ColOption) TCol[T]

CC cast c for computing with type T

func CT

func CT[T any](name string, options ...ColOption) TCol[T]

CT creates a Col by name and ColOption with computing T

type Table

type Table interface {
	TableName() string
	String() string

	KeyPick
	KeyIter

	ColPick
	ColIter

	Fragment(string, ...any) frag.Fragment
	frag.Fragment
}

func GetColTable

func GetColTable(c Col) Table

func GetKeyTable

func GetKeyTable(k Key) Table

func T

func T(name string, defs ...frag.Fragment) Table

func TFrom

func TFrom(m any) Table

type ToggleType

type ToggleType int8
const (
	TOGGLE__MULTI_TABLE ToggleType = iota + 1
	TOGGLE__AUTO_ALIAS
	TOGGLE__ASSIGNMENTS
	TOGGLE__IN_PROJECT
	TOGGLE__SKIP_COMMENTS
	TOGGLE__SKIP_JOIN
)

type Toggles

type Toggles map[ToggleType]bool

func TogglesFromContext

func TogglesFromContext(ctx context.Context) Toggles

func (Toggles) Is

func (ts Toggles) Is(key ToggleType) bool

func (Toggles) Merge

func (ts Toggles) Merge(next Toggles) Toggles

type WithColumnComment

type WithColumnComment interface {
	ColumnComment() map[string]string
}

type WithColumnDesc

type WithColumnDesc interface {
	ColumnDesc() map[string][]string
}

type WithColumnRel

type WithColumnRel interface {
	ColumnRel() map[string][]string
}

type WithDatabase

type WithDatabase interface {
	WithDatabase(database string) Table
}

type WithDatatypeDesc

type WithDatatypeDesc interface {
	DBType(driver string) string
}

type WithIndexes

type WithIndexes interface {
	// Indexes returns field name => []string{index name, options...}
	Indexes() map[string][]string
}

type WithPrimaryKey

type WithPrimaryKey interface {
	PrimaryKey() []string
}

type WithSchema

type WithSchema interface {
	WithSchema(schema string) Table
}

type WithStmt

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

func With

func With(t Table, q SubQuery, modifiers ...string) *WithStmt

func WithRecursive

func WithRecursive(t Table, q SubQuery) *WithStmt

func (WithStmt) Exec

func (w WithStmt) Exec(stmt func(...Table) frag.Fragment) *WithStmt

func (*WithStmt) Frag

func (w *WithStmt) Frag(ctx context.Context) frag.Iter

func (*WithStmt) IsNil

func (w *WithStmt) IsNil() bool

func (WithStmt) With

func (w WithStmt) With(t Table, q SubQuery) *WithStmt

type WithTable

type WithTable interface {
	T() Table
}

type WithTableDesc

type WithTableDesc interface {
	TableDesc() []string
}

type WithTableName

type WithTableName interface {
	WithTableName(name string) Table
}

type WithUniqueIndexes

type WithUniqueIndexes interface {
	// UniqueIndexes returns field name => []string{index name, options...}
	UniqueIndexes() map[string][]string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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