sql

package
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2024 License: Apache-2.0 Imports: 11 Imported by: 249

Documentation

Overview

Package sql provides wrappers around the standard database/sql package to allow the generated code to interact with a statically-typed API.

Users that are interacting with this package should be aware that the following builders don't check the given SQL syntax nor validate or escape user-inputs. ~All validations are expected to be happened in the generated fluent package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AndPredicates

func AndPredicates[P ~func(*Selector)](predicates ...P) func(*Selector)

AndPredicates returns a new predicate for joining multiple generated predicates with AND between them.

func As

func As(ident string, as string) string

As suffixed the given column with an alias (`a` AS `b`).

func Asc

func Asc(column string) string

Asc adds the ASC suffix for the given column.

func Avg

func Avg(ident string) string

Avg wraps the ident with the AVG aggregation function.

func Count

func Count(ident string) string

Count wraps the ident with the COUNT aggregation function.

func Desc

func Desc(column string) string

Desc adds the DESC suffix for the given column.

func Distinct

func Distinct(idents ...string) string

Distinct prefixed the given columns with the `DISTINCT` keyword (DISTINCT `id`).

func FieldContains

func FieldContains(name string, substr string) func(*Selector)

FieldContains returns a raw predicate to check if the field contains the given substring.

func FieldContainsFold

func FieldContainsFold(name string, substr string) func(*Selector)

FieldContainsFold returns a raw predicate to check if the field contains the given substring with case-folding.

func FieldEQ

func FieldEQ(name string, v any) func(*Selector)

FieldEQ returns a raw predicate to check if the given field equals to the given value.

func FieldEqualFold

func FieldEqualFold(name string, substr string) func(*Selector)

FieldEqualFold returns a raw predicate to check if the field has the given prefix with case-folding.

func FieldGT

func FieldGT(name string, v any) func(*Selector)

FieldGT returns a raw predicate to check if the given field is greater than the given value.

func FieldGTE

func FieldGTE(name string, v any) func(*Selector)

FieldGTE returns a raw predicate to check if the given field is greater than or equal the given value.

func FieldHasPrefix

func FieldHasPrefix(name string, prefix string) func(*Selector)

FieldHasPrefix returns a raw predicate to check if the field has the given prefix.

func FieldHasPrefixFold

func FieldHasPrefixFold(name string, prefix string) func(*Selector)

FieldHasPrefixFold returns a raw predicate to check if the field has the given prefix with case-folding

func FieldHasSuffix

func FieldHasSuffix(name string, suffix string) func(*Selector)

FieldHasSuffix returns a raw predicate to check if the field has the given suffix.

func FieldHasSuffixFold

func FieldHasSuffixFold(name string, suffix string) func(*Selector)

FieldHasSuffixFold returns a raw predicate to check if the field has the given suffix with case-folding

func FieldIn

func FieldIn[T any](name string, vs ...T) func(*Selector)

FieldIn returns a raw predicate to check if the value of the field is IN the given values.

func FieldIsNull

func FieldIsNull(name string) func(*Selector)

FieldIsNull returns a raw predicate to check if the given field is NULL.

func FieldLT

func FieldLT(name string, v any) func(*Selector)

FieldLT returns a raw predicate to check if the value of the field is less than the given value.

func FieldLTE

func FieldLTE(name string, v any) func(*Selector)

FieldLTE returns a raw predicate to check if the value of the field is less than the given value.

func FieldNEQ

func FieldNEQ(name string, v any) func(*Selector)

FieldNEQ returns a raw predicate to check if the given field does not equal to the given value.

func FieldNotIn

func FieldNotIn[T any](name string, vs ...T) func(*Selector)

FieldNotIn returns a raw predicate to check if the value of the field is NOT IN the given values.

func FieldNotNull

func FieldNotNull(name string) func(*Selector)

FieldNotNull returns a raw predicate to check if the given field is not NULL.

func FieldsEQ

func FieldsEQ(field1, field2 string) func(*Selector)

FieldsEQ returns a raw predicate to check if the given fields (columns) are equal.

func FieldsGT

func FieldsGT(field1, field2 string) func(*Selector)

FieldsGT returns a raw predicate to check if field1 is greater than field2.

func FieldsGTE

func FieldsGTE(field1, field2 string) func(*Selector)

FieldsGTE returns a raw predicate to check if field1 is greater than or equal field2.

func FieldsHasPrefix

func FieldsHasPrefix(field1, field2 string) func(*Selector)

FieldsHasPrefix returns a raw predicate to checks if field1 begins with the value of field2.

func FieldsLT

func FieldsLT(field1, field2 string) func(*Selector)

FieldsLT returns a raw predicate to check if field1 is lower than field2.

func FieldsLTE

func FieldsLTE(field1, field2 string) func(*Selector)

FieldsLTE returns a raw predicate to check if field1 is lower than or equal field2.

func FieldsNEQ

func FieldsNEQ(field1, field2 string) func(*Selector)

FieldsNEQ returns a raw predicate to check if the given fields (columns) are not equal.

func Lower

func Lower(ident string) string

Lower wraps the given column with the LOWER function.

P().EQ(sql.Lower("name"), "a8m")

func Max

func Max(ident string) string

Max wraps the ident with the MAX aggregation function.

func Min

func Min(ident string) string

Min wraps the ident with the MIN aggregation function.

func NotPredicates

func NotPredicates[P ~func(*Selector)](predicates ...P) func(*Selector)

NotPredicates wraps the generated predicates with NOT. For example, NOT(P), NOT((P1 AND P2)).

func OrPredicates

func OrPredicates[P ~func(*Selector)](predicates ...P) func(*Selector)

OrPredicates returns a new predicate for joining multiple generated predicates with OR between them.

func OrderByRand

func OrderByRand() func(*Selector)

OrderByRand returns a term to natively order by a random value.

func ScanBool

func ScanBool(rows ColumnScanner) (bool, error)

ScanBool scans and returns a boolean from the rows.

func ScanInt

func ScanInt(rows ColumnScanner) (int, error)

ScanInt scans and returns an int from the rows.

func ScanInt64

func ScanInt64(rows ColumnScanner) (int64, error)

ScanInt64 scans and returns an int64 from the rows.

func ScanOne

func ScanOne(rows ColumnScanner, v any) error

ScanOne scans one row to the given value. It fails if the rows holds more than 1 row.

func ScanSlice

func ScanSlice(rows ColumnScanner, v any) error

ScanSlice scans the given ColumnScanner (basically, sql.Row or sql.Rows) into the given slice.

func ScanString

func ScanString(rows ColumnScanner) (string, error)

ScanString scans and returns a string from the rows.

func ScanTypeOf

func ScanTypeOf(rows *Rows, i int) any

ScanTypeOf returns the type used for scanning column i from the database.

func ScanValue

func ScanValue(rows ColumnScanner) (driver.Value, error)

ScanValue scans and returns a driver.Value from the rows.

func Sum

func Sum(ident string) string

Sum wraps the ident with the SUM aggregation function.

func WithIntVar

func WithIntVar(ctx context.Context, name string, value int) context.Context

WithIntVar calls WithVar with the string representation of the value.

func WithVar

func WithVar(ctx context.Context, name, value string) context.Context

WithVar returns a new context that holds the session variable to be executed before every query.

Types

type Builder

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

Builder is the base query builder for the sql dsl.

func (*Builder) AddError

func (b *Builder) AddError(err error) *Builder

AddError appends an error to the builder errors.

func (*Builder) Arg

func (b *Builder) Arg(a any) *Builder

Arg appends an input argument to the builder.

func (*Builder) Argf

func (b *Builder) Argf(format string, a any) *Builder

Argf appends an input argument to the builder with the given format. For example:

FormatArg("JSON(?)", b).
FormatArg("ST_GeomFromText(?)", geom)

func (*Builder) Args

func (b *Builder) Args(a ...any) *Builder

Args appends a list of arguments to the builder.

func (*Builder) Comma

func (b *Builder) Comma() *Builder

Comma adds a comma to the query.

func (Builder) Dialect

func (b Builder) Dialect() string

Dialect returns the dialect of the builder.

func (*Builder) Err

func (b *Builder) Err() error

Err returns a concatenated error of all errors encountered during the query-building, or were added manually by calling AddError.

func (*Builder) Ident

func (b *Builder) Ident(s string) *Builder

Ident appends the given string as an identifier.

func (*Builder) IdentComma

func (b *Builder) IdentComma(s ...string) *Builder

IdentComma calls Ident on all arguments and adds a comma between them.

func (*Builder) Join

func (b *Builder) Join(qs ...Querier) *Builder

Join joins a list of Queries to the builder.

func (*Builder) JoinComma

func (b *Builder) JoinComma(qs ...Querier) *Builder

JoinComma joins a list of Queries and adds comma between them.

func (*Builder) Len

func (b *Builder) Len() int

Len returns the number of accumulated bytes.

func (*Builder) Nested deprecated

func (b *Builder) Nested(f func(*Builder)) *Builder

Nested gets a callback, and wraps its result with parentheses.

Deprecated: Use Builder.Wrap instead.

func (*Builder) Pad

func (b *Builder) Pad() *Builder

Pad adds a space to the query.

func (Builder) Query

func (b Builder) Query() (string, []any)

Query implements the Querier interface.

func (*Builder) Quote

func (b *Builder) Quote(ident string) string

Quote quotes the given identifier with the characters based on the configured dialect. It defaults to "`".

func (*Builder) Reset

func (b *Builder) Reset() *Builder

Reset resets the Builder to be empty.

func (*Builder) S

func (b *Builder) S(s string) *Builder

S is a short version of WriteString.

func (*Builder) SetDialect

func (b *Builder) SetDialect(dialect string)

SetDialect sets the builder dialect. It's used for garnering dialect specific queries.

func (*Builder) SetTotal

func (b *Builder) SetTotal(total int)

SetTotal sets the value of the total arguments. Used to pass this information between sub queries/expressions.

func (*Builder) String

func (b *Builder) String() string

String returns the accumulated string.

func (Builder) Total

func (b Builder) Total() int

Total returns the total number of arguments so far.

func (*Builder) Wrap

func (b *Builder) Wrap(f func(*Builder)) *Builder

Wrap gets a callback, and wraps its result with parentheses.

func (*Builder) WriteByte

func (b *Builder) WriteByte(c byte) *Builder

WriteByte wraps the Buffer.WriteByte to make it chainable with other methods.

func (*Builder) WriteOp

func (b *Builder) WriteOp(op Op) *Builder

WriteOp writes an operator to the builder.

func (*Builder) WriteString

func (b *Builder) WriteString(s string) *Builder

WriteString wraps the Buffer.WriteString to make it chainable with other methods.

type ColumnBuilder

type ColumnBuilder struct {
	Builder
	// contains filtered or unexported fields
}

ColumnBuilder is a builder for column definition in table creation.

func Column

func Column(name string) *ColumnBuilder

Column returns a new ColumnBuilder with the given name.

sql.Column("group_id").Type("int").Attr("UNIQUE")

func (*ColumnBuilder) Attr

func (c *ColumnBuilder) Attr(attr string) *ColumnBuilder

Attr sets an extra attribute for the column, like UNIQUE or AUTO_INCREMENT.

func (*ColumnBuilder) Check

func (c *ColumnBuilder) Check(check func(*Builder)) *ColumnBuilder

Check adds a CHECK clause to the ADD COLUMN statement.

func (*ColumnBuilder) Constraint

func (c *ColumnBuilder) Constraint(fk *ForeignKeyBuilder) *ColumnBuilder

Constraint adds the CONSTRAINT clause to the ADD COLUMN statement in SQLite.

func (*ColumnBuilder) Query

func (c *ColumnBuilder) Query() (string, []any)

Query returns query representation of a Column.

func (*ColumnBuilder) Type

func (c *ColumnBuilder) Type(t string) *ColumnBuilder

Type sets the column type.

type ColumnCheck

type ColumnCheck func(table, column string) error

ColumnCheck is a function that verifies whether the specified column exists within the given table.

func NewColumnCheck

func NewColumnCheck(checks map[string]func(string) bool) ColumnCheck

NewColumnCheck returns a function that verifies whether the specified column exists within the given table. This function is utilized by the generated code to validate column names in ordering functions.

type ColumnScanner

type ColumnScanner interface {
	Close() error
	ColumnTypes() ([]*sql.ColumnType, error)
	Columns() ([]string, error)
	Err() error
	Next() bool
	NextResultSet() bool
	Scan(dest ...any) error
}

ColumnScanner is the interface that wraps the standard sql.Rows methods used for scanning database rows.

type ConflictOption

type ConflictOption func(*conflict)

ConflictOption allows configuring the conflict config using functional options.

func ConflictColumns

func ConflictColumns(names ...string) ConflictOption

ConflictColumns sets the unique constraints that trigger the conflict resolution on insert to perform an upsert operation. The columns must have a unique constraint applied to trigger this behaviour.

sql.Insert("users").
	Columns("id", "name").
	Values(1, "Mashraki").
	OnConflict(
		sql.ConflictColumns("id"),
		sql.ResolveWithNewValues(),
	)

func ConflictConstraint

func ConflictConstraint(name string) ConflictOption

ConflictConstraint allows setting the constraint name (i.e. `ON CONSTRAINT <name>`) for PostgreSQL.

sql.Insert("users").
	Columns("id", "name").
	Values(1, "Mashraki").
	OnConflict(
		sql.ConflictConstraint("users_pkey"),
		sql.ResolveWithNewValues(),
	)

func ConflictWhere

func ConflictWhere(p *Predicate) ConflictOption

ConflictWhere allows inference of partial unique indexes. See, PostgreSQL doc: https://www.postgresql.org/docs/current/sql-insert.html#SQL-ON-CONFLICT

func DoNothing

func DoNothing() ConflictOption

DoNothing configures the conflict_action to `DO NOTHING`. Supported by SQLite and PostgreSQL.

sql.Insert("users").
	Columns("id", "name").
	Values(1, "Mashraki").
	OnConflict(
		sql.ConflictColumns("id"),
		sql.DoNothing()
	)

func ResolveWith

func ResolveWith(fn func(*UpdateSet)) ConflictOption

ResolveWith allows setting a custom function to set the `UPDATE` clause.

Insert("users").
	Columns("id", "name").
	Values(1, "Mashraki").
	OnConflict(
		ConflictColumns("name"),
		ResolveWith(func(u *UpdateSet) {
			u.SetIgnore("id")
			u.SetNull("created_at")
			u.Set("name", Expr(u.Excluded().C("name")))
		}),
	)

func ResolveWithIgnore

func ResolveWithIgnore() ConflictOption

ResolveWithIgnore sets each column to itself to force an update and return the ID, otherwise does not change any data. This may still trigger update hooks in the database.

sql.Insert("users").
	Columns("id").
	Values(1).
	OnConflict(
		sql.ConflictColumns("id"),
		sql.ResolveWithIgnore()
	)

// Output:
// MySQL: INSERT INTO `users` (`id`) VALUES(1) ON DUPLICATE KEY UPDATE `id` = `users`.`id`
// PostgreSQL: INSERT INTO "users" ("id") VALUES(1) ON CONFLICT ("id") DO UPDATE SET "id" = "users"."id

func ResolveWithNewValues

func ResolveWithNewValues() ConflictOption

ResolveWithNewValues updates columns using the new values proposed for insertion using the special EXCLUDED/VALUES table.

sql.Insert("users").
	Columns("id", "name").
	Values(1, "Mashraki").
	OnConflict(
		sql.ConflictColumns("id"),
		sql.ResolveWithNewValues()
	)

// Output:
// MySQL: INSERT INTO `users` (`id`, `name`) VALUES(1, 'Mashraki) ON DUPLICATE KEY UPDATE `id` = VALUES(`id`), `name` = VALUES(`name`),
// PostgreSQL: INSERT INTO "users" ("id") VALUES(1) ON CONFLICT ("id") DO UPDATE SET "id" = "excluded"."id, "name" = "excluded"."name"

func UpdateWhere

func UpdateWhere(p *Predicate) ConflictOption

UpdateWhere allows setting the update condition. Only rows for which this expression returns true will be updated.

type Conn

type Conn struct {
	ExecQuerier
}

Conn implements dialect.ExecQuerier given ExecQuerier.

func (Conn) Exec

func (c Conn) Exec(ctx context.Context, query string, args, v any) (rerr error)

Exec implements the dialect.Exec method.

func (Conn) Query

func (c Conn) Query(ctx context.Context, query string, args, v any) error

Query implements the dialect.Query method.

type DeleteBuilder

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

DeleteBuilder is a builder for `DELETE` statement.

func Delete

func Delete(table string) *DeleteBuilder

Delete creates a builder for the `DELETE` statement.

Delete("users").
	Where(
		Or(
			EQ("name", "foo").And().EQ("age", 10),
			EQ("name", "bar").And().EQ("age", 20),
			And(
				EQ("name", "qux"),
				EQ("age", 1).Or().EQ("age", 2),
			),
		),
	)

func (*DeleteBuilder) FromSelect

func (d *DeleteBuilder) FromSelect(s *Selector) *DeleteBuilder

FromSelect makes it possible to delete a sub query.

func (*DeleteBuilder) Query

func (d *DeleteBuilder) Query() (string, []any)

Query returns query representation of a `DELETE` statement.

func (*DeleteBuilder) Schema

func (d *DeleteBuilder) Schema(name string) *DeleteBuilder

Schema sets the database name for the table whose row will be deleted.

func (*DeleteBuilder) Where

func (d *DeleteBuilder) Where(p *Predicate) *DeleteBuilder

Where appends a where predicate to the `DELETE` statement.

type DescribeBuilder

type DescribeBuilder struct {
	Builder
	// contains filtered or unexported fields
}

DescribeBuilder is a query builder for `DESCRIBE` statement.

func Describe

func Describe(name string) *DescribeBuilder

Describe returns a query builder for the `DESCRIBE` statement.

Describe("users")

func (*DescribeBuilder) Query

func (t *DescribeBuilder) Query() (string, []any)

Query returns query representation of a `DESCRIBE` statement.

type DialectBuilder

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

DialectBuilder prefixes all root builders with the `Dialect` constructor.

func Dialect

func Dialect(name string) *DialectBuilder

Dialect creates a new DialectBuilder with the given dialect name.

func (*DialectBuilder) AlterIndex

func (d *DialectBuilder) AlterIndex(name string) *IndexAlter

AlterIndex creates an IndexAlter for the configured dialect.

Dialect(dialect.Postgres).
	AlterIndex("old").
	Rename("new")

func (*DialectBuilder) AlterTable

func (d *DialectBuilder) AlterTable(name string) *TableAlter

AlterTable creates a TableAlter for the configured dialect.

Dialect(dialect.Postgres).
	AlterTable("users").
	AddColumn(Column("group_id").Type("int").Attr("UNIQUE")).
	AddForeignKey(ForeignKey().Columns("group_id").
		Reference(Reference().Table("groups").Columns("id")).
		OnDelete("CASCADE"),
	)

func (*DialectBuilder) Column

func (d *DialectBuilder) Column(name string) *ColumnBuilder

Column creates a ColumnBuilder for the configured dialect.

Dialect(dialect.Postgres)..
	Column("group_id").Type("int").Attr("UNIQUE")

func (*DialectBuilder) CreateIndex

func (d *DialectBuilder) CreateIndex(name string) *IndexBuilder

CreateIndex creates a IndexBuilder for the configured dialect.

Dialect(dialect.Postgres).
	CreateIndex("unique_name").
	Unique().
	Table("users").
	Columns("first", "last")

func (*DialectBuilder) CreateTable

func (d *DialectBuilder) CreateTable(name string) *TableBuilder

CreateTable creates a TableBuilder for the configured dialect.

Dialect(dialect.Postgres).
	CreateTable("users").
		Columns(
			Column("id").Type("int").Attr("auto_increment"),
			Column("name").Type("varchar(255)"),
		).
		PrimaryKey("id")

func (*DialectBuilder) Delete

func (d *DialectBuilder) Delete(table string) *DeleteBuilder

Delete creates a DeleteBuilder for the configured dialect.

Dialect(dialect.Postgres).
	Delete().From("users")

func (*DialectBuilder) Describe

func (d *DialectBuilder) Describe(name string) *DescribeBuilder

Describe creates a DescribeBuilder for the configured dialect.

Dialect(dialect.Postgres).
	Describe("users")

func (*DialectBuilder) DropIndex

func (d *DialectBuilder) DropIndex(name string) *DropIndexBuilder

DropIndex creates a DropIndexBuilder for the configured dialect.

Dialect(dialect.Postgres).
	DropIndex("name")

func (*DialectBuilder) Expr

func (d *DialectBuilder) Expr(f func(*Builder)) Querier

Expr builds a dialect-aware expression from the given callback.

func (*DialectBuilder) Insert

func (d *DialectBuilder) Insert(table string) *InsertBuilder

Insert creates a InsertBuilder for the configured dialect.

Dialect(dialect.Postgres).
	Insert("users").Columns("age").Values(1)

func (*DialectBuilder) Select

func (d *DialectBuilder) Select(columns ...string) *Selector

Select creates a Selector for the configured dialect.

Dialect(dialect.Postgres).
	Select().From(Table("users"))

func (*DialectBuilder) SelectExpr

func (d *DialectBuilder) SelectExpr(exprs ...Querier) *Selector

SelectExpr is like Select, but supports passing arbitrary expressions for SELECT clause.

Dialect(dialect.Postgres).
	SelectExpr(expr...).
	From(Table("users"))

func (*DialectBuilder) String

func (d *DialectBuilder) String(f func(*Builder)) string

String builds a dialect-aware expression string from the given callback.

func (*DialectBuilder) Table

func (d *DialectBuilder) Table(name string) *SelectTable

Table creates a SelectTable for the configured dialect.

Dialect(dialect.Postgres).
	Table("users").As("u")

func (*DialectBuilder) Update

func (d *DialectBuilder) Update(table string) *UpdateBuilder

Update creates a UpdateBuilder for the configured dialect.

Dialect(dialect.Postgres).
	Update("users").Set("name", "foo")

func (*DialectBuilder) With

func (d *DialectBuilder) With(name string) *WithBuilder

With creates a WithBuilder for the configured dialect.

Dialect(dialect.Postgres).
	With("users_view").
	As(Select().From(Table("users")))

type Driver

type Driver struct {
	Conn
	// contains filtered or unexported fields
}

Driver is a dialect.Driver implementation for SQL based databases.

func NewDriver

func NewDriver(dialect string, c Conn) *Driver

NewDriver creates a new Driver with the given Conn and dialect.

func Open

func Open(dialect, source string) (*Driver, error)

Open wraps the database/sql.Open method and returns a dialect.Driver that implements the an fluent/dialect.Driver interface.

func OpenDB

func OpenDB(dialect string, db *sql.DB) *Driver

OpenDB wraps the given database/sql.DB method with a Driver.

func (*Driver) BeginTx

func (d *Driver) BeginTx(ctx context.Context, opts *TxOptions) (dialect.Tx, error)

BeginTx starts a transaction with options.

func (*Driver) Close

func (d *Driver) Close() error

Close closes the underlying connection.

func (Driver) DB

func (d Driver) DB() *sql.DB

DB returns the underlying *sql.DB instance.

func (Driver) Dialect

func (d Driver) Dialect() string

Dialect implements the dialect.Dialect method.

func (*Driver) Tx

func (d *Driver) Tx(ctx context.Context) (dialect.Tx, error)

Tx starts and returns a transaction.

type DropIndexBuilder

type DropIndexBuilder struct {
	Builder
	// contains filtered or unexported fields
}

DropIndexBuilder is a builder for `DROP INDEX` statement.

func DropIndex

func DropIndex(name string) *DropIndexBuilder

DropIndex creates a builder for the `DROP INDEX` statement.

MySQL:

	DropIndex("index_name").
		Table("users").

SQLite/PostgreSQL:

	DropIndex("index_name")

func (*DropIndexBuilder) Query

func (d *DropIndexBuilder) Query() (string, []any)

Query returns query representation of a reference clause.

DROP INDEX index_name [ON table_name]

func (*DropIndexBuilder) Table

func (d *DropIndexBuilder) Table(table string) *DropIndexBuilder

Table defines the table for the index.

type ExecQuerier

type ExecQuerier interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}

ExecQuerier wraps the standard Exec and Query methods.

type ForeignKeyBuilder

type ForeignKeyBuilder struct {
	Builder
	// contains filtered or unexported fields
}

ForeignKeyBuilder is the builder for the foreign-key constraint clause.

func ForeignKey

func ForeignKey(symbol ...string) *ForeignKeyBuilder

ForeignKey returns a builder for the foreign-key constraint clause in create/alter table statements.

ForeignKey().
	Columns("group_id").
	Reference(Reference().Table("groups").Columns("id")).
	OnDelete("CASCADE")

func (*ForeignKeyBuilder) Columns

func (fk *ForeignKeyBuilder) Columns(s ...string) *ForeignKeyBuilder

Columns sets the columns of the foreign key in the source table.

func (*ForeignKeyBuilder) OnDelete

func (fk *ForeignKeyBuilder) OnDelete(action string) *ForeignKeyBuilder

OnDelete sets the on delete action for this constraint.

func (*ForeignKeyBuilder) OnUpdate

func (fk *ForeignKeyBuilder) OnUpdate(action string) *ForeignKeyBuilder

OnUpdate sets the on delete action for this constraint.

func (*ForeignKeyBuilder) Query

func (fk *ForeignKeyBuilder) Query() (string, []any)

Query returns query representation of a foreign key constraint.

func (*ForeignKeyBuilder) Reference

Reference sets the reference clause.

func (*ForeignKeyBuilder) Symbol

Symbol sets the symbol of the foreign key.

type Func

type Func struct {
	Builder
	// contains filtered or unexported fields
}

Func represents an SQL function.

func (*Func) Append

func (f *Func) Append(fn func(*Builder)) *Func

Append appends a new function to the function callbacks. The callback list are executed on call to String.

func (*Func) Avg

func (f *Func) Avg(ident string)

Avg wraps the ident with the AVG aggregation function.

func (*Func) Count

func (f *Func) Count(ident string)

Count wraps the ident with the COUNT aggregation function.

func (*Func) Lower

func (f *Func) Lower(ident string)

Lower wraps the given ident with the LOWER function.

func (*Func) Max

func (f *Func) Max(ident string)

Max wraps the ident with the MAX aggregation function.

func (*Func) Min

func (f *Func) Min(ident string)

Min wraps the ident with the MIN aggregation function.

func (*Func) String

func (f *Func) String() string

String implements the fmt.Stringer.

func (*Func) Sum

func (f *Func) Sum(ident string)

Sum wraps the ident with the SUM aggregation function.

type IndexAlter

type IndexAlter struct {
	Builder

	Queries []Querier // alter options.
	// contains filtered or unexported fields
}

IndexAlter is a query builder for `ALTER INDEX` statement.

func AlterIndex

func AlterIndex(name string) *IndexAlter

AlterIndex returns a query builder for the `ALTER INDEX` statement.

AlterIndex("old_key").
	Rename("new_key")

func (*IndexAlter) Query

func (i *IndexAlter) Query() (string, []any)

Query returns query representation of the `ALTER INDEX` statement.

ALTER INDEX name
	[alter_specification]

func (*IndexAlter) Rename

func (i *IndexAlter) Rename(name string) *IndexAlter

Rename appends the `RENAME TO` clause to the `ALTER INDEX` statement.

type IndexBuilder

type IndexBuilder struct {
	Builder
	// contains filtered or unexported fields
}

IndexBuilder is a builder for `CREATE INDEX` statement.

func CreateIndex

func CreateIndex(name string) *IndexBuilder

CreateIndex creates a builder for the `CREATE INDEX` statement.

CreateIndex("index_name").
	Unique().
	Table("users").
	Column("name")

Or:

CreateIndex("index_name").
	Unique().
	Table("users").
	Columns("name", "age")

func (*IndexBuilder) Column

func (i *IndexBuilder) Column(column string) *IndexBuilder

Column appends a column to the column list for the index.

func (*IndexBuilder) Columns

func (i *IndexBuilder) Columns(columns ...string) *IndexBuilder

Columns appends the given columns to the column list for the index.

func (*IndexBuilder) IfNotExists

func (i *IndexBuilder) IfNotExists() *IndexBuilder

IfNotExists appends the `IF NOT EXISTS` clause to the `CREATE INDEX` statement.

func (*IndexBuilder) Query

func (i *IndexBuilder) Query() (string, []any)

Query returns query representation of a reference clause.

func (*IndexBuilder) Table

func (i *IndexBuilder) Table(table string) *IndexBuilder

Table defines the table for the index.

func (*IndexBuilder) Unique

func (i *IndexBuilder) Unique() *IndexBuilder

Unique sets the index to be a unique index.

func (*IndexBuilder) Using

func (i *IndexBuilder) Using(method string) *IndexBuilder

Using sets the method to create the index with.

type InsertBuilder

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

InsertBuilder is a builder for `INSERT INTO` statement.

func Insert

func Insert(table string) *InsertBuilder

Insert creates a builder for the `INSERT INTO` statement.

Insert("users").
	Columns("name", "age").
	Values("a8m", 10).
	Values("foo", 20)

Note: Insert inserts all values in one batch.

func (*InsertBuilder) Columns

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

Columns appends columns to the INSERT statement.

func (*InsertBuilder) Default

func (i *InsertBuilder) Default() *InsertBuilder

Default sets the default values clause based on the dialect type.

func (*InsertBuilder) OnConflict

func (i *InsertBuilder) OnConflict(opts ...ConflictOption) *InsertBuilder

OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause of the `INSERT` statement. For example:

sql.Insert("users").
	Columns("id", "name").
	Values(1, "Mashraki").
	OnConflict(
		sql.ConflictColumns("id"),
		sql.ResolveWithNewValues()
	)

func (*InsertBuilder) Query

func (i *InsertBuilder) Query() (string, []any)

Query returns query representation of an `INSERT INTO` statement.

func (*InsertBuilder) QueryErr

func (i *InsertBuilder) QueryErr() (string, []any, error)

QueryErr returns query representation of an `INSERT INTO` statement and any error occurred in building the statement.

func (*InsertBuilder) Returning

func (i *InsertBuilder) Returning(columns ...string) *InsertBuilder

Returning adds the `RETURNING` clause to the insert statement. Supported by SQLite and PostgreSQL.

func (*InsertBuilder) Schema

func (i *InsertBuilder) Schema(name string) *InsertBuilder

Schema sets the database name for the insert table.

func (*InsertBuilder) Set

func (i *InsertBuilder) Set(column string, v any) *InsertBuilder

Set is a syntactic sugar API for inserting only one row.

func (*InsertBuilder) Values

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

Values append a value tuple for the insert statement.

type LockAction

type LockAction string

LockAction tells the transaction what to do in case of requesting a row that is locked by other transaction.

const (
	// NoWait means never wait and returns an error.
	NoWait LockAction = "NOWAIT"
	// SkipLocked means never wait and skip.
	SkipLocked LockAction = "SKIP LOCKED"
)

type LockOption

type LockOption func(*LockOptions)

LockOption allows configuring the LockOptions using functional options.

func WithLockAction

func WithLockAction(action LockAction) LockOption

WithLockAction sets the Action of the lock.

func WithLockClause

func WithLockClause(clause string) LockOption

WithLockClause allows providing a custom clause for locking the statement. For example, in MySQL <= 8.22:

Select().
From(Table("users")).
ForShare(
	WithLockClause("LOCK IN SHARE MODE"),
)

func WithLockTables

func WithLockTables(tables ...string) LockOption

WithLockTables sets the Tables of the lock.

type LockOptions

type LockOptions struct {
	// Strength of the lock.
	Strength LockStrength
	// Action of the lock.
	Action LockAction
	// Tables are an option tables.
	Tables []string
	// contains filtered or unexported fields
}

LockOptions defines a SELECT statement lock for protecting concurrent updates.

type LockStrength

type LockStrength string

LockStrength defines the strength of the lock (see the list below).

const (
	LockShare       LockStrength = "SHARE"
	LockUpdate      LockStrength = "UPDATE"
	LockNoKeyUpdate LockStrength = "NO KEY UPDATE"
	LockKeyShare    LockStrength = "KEY SHARE"
)

A list of all locking clauses.

type NullBool

type NullBool = sql.NullBool

NullBool is an alias to sql.NullBool.

type NullFloat64

type NullFloat64 = sql.NullFloat64

NullFloat64 is an alias to sql.NullFloat64.

type NullInt64

type NullInt64 = sql.NullInt64

NullInt64 is an alias to sql.NullInt64.

type NullScanner

type NullScanner struct {
	S     sql.Scanner
	Valid bool // Valid is true if the Scan value is not NULL.
}

NullScanner implements the sql.Scanner interface such that it can be used as a scan destination, similar to the types above.

func (*NullScanner) Scan

func (n *NullScanner) Scan(value any) error

Scan implements the Scanner interface.

type NullString

type NullString = sql.NullString

NullString is an alias to sql.NullString.

type NullTime

type NullTime = sql.NullTime

NullTime represents a time.Time that may be null.

type Op

type Op int

An Op represents an operator.

const (
	OpEQ      Op = iota // =
	OpNEQ               // <>
	OpGT                // >
	OpGTE               // >=
	OpLT                // <
	OpLTE               // <=
	OpIn                // IN
	OpNotIn             // NOT IN
	OpLike              // LIKE
	OpIsNull            // IS NULL
	OpNotNull           // IS NOT NULL
	OpAdd               // +
	OpSub               // -
	OpMul               // *
	OpDiv               // / (Quotient)
	OpMod               // % (Reminder)
)

Predicate and arithmetic operators.

type OrderExprTerm

type OrderExprTerm struct {
	OrderTermOptions
	Expr func(*Selector) Querier // Expression.
}

OrderExprTerm represents an ordering by an expression.

func OrderByCount

func OrderByCount(field string, opts ...OrderTermOption) *OrderExprTerm

OrderByCount returns an ordering by the count of the given field.

func OrderBySum

func OrderBySum(field string, opts ...OrderTermOption) *OrderExprTerm

OrderBySum returns an ordering by the sum of the given field.

type OrderFieldTerm

type OrderFieldTerm struct {
	OrderTermOptions
	Field string // Field name.
}

OrderFieldTerm represents an ordering by a field.

func OrderByField

func OrderByField(field string, opts ...OrderTermOption) *OrderFieldTerm

OrderByField returns an ordering by the given field.

func (*OrderFieldTerm) ToFunc

func (f *OrderFieldTerm) ToFunc() func(*Selector)

ToFunc returns a function that sets the ordering on the given selector. This is used by the generated code.

type OrderTerm

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

OrderTerm represents an ordering by a term.

type OrderTermOption

type OrderTermOption func(*OrderTermOptions)

OrderTermOption is an option for ordering by a term.

func OrderAs

func OrderAs(as string) OrderTermOption

OrderAs returns an option to set the alias for the ordering.

func OrderAsc

func OrderAsc() OrderTermOption

OrderAsc returns an option to sort in ascending order.

func OrderDesc

func OrderDesc() OrderTermOption

OrderDesc returns an option to sort in descending order.

func OrderNullsFirst

func OrderNullsFirst() OrderTermOption

OrderNullsFirst returns an option to sort nulls first.

func OrderNullsLast

func OrderNullsLast() OrderTermOption

OrderNullsLast returns an option to sort nulls last.

func OrderSelectAs

func OrderSelectAs(as string) OrderTermOption

OrderSelectAs returns an option to set and select the alias for the ordering.

func OrderSelected

func OrderSelected() OrderTermOption

OrderSelected returns an option to select the ordering term.

type OrderTermOptions

type OrderTermOptions struct {
	Desc       bool   // Whether to sort in descending order.
	As         string // Optional alias.
	Selected   bool   // Whether the term should be selected.
	NullsFirst bool   // Whether to sort nulls first.
	NullsLast  bool   // Whether to sort nulls last.
}

OrderTermOptions represents options for ordering by a term.

func NewOrderTermOptions

func NewOrderTermOptions(opts ...OrderTermOption) *OrderTermOptions

NewOrderTermOptions returns a new OrderTermOptions from the given options.

type ParamFormatter

type ParamFormatter interface {
	// The FormatParam function lets users define
	// custom placeholder formatting for their types.
	// For example, formatting the default placeholder
	// from '?' to 'ST_GeomFromWKB(?)' for MySQL dialect.
	FormatParam(placeholder string, info *StmtInfo) string
}

ParamFormatter wraps the FormatPram function.

type Predicate

type Predicate struct {
	Builder
	// contains filtered or unexported fields
}

Predicate is a where predicate.

func And

func And(preds ...*Predicate) *Predicate

And combines all given predicates with AND between them.

func ColumnsEQ

func ColumnsEQ(col1, col2 string) *Predicate

ColumnsEQ appends a "=" predicate between 2 columns.

func ColumnsGT

func ColumnsGT(col1, col2 string) *Predicate

ColumnsGT appends a ">" predicate between 2 columns.

func ColumnsGTE

func ColumnsGTE(col1, col2 string) *Predicate

ColumnsGTE appends a ">=" predicate between 2 columns.

func ColumnsHasPrefix

func ColumnsHasPrefix(col, prefixC string) *Predicate

ColumnsHasPrefix appends a new predicate that checks if the given column begins with the other column (prefix).

func ColumnsLT

func ColumnsLT(col1, col2 string) *Predicate

ColumnsLT appends a "<" predicate between 2 columns.

func ColumnsLTE

func ColumnsLTE(col1, col2 string) *Predicate

ColumnsLTE appends a "<=" predicate between 2 columns.

func ColumnsNEQ

func ColumnsNEQ(col1, col2 string) *Predicate

ColumnsNEQ appends a "<>" predicate between 2 columns.

func ColumnsOp

func ColumnsOp(col1, col2 string, op Op) *Predicate

ColumnsOp returns a new predicate between 2 columns.

func CompositeGT

func CompositeGT(columns []string, args ...any) *Predicate

CompositeGT returns a composite ">" predicate

func CompositeLT

func CompositeLT(columns []string, args ...any) *Predicate

CompositeLT returns a composite "<" predicate

func Contains

func Contains(col, sub string) *Predicate

Contains is a helper predicate that checks substring using the LIKE predicate.

func ContainsFold

func ContainsFold(col, sub string) *Predicate

ContainsFold is a helper predicate that checks substring using the LIKE predicate with case-folding.

func EQ

func EQ(col string, value any) *Predicate

EQ returns a "=" predicate.

func EqualFold

func EqualFold(col, sub string) *Predicate

EqualFold is a helper predicate that applies the "=" predicate with case-folding.

func Exists

func Exists(query Querier) *Predicate

Exists returns the `Exists` predicate.

func ExprP

func ExprP(exr string, args ...any) *Predicate

ExprP creates a new predicate from the given expression.

ExprP("A = ? AND B > ?", args...)

func False

func False() *Predicate

False appends the FALSE keyword to the predicate.

Delete().From("users").Where(False())

func GT

func GT(col string, value any) *Predicate

GT returns a ">" predicate.

func GTE

func GTE(col string, value any) *Predicate

GTE returns a ">=" predicate.

func HasPrefix

func HasPrefix(col, prefix string) *Predicate

HasPrefix is a helper predicate that checks prefix using the LIKE predicate.

func HasPrefixFold

func HasPrefixFold(col, prefix string) *Predicate

HasPrefixFold is a helper predicate that checks prefix using the ILIKE predicate.

func HasSuffix

func HasSuffix(col, suffix string) *Predicate

HasSuffix is a helper predicate that checks suffix using the LIKE predicate.

func HasSuffixFold

func HasSuffixFold(col, suffix string) *Predicate

HasSuffixFold is a helper predicate that checks suffix using the ILIKE predicate.

func In

func In(col string, args ...any) *Predicate

In returns the `IN` predicate.

func InInts

func InInts(col string, args ...int) *Predicate

InInts returns the `IN` predicate for ints.

func InValues

func InValues(col string, args ...driver.Value) *Predicate

InValues adds the `IN` predicate for slice of driver.Value.

func IsFalse

func IsFalse(col string) *Predicate

IsFalse appends a predicate that checks if the column value is falsey.

func IsNull

func IsNull(col string) *Predicate

IsNull returns the `IS NULL` predicate.

func IsTrue

func IsTrue(col string) *Predicate

IsTrue appends a predicate that checks if the column value is truthy.

func LT

func LT(col string, value any) *Predicate

LT returns a "<" predicate.

func LTE

func LTE(col string, value any) *Predicate

LTE returns a "<=" predicate.

func Like

func Like(col, pattern string) *Predicate

Like returns the `LIKE` predicate.

func NEQ

func NEQ(col string, value any) *Predicate

NEQ returns a "<>" predicate.

func Not

func Not(pred *Predicate) *Predicate

Not wraps the given predicate with the not predicate.

Not(Or(EQ("name", "foo"), EQ("name", "bar")))

func NotExists

func NotExists(query Querier) *Predicate

NotExists returns the `NotExists` predicate.

func NotIn

func NotIn(col string, args ...any) *Predicate

NotIn returns the `Not IN` predicate.

func NotNull

func NotNull(col string) *Predicate

NotNull returns the `IS NOT NULL` predicate.

func Or

func Or(preds ...*Predicate) *Predicate

Or combines all given predicates with OR between them.

Or(EQ("name", "foo"), EQ("name", "bar"))

func P

func P(fns ...func(*Builder)) *Predicate

P creates a new predicate.

P().EQ("name", "a8m").And().EQ("age", 30)

func (*Predicate) Append

func (p *Predicate) Append(f func(*Builder)) *Predicate

Append appends a new function to the predicate callbacks. The callback list are executed on call to Query.

func (*Predicate) ColumnsEQ

func (p *Predicate) ColumnsEQ(col1, col2 string) *Predicate

ColumnsEQ appends a "=" predicate between 2 columns.

func (*Predicate) ColumnsGT

func (p *Predicate) ColumnsGT(col1, col2 string) *Predicate

ColumnsGT appends a ">" predicate between 2 columns.

func (*Predicate) ColumnsGTE

func (p *Predicate) ColumnsGTE(col1, col2 string) *Predicate

ColumnsGTE appends a ">=" predicate between 2 columns.

func (*Predicate) ColumnsHasPrefix

func (p *Predicate) ColumnsHasPrefix(col, prefixC string) *Predicate

ColumnsHasPrefix appends a new predicate that checks if the given column begins with the other column (prefix).

func (*Predicate) ColumnsLT

func (p *Predicate) ColumnsLT(col1, col2 string) *Predicate

ColumnsLT appends a "<" predicate between 2 columns.

func (*Predicate) ColumnsLTE

func (p *Predicate) ColumnsLTE(col1, col2 string) *Predicate

ColumnsLTE appends a "<=" predicate between 2 columns.

func (*Predicate) ColumnsNEQ

func (p *Predicate) ColumnsNEQ(col1, col2 string) *Predicate

ColumnsNEQ appends a "<>" predicate between 2 columns.

func (*Predicate) ColumnsOp

func (p *Predicate) ColumnsOp(col1, col2 string, op Op) *Predicate

ColumnsOp appends the given predicate between 2 columns.

func (*Predicate) CompositeGT

func (p *Predicate) CompositeGT(columns []string, args ...any) *Predicate

CompositeGT returns a composite ">" predicate.

func (*Predicate) CompositeLT

func (p *Predicate) CompositeLT(columns []string, args ...any) *Predicate

CompositeLT appends a composite "<" predicate.

func (*Predicate) Contains

func (p *Predicate) Contains(col, substr string) *Predicate

Contains is a helper predicate that checks substring using the LIKE predicate.

func (*Predicate) ContainsFold

func (p *Predicate) ContainsFold(col, substr string) *Predicate

ContainsFold is a helper predicate that applies the LIKE predicate with case-folding.

func (*Predicate) EQ

func (p *Predicate) EQ(col string, arg any) *Predicate

EQ appends a "=" predicate.

func (*Predicate) EqualFold

func (p *Predicate) EqualFold(col, sub string) *Predicate

EqualFold is a helper predicate that applies the "=" predicate with case-folding.

func (*Predicate) Exists

func (p *Predicate) Exists(query Querier) *Predicate

Exists appends the `EXISTS` predicate with the given query.

func (*Predicate) False

func (p *Predicate) False() *Predicate

False appends FALSE to the predicate.

func (*Predicate) GT

func (p *Predicate) GT(col string, arg any) *Predicate

GT appends a ">" predicate.

func (*Predicate) GTE

func (p *Predicate) GTE(col string, arg any) *Predicate

GTE appends a ">=" predicate.

func (*Predicate) HasPrefix

func (p *Predicate) HasPrefix(col, prefix string) *Predicate

HasPrefix is a helper predicate that checks prefix using the LIKE predicate.

func (*Predicate) HasPrefixFold

func (p *Predicate) HasPrefixFold(col, prefix string) *Predicate

HasPrefixFold is a helper predicate that checks prefix using the ILIKE predicate.

func (*Predicate) HasSuffix

func (p *Predicate) HasSuffix(col, suffix string) *Predicate

HasSuffix is a helper predicate that checks suffix using the LIKE predicate.

func (*Predicate) HasSuffixFold

func (p *Predicate) HasSuffixFold(col, suffix string) *Predicate

HasSuffixFold is a helper predicate that checks suffix using the ILIKE predicate.

func (*Predicate) In

func (p *Predicate) In(col string, args ...any) *Predicate

In appends the `IN` predicate.

func (*Predicate) InInts

func (p *Predicate) InInts(col string, args ...int) *Predicate

InInts adds the `IN` predicate for ints.

func (*Predicate) InValues

func (p *Predicate) InValues(col string, args ...driver.Value) *Predicate

InValues adds the `IN` predicate for slice of driver.Value.

func (*Predicate) IsFalse

func (p *Predicate) IsFalse(col string) *Predicate

IsFalse appends a predicate that checks if the column value is falsey.

func (*Predicate) IsNull

func (p *Predicate) IsNull(col string) *Predicate

IsNull appends the `IS NULL` predicate.

func (*Predicate) IsTrue

func (p *Predicate) IsTrue(col string) *Predicate

IsTrue appends a predicate that checks if the column value is truthy.

func (*Predicate) LT

func (p *Predicate) LT(col string, arg any) *Predicate

LT appends a "<" predicate.

func (*Predicate) LTE

func (p *Predicate) LTE(col string, arg any) *Predicate

LTE appends a "<=" predicate.

func (*Predicate) Like

func (p *Predicate) Like(col, pattern string) *Predicate

Like appends the `LIKE` predicate.

func (*Predicate) NEQ

func (p *Predicate) NEQ(col string, arg any) *Predicate

NEQ appends a "<>" predicate.

func (*Predicate) Not

func (p *Predicate) Not() *Predicate

Not appends NOT to the predicate.

func (*Predicate) NotExists

func (p *Predicate) NotExists(query Querier) *Predicate

NotExists appends the `NOT EXISTS` predicate with the given query.

func (*Predicate) NotIn

func (p *Predicate) NotIn(col string, args ...any) *Predicate

NotIn appends the `Not IN` predicate.

func (*Predicate) NotNull

func (p *Predicate) NotNull(col string) *Predicate

NotNull appends the `IS NOT NULL` predicate.

func (*Predicate) Query

func (p *Predicate) Query() (string, []any)

Query returns query representation of a predicate.

type Querier

type Querier interface {
	// Query returns the query representation of the element
	// and its arguments (if any).
	Query() (string, []any)
}

Querier wraps the basic Query method that is implemented by the different builders in this file.

func DescExpr

func DescExpr(x Querier) Querier

DescExpr returns a new expression where the DESC suffix is added.

func Expr

func Expr(exr string, args ...any) Querier

Expr returns an SQL expression that implements the Querier interface.

func ExprFunc

func ExprFunc(fn func(*Builder)) Querier

ExprFunc returns an expression function that implements the Querier interface.

Update("users").
	Set("x", ExprFunc(func(b *Builder) {
		// The sql.Builder config (argc and dialect)
		// was set before the function was executed.
		b.Ident("x").WriteOp(OpAdd).Arg(1)
	}))

func Raw

func Raw(s string) Querier

Raw returns a raw SQL query that is placed as-is in the query.

type Queries

type Queries []Querier

Queries are list of queries join with space between them.

func (Queries) Query

func (n Queries) Query() (string, []any)

Query returns query representation of Queriers.

type ReferenceBuilder

type ReferenceBuilder struct {
	Builder
	// contains filtered or unexported fields
}

ReferenceBuilder is a builder for the reference clause in constraints. For example, in foreign key creation.

func Reference

func Reference() *ReferenceBuilder

Reference creates a reference builder for the reference_option clause.

Reference().Table("groups").Columns("id")

func (*ReferenceBuilder) Columns

func (r *ReferenceBuilder) Columns(s ...string) *ReferenceBuilder

Columns sets the columns of the referenced table.

func (*ReferenceBuilder) Query

func (r *ReferenceBuilder) Query() (string, []any)

Query returns query representation of a reference clause.

func (*ReferenceBuilder) Table

Table sets the referenced table.

type Result

type Result = sql.Result

Result is an alias to sql.Result.

type Rows

type Rows struct{ ColumnScanner }

Rows wraps the sql.Rows to avoid locks copy.

type SelectTable

type SelectTable struct {
	Builder
	// contains filtered or unexported fields
}

SelectTable is a table selector.

func Table

func Table(name string) *SelectTable

Table returns a new table selector.

t1 := Table("users").As("u")
return Select(t1.C("name"))

func (*SelectTable) As

func (s *SelectTable) As(alias string) *SelectTable

As adds the AS clause to the table selector.

func (*SelectTable) C

func (s *SelectTable) C(column string) string

C returns a formatted string for the table column.

func (*SelectTable) Columns

func (s *SelectTable) Columns(columns ...string) []string

Columns returns a list of formatted strings for the table columns.

func (*SelectTable) Schema

func (s *SelectTable) Schema(name string) *SelectTable

Schema sets the schema name of the table.

func (*SelectTable) Unquote

func (s *SelectTable) Unquote() *SelectTable

Unquote makes the table name to be formatted as raw string (unquoted). It is useful when you don't want to query tables under the current database. For example: "INFORMATION_SCHEMA.TABLE_CONSTRAINTS" in MySQL.

type SelectValues

type SelectValues map[string]any

SelectValues maps a selected column to its value. Used by the generated code for storing runtime selected columns/expressions.

func (SelectValues) Get

func (s SelectValues) Get(name string) (any, error)

Get returns the value of the given column.

func (*SelectValues) Set

func (s *SelectValues) Set(name string, v any)

Set sets the value of the given column.

type Selector

type Selector struct {
	Builder
	// contains filtered or unexported fields
}

Selector is a builder for the `SELECT` statement.

func Select

func Select(columns ...string) *Selector

Select returns a new selector for the `SELECT` statement.

t1 := Table("users").As("u")
t2 := Select().From(Table("groups")).Where(EQ("user_id", 10)).As("g")
return Select(t1.C("id"), t2.C("name")).
		From(t1).
		Join(t2).
		On(t1.C("id"), t2.C("user_id"))

func SelectExpr

func SelectExpr(exprs ...Querier) *Selector

SelectExpr is like Select, but supports passing arbitrary expressions for SELECT clause.

func (*Selector) AppendFrom

func (s *Selector) AppendFrom(t TableView) *Selector

AppendFrom appends a new TableView to the `FROM` clause.

func (*Selector) AppendFromExpr

func (s *Selector) AppendFromExpr(x Querier) *Selector

AppendFromExpr appends an expression (Queries) to the `FROM` clause.

func (*Selector) AppendSelect

func (s *Selector) AppendSelect(columns ...string) *Selector

AppendSelect appends additional columns to the SELECT statement.

func (*Selector) AppendSelectAs

func (s *Selector) AppendSelectAs(column, as string) *Selector

AppendSelectAs appends additional column to the SELECT statement with the given alias.

func (*Selector) AppendSelectExpr

func (s *Selector) AppendSelectExpr(exprs ...Querier) *Selector

AppendSelectExpr appends additional expressions to the SELECT statement.

func (*Selector) AppendSelectExprAs

func (s *Selector) AppendSelectExprAs(expr Querier, as string) *Selector

AppendSelectExprAs appends additional expressions to the SELECT statement with the given name.

func (*Selector) As

func (s *Selector) As(alias string) *Selector

As give this selection an alias.

func (*Selector) C

func (s *Selector) C(column string) string

C returns a formatted string for a selected column from this statement.

func (*Selector) ClearOrder

func (s *Selector) ClearOrder() *Selector

ClearOrder clears the ORDER BY clause to be empty.

func (*Selector) Clone

func (s *Selector) Clone() *Selector

Clone returns a duplicate of the selector, including all associated steps. It can be used to prepare common SELECT statements and use them differently after the clone is made.

func (*Selector) CollectPredicates

func (s *Selector) CollectPredicates() *Selector

CollectPredicates indicates the appended predicated should be collected and not appended to the `WHERE` clause.

func (*Selector) CollectedPredicates

func (s *Selector) CollectedPredicates() []*Predicate

CollectedPredicates returns the collected predicates.

func (*Selector) Columns

func (s *Selector) Columns(columns ...string) []string

Columns returns a list of formatted strings for a selected columns from this statement.

func (*Selector) Context

func (s *Selector) Context() context.Context

Context returns the Selector context or Background if nil.

func (*Selector) Count

func (s *Selector) Count(columns ...string) *Selector

Count sets the Select statement to be a `SELECT COUNT(*)`.

func (*Selector) Distinct

func (s *Selector) Distinct() *Selector

Distinct adds the DISTINCT keyword to the `SELECT` statement.

func (*Selector) Except

func (s *Selector) Except(t TableView) *Selector

Except appends the EXCEPT clause to the query.

func (*Selector) ExceptAll

func (s *Selector) ExceptAll(t TableView) *Selector

ExceptAll appends the EXCEPT ALL clause to the query.

func (*Selector) FindSelection

func (s *Selector) FindSelection(name string) (matches []string)

FindSelection returns all occurrences in the selection that match the given column name. For example, for column "a" the following match: a, "a", "t"."a", "t"."b" AS "a".

func (*Selector) For

func (s *Selector) For(l LockStrength, opts ...LockOption) *Selector

For sets the lock configuration for suffixing the `SELECT` statement with the `FOR [SHARE | UPDATE] ...` clause.

func (*Selector) ForShare

func (s *Selector) ForShare(opts ...LockOption) *Selector

ForShare sets the lock configuration for suffixing the `SELECT` statement with the `FOR SHARE` clause.

func (*Selector) ForUpdate

func (s *Selector) ForUpdate(opts ...LockOption) *Selector

ForUpdate sets the lock configuration for suffixing the `SELECT` statement with the `FOR UPDATE` clause.

func (*Selector) From

func (s *Selector) From(t TableView) *Selector

From sets the source of `FROM` clause.

func (*Selector) FromExpr

func (s *Selector) FromExpr(x Querier) *Selector

FromExpr sets the expression of `FROM` clause.

func (*Selector) FromSelect

func (s *Selector) FromSelect(s2 *Selector) *Selector

FromSelect copies the predicate from a selector.

func (*Selector) FullJoin

func (s *Selector) FullJoin(t TableView) *Selector

FullJoin appends a `FULL JOIN` clause to the statement.

func (*Selector) GroupBy

func (s *Selector) GroupBy(columns ...string) *Selector

GroupBy appends the `GROUP BY` clause to the `SELECT` statement.

func (*Selector) HasJoins

func (s *Selector) HasJoins() bool

HasJoins reports if the selector has any JOINs.

func (*Selector) Having

func (s *Selector) Having(p *Predicate) *Selector

Having appends a predicate for the `HAVING` clause.

func (*Selector) Intersect

func (s *Selector) Intersect(t TableView) *Selector

Intersect appends the INTERSECT clause to the query.

func (*Selector) IntersectAll

func (s *Selector) IntersectAll(t TableView) *Selector

IntersectAll appends the INTERSECT ALL clause to the query.

func (*Selector) Join

func (s *Selector) Join(t TableView) *Selector

Join appends a `JOIN` clause to the statement.

func (*Selector) JoinedTable

func (s *Selector) JoinedTable(name string) (*SelectTable, bool)

JoinedTable returns the first joined table with the given name.

func (*Selector) JoinedTableView

func (s *Selector) JoinedTableView(name string) (TableView, bool)

JoinedTableView returns the first joined TableView with the given name or alias.

func (*Selector) LeftJoin

func (s *Selector) LeftJoin(t TableView) *Selector

LeftJoin appends a `LEFT JOIN` clause to the statement.

func (*Selector) Limit

func (s *Selector) Limit(limit int) *Selector

Limit adds the `LIMIT` clause to the `SELECT` statement.

func (*Selector) New

func (s *Selector) New() *Selector

New returns a new Selector with the same dialect and context.

func (*Selector) Not

func (s *Selector) Not() *Selector

Not sets the next coming predicate with not.

func (*Selector) Offset

func (s *Selector) Offset(offset int) *Selector

Offset adds the `OFFSET` clause to the `SELECT` statement.

func (*Selector) On

func (s *Selector) On(c1, c2 string) *Selector

On sets the `ON` clause for the `JOIN` operation.

func (*Selector) OnP

func (s *Selector) OnP(p *Predicate) *Selector

OnP sets or appends the given predicate for the `ON` clause of the statement.

func (*Selector) Or

func (s *Selector) Or() *Selector

Or sets the next coming predicate with OR operator (disjunction).

func (*Selector) OrderBy

func (s *Selector) OrderBy(columns ...string) *Selector

OrderBy appends the `ORDER BY` clause to the `SELECT` statement.

func (*Selector) OrderColumns

func (s *Selector) OrderColumns() []string

OrderColumns returns the ordered columns in the Selector. Note, this function skips columns selected with expressions.

func (*Selector) OrderExpr

func (s *Selector) OrderExpr(exprs ...Querier) *Selector

OrderExpr appends the `ORDER BY` clause to the `SELECT` statement with custom list of expressions.

func (*Selector) OrderExprFunc

func (s *Selector) OrderExprFunc(f func(*Builder)) *Selector

OrderExprFunc appends the `ORDER BY` expression that evaluates the given function.

func (*Selector) P

func (s *Selector) P() *Predicate

P returns the predicate of a selector.

func (*Selector) Prefix

func (s *Selector) Prefix(queries ...Querier) *Selector

Prefix prefixes the query with list of queries.

func (*Selector) Query

func (s *Selector) Query() (string, []any)

Query returns query representation of a `SELECT` statement.

func (*Selector) RightJoin

func (s *Selector) RightJoin(t TableView) *Selector

RightJoin appends a `RIGHT JOIN` clause to the statement.

func (*Selector) Select

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

Select changes the columns selection of the SELECT statement. Empty selection means all columns *.

func (*Selector) SelectDistinct

func (s *Selector) SelectDistinct(columns ...string) *Selector

SelectDistinct selects distinct columns.

func (*Selector) SelectExpr

func (s *Selector) SelectExpr(exprs ...Querier) *Selector

SelectExpr changes the columns selection of the SELECT statement with custom list of expressions.

func (*Selector) SelectedColumns

func (s *Selector) SelectedColumns() []string

SelectedColumns returns the selected columns in the Selector.

func (*Selector) SetDistinct

func (s *Selector) SetDistinct(v bool) *Selector

SetDistinct sets explicitly if the returned rows are distinct or indistinct.

func (*Selector) SetP

func (s *Selector) SetP(p *Predicate) *Selector

SetP sets explicitly the predicate function for the selector and clear its previous state.

func (*Selector) Table

func (s *Selector) Table() *SelectTable

Table returns the selected table.

func (*Selector) TableName

func (s *Selector) TableName() string

TableName returns the name of the selected table or alias of selector.

func (*Selector) UncollectedPredicates

func (s *Selector) UncollectedPredicates() *Selector

UncollectedPredicates stop collecting predicates.

func (*Selector) Union

func (s *Selector) Union(t TableView) *Selector

Union appends the UNION (DISTINCT) clause to the query.

func (*Selector) UnionAll

func (s *Selector) UnionAll(t TableView) *Selector

UnionAll appends the UNION ALL clause to the query.

func (*Selector) UnionDistinct

func (s *Selector) UnionDistinct(t TableView) *Selector

UnionDistinct appends the UNION DISTINCT clause to the query. Deprecated: use Union instead as by default, duplicate rows are eliminated unless ALL is specified.

func (*Selector) UnqualifiedColumns

func (s *Selector) UnqualifiedColumns() []string

UnqualifiedColumns returns an unqualified version of the selected columns in the Selector. e.g. "t1"."c" => "c".

func (*Selector) Where

func (s *Selector) Where(p *Predicate) *Selector

Where sets or appends the given predicate to the statement.

func (*Selector) WithContext

func (s *Selector) WithContext(ctx context.Context) *Selector

WithContext sets the context into the *Selector.

type StmtInfo

type StmtInfo struct {
	// The Dialect of the SQL driver.
	Dialect string
}

StmtInfo holds an information regarding the statement

type TableAlter

type TableAlter struct {
	Builder

	Queries []Querier // columns and foreign-keys to add.
	// contains filtered or unexported fields
}

TableAlter is a query builder for `ALTER TABLE` statement.

func AlterTable

func AlterTable(name string) *TableAlter

AlterTable returns a query builder for the `ALTER TABLE` statement.

AlterTable("users").
	AddColumn(Column("group_id").Type("int").Attr("UNIQUE")).
	AddForeignKey(ForeignKey().Columns("group_id").
		Reference(Reference().Table("groups").Columns("id")).OnDelete("CASCADE")),
	)

func (*TableAlter) AddColumn

func (t *TableAlter) AddColumn(c *ColumnBuilder) *TableAlter

AddColumn appends the `ADD COLUMN` clause to the given `ALTER TABLE` statement.

func (*TableAlter) AddForeignKey

func (t *TableAlter) AddForeignKey(fk *ForeignKeyBuilder) *TableAlter

AddForeignKey adds a foreign key constraint to the `ALTER TABLE` statement.

func (*TableAlter) AddIndex

func (t *TableAlter) AddIndex(idx *IndexBuilder) *TableAlter

AddIndex appends the `ADD INDEX` clause to the given `ALTER TABLE` statement.

func (*TableAlter) ChangeColumn

func (t *TableAlter) ChangeColumn(name string, c *ColumnBuilder) *TableAlter

ChangeColumn appends the `CHANGE COLUMN` clause to the given `ALTER TABLE` statement.

func (*TableAlter) DropColumn

func (t *TableAlter) DropColumn(c *ColumnBuilder) *TableAlter

DropColumn appends the `DROP COLUMN` clause to the given `ALTER TABLE` statement.

func (*TableAlter) DropConstraint

func (t *TableAlter) DropConstraint(ident string) *TableAlter

DropConstraint appends the `DROP CONSTRAINT` clause to the given `ALTER TABLE` statement.

func (*TableAlter) DropForeignKey

func (t *TableAlter) DropForeignKey(ident string) *TableAlter

DropForeignKey appends the `DROP FOREIGN KEY` clause to the given `ALTER TABLE` statement.

func (*TableAlter) DropIndex

func (t *TableAlter) DropIndex(name string) *TableAlter

DropIndex appends the `DROP INDEX` clause to the given `ALTER TABLE` statement.

func (*TableAlter) ModifyColumn

func (t *TableAlter) ModifyColumn(c *ColumnBuilder) *TableAlter

ModifyColumn appends the `MODIFY/ALTER COLUMN` clause to the given `ALTER TABLE` statement.

func (*TableAlter) ModifyColumns

func (t *TableAlter) ModifyColumns(cs ...*ColumnBuilder) *TableAlter

ModifyColumns calls ModifyColumn with each of the given builders.

func (*TableAlter) Query

func (t *TableAlter) Query() (string, []any)

Query returns query representation of the `ALTER TABLE` statement.

ALTER TABLE name
	[alter_specification]

func (*TableAlter) RenameColumn

func (t *TableAlter) RenameColumn(old, new string) *TableAlter

RenameColumn appends the `RENAME COLUMN` clause to the given `ALTER TABLE` statement.

func (*TableAlter) RenameIndex

func (t *TableAlter) RenameIndex(curr, new string) *TableAlter

RenameIndex appends the `RENAME INDEX` clause to the given `ALTER TABLE` statement.

type TableBuilder

type TableBuilder struct {
	Builder
	// contains filtered or unexported fields
}

TableBuilder is a query builder for `CREATE TABLE` statement.

func CreateTable

func CreateTable(name string) *TableBuilder

CreateTable returns a query builder for the `CREATE TABLE` statement.

CreateTable("users").
	Columns(
		Column("id").Type("int").Attr("auto_increment"),
		Column("name").Type("varchar(255)"),
	).
	PrimaryKey("id")

func (*TableBuilder) Charset

func (t *TableBuilder) Charset(s string) *TableBuilder

Charset appends the `CHARACTER SET` clause to the statement. MySQL only.

func (*TableBuilder) Checks

func (t *TableBuilder) Checks(checks ...func(*Builder)) *TableBuilder

Checks adds CHECK clauses to the CREATE TABLE statement.

func (*TableBuilder) Collate

func (t *TableBuilder) Collate(s string) *TableBuilder

Collate appends the `COLLATE` clause to the statement. MySQL only.

func (*TableBuilder) Column

func (t *TableBuilder) Column(c *ColumnBuilder) *TableBuilder

Column appends the given column to the `CREATE TABLE` statement.

func (*TableBuilder) Columns

func (t *TableBuilder) Columns(columns ...*ColumnBuilder) *TableBuilder

Columns appends a list of columns to the builder.

func (*TableBuilder) Constraints

func (t *TableBuilder) Constraints(fks ...*ForeignKeyBuilder) *TableBuilder

Constraints adds a list of foreign-key constraints to the statement.

func (*TableBuilder) ForeignKeys

func (t *TableBuilder) ForeignKeys(fks ...*ForeignKeyBuilder) *TableBuilder

ForeignKeys adds a list of foreign-keys to the statement (without constraints).

func (*TableBuilder) IfNotExists

func (t *TableBuilder) IfNotExists() *TableBuilder

IfNotExists appends the `IF NOT EXISTS` clause to the `CREATE TABLE` statement.

func (*TableBuilder) Options

func (t *TableBuilder) Options(s string) *TableBuilder

Options appends additional options to the statement (MySQL only).

func (*TableBuilder) PrimaryKey

func (t *TableBuilder) PrimaryKey(column ...string) *TableBuilder

PrimaryKey adds a column to the primary-key constraint in the statement.

func (*TableBuilder) Query

func (t *TableBuilder) Query() (string, []any)

Query returns query representation of a `CREATE TABLE` statement.

CREATE TABLE [IF NOT EXISTS] name

(table definition)
[charset and collation]

type TableView

type TableView interface {

	// C returns a formatted string prefixed
	// with the table view qualifier.
	C(string) string
	// contains filtered or unexported methods
}

TableView is a view that returns a table view. Can be a Table, Selector or a View (WITH statement).

type Tx

type Tx struct {
	Conn
	driver.Tx
}

Tx implements dialect.Tx interface.

type TxOptions

type TxOptions = sql.TxOptions

TxOptions holds the transaction options to be used in DB.BeginTx.

type UnknownType

type UnknownType any

UnknownType is a named type to any indicates the info needs to be extracted from the underlying rows.

type UpdateBuilder

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

UpdateBuilder is a builder for `UPDATE` statement.

func Update

func Update(table string) *UpdateBuilder

Update creates a builder for the `UPDATE` statement.

Update("users").Set("name", "foo").Set("age", 10)

func (*UpdateBuilder) Add

func (u *UpdateBuilder) Add(column string, v any) *UpdateBuilder

Add adds a numeric value to the given column. Note that, calling Set(c) after Add(c) will erase previous calls with c from the builder.

func (*UpdateBuilder) Empty

func (u *UpdateBuilder) Empty() bool

Empty reports whether this builder does not contain update changes.

func (*UpdateBuilder) FromSelect

func (u *UpdateBuilder) FromSelect(s *Selector) *UpdateBuilder

FromSelect makes it possible to update entities that match the sub-query.

func (*UpdateBuilder) Limit

func (u *UpdateBuilder) Limit(limit int) *UpdateBuilder

Limit appends the `LIMIT` clause to the `UPDATE` statement. Supported by SQLite and MySQL.

func (*UpdateBuilder) OrderBy

func (u *UpdateBuilder) OrderBy(columns ...string) *UpdateBuilder

OrderBy appends the `ORDER BY` clause to the `UPDATE` statement. Supported by SQLite and MySQL.

func (*UpdateBuilder) Prefix

func (u *UpdateBuilder) Prefix(stmts ...Querier) *UpdateBuilder

Prefix prefixes the UPDATE statement with list of statements.

func (*UpdateBuilder) Query

func (u *UpdateBuilder) Query() (string, []any)

Query returns query representation of an `UPDATE` statement.

func (*UpdateBuilder) Returning

func (u *UpdateBuilder) Returning(columns ...string) *UpdateBuilder

Returning adds the `RETURNING` clause to the insert statement. Supported by SQLite and PostgreSQL.

func (*UpdateBuilder) Schema

func (u *UpdateBuilder) Schema(name string) *UpdateBuilder

Schema sets the database name for the updated table.

func (*UpdateBuilder) Set

func (u *UpdateBuilder) Set(column string, v any) *UpdateBuilder

Set sets a column to a given value. If `Set` was called before with the same column name, it overrides the value of the previous call.

func (*UpdateBuilder) SetNull

func (u *UpdateBuilder) SetNull(column string) *UpdateBuilder

SetNull sets a column as null value.

func (*UpdateBuilder) Where

func (u *UpdateBuilder) Where(p *Predicate) *UpdateBuilder

Where adds a where predicate for update statement.

type UpdateSet

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

UpdateSet describes a set of changes of the `DO UPDATE` clause.

func (*UpdateSet) Add

func (u *UpdateSet) Add(column string, v any) *UpdateSet

Add adds a numeric value to the given column.

func (*UpdateSet) Columns

func (u *UpdateSet) Columns() []string

Columns returns all columns in the `INSERT` statement.

func (*UpdateSet) Set

func (u *UpdateSet) Set(column string, v any) *UpdateSet

Set sets a column to a given value.

func (*UpdateSet) SetExcluded

func (u *UpdateSet) SetExcluded(name string) *UpdateSet

SetExcluded sets the column name to its EXCLUDED/VALUES value. For example, "c" = "excluded"."c", or `c` = VALUES(`c`).

func (*UpdateSet) SetIgnore

func (u *UpdateSet) SetIgnore(name string) *UpdateSet

SetIgnore sets the column to itself. For example, "id" = "users"."id".

func (*UpdateSet) SetNull

func (u *UpdateSet) SetNull(column string) *UpdateSet

SetNull sets a column as null value.

func (*UpdateSet) Table

func (u *UpdateSet) Table() *SelectTable

Table returns the table the `UPSERT` statement is executed on.

func (*UpdateSet) UpdateColumns

func (u *UpdateSet) UpdateColumns() []string

UpdateColumns returns all columns in the `UPDATE` statement.

type WindowBuilder

type WindowBuilder struct {
	Builder
	// contains filtered or unexported fields
}

WindowBuilder represents a builder for a window clause. Note that window functions support is limited and used only to query rows-limited edges in pagination.

func RowNumber

func RowNumber() *WindowBuilder

RowNumber returns a new window clause with the ROW_NUMBER() as a function. Using this function will assign each row a number, from 1 to N, in the order defined by the ORDER BY clause in the window spec.

func Window

func Window(fn func(*Builder)) *WindowBuilder

Window returns a new window clause with a custom selector allowing for custom window functions.

Window(func(b *Builder) {
	b.WriteString(Sum(posts.C("duration")))
}).PartitionBy("author_id").OrderBy("id"), "duration").

func (*WindowBuilder) OrderBy

func (w *WindowBuilder) OrderBy(columns ...string) *WindowBuilder

OrderBy indicates how to sort rows in each partition.

func (*WindowBuilder) OrderExpr

func (w *WindowBuilder) OrderExpr(exprs ...Querier) *WindowBuilder

OrderExpr appends the `ORDER BY` clause to the window partition with custom list of expressions.

func (*WindowBuilder) PartitionBy

func (w *WindowBuilder) PartitionBy(columns ...string) *WindowBuilder

PartitionBy indicates to divide the query rows into groups by the given columns. Note that, standard SQL spec allows partition only by columns, and in order to use the "expression" version, use the PartitionByExpr.

func (*WindowBuilder) PartitionExpr

func (w *WindowBuilder) PartitionExpr(x Querier) *WindowBuilder

PartitionExpr indicates to divide the query rows into groups by the given expression.

func (*WindowBuilder) Query

func (w *WindowBuilder) Query() (string, []any)

Query returns query representation of the window function.

type WithBuilder

type WithBuilder struct {
	Builder
	// contains filtered or unexported fields
}

WithBuilder is the builder for the `WITH` statement.

func With

func With(name string, columns ...string) *WithBuilder

With returns a new builder for the `WITH` statement.

n := Queries{
	With("users_view").As(Select().From(Table("users"))),
	Select().From(Table("users_view")),
}
return n.Query()

func WithRecursive

func WithRecursive(name string, columns ...string) *WithBuilder

WithRecursive returns a new builder for the `WITH RECURSIVE` statement.

n := Queries{
	WithRecursive("users_view").As(Select().From(Table("users"))),
	Select().From(Table("users_view")),
}
return n.Query()

func (*WithBuilder) As

func (w *WithBuilder) As(s *Selector) *WithBuilder

As sets the view sub query.

func (*WithBuilder) C

func (w *WithBuilder) C(column string) string

C returns a formatted string for the WITH column.

func (*WithBuilder) Name

func (w *WithBuilder) Name() string

Name returns the name of the view.

func (*WithBuilder) Query

func (w *WithBuilder) Query() (string, []any)

Query returns query representation of a `WITH` clause.

func (*WithBuilder) With

func (w *WithBuilder) With(name string, columns ...string) *WithBuilder

With appends another named CTE to the statement.

type Wrapper

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

Wrapper wraps a given Querier with different format. Used to prefix/suffix other queries.

func (*Wrapper) Dialect

func (w *Wrapper) Dialect() string

Dialect calls Dialect on the wrapped query.

func (*Wrapper) Query

func (w *Wrapper) Query() (string, []any)

Query returns query representation of a wrapped Querier.

func (*Wrapper) SetDialect

func (w *Wrapper) SetDialect(name string)

SetDialect calls SetDialect on the wrapped query.

func (*Wrapper) SetTotal

func (w *Wrapper) SetTotal(total int)

SetTotal sets the value of the total arguments. Used to pass this information between sub queries/expressions.

func (*Wrapper) Total

func (w *Wrapper) Total() int

Total returns the total number of arguments so far.

Directories

Path Synopsis
Package schema contains all schema migration logic for SQL dialects.
Package schema contains all schema migration logic for SQL dialects.
Package sqlgraph provides graph abstraction capabilities on top of sql-based databases for fluent codegen.
Package sqlgraph provides graph abstraction capabilities on top of sql-based databases for fluent codegen.

Jump to

Keyboard shortcuts

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