builder

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package builder provides a fluent, chainable query builder for the database package. It lets you construct and execute SELECT, UPDATE, and DELETE statements against models without writing raw SQL.

There are two types of builders. Builder represents a query before any model is attached and exposes the full set of query operations, while the generic ModelBuilder[T] is bound to a model type and adds the type-safe terminal operations for loading, counting, updating, and deleting records.

Start a query with New, From, or NewEmpty and chain methods to apply conditions, joins, ordering, and pagination:

users, err := builder.From[User]().
	Where("active", "=", true).
	OrderByDesc("name").
	Limit(10).
	Get(db)

Relationships declared as fields on a model can be eager loaded with With, constrained with WhereHas, or loaded after the fact with Load and LoadMissing.

Builder methods generally mutate the receiver and return it so calls can be chained. Use Clone to obtain an independent copy of a query before applying further modifications.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingRelationship is returned when a model does not have the given
	// relationship.
	ErrMissingRelationship = fmt.Errorf("missing relationship")
	// ErrMissingField is returned when a model does not have the given field.
	ErrMissingField = fmt.Errorf("missing related field")
)
View Source
var (
	// ErrNoUpdates is returned when an update statement is built with no
	// columns to update.
	ErrNoUpdates = errors.New("no updates found")
)

Functions

func Load

func Load(tx database.DB, models any, relation string) error

Load eagerly loads the given relationship on each of the models.

Load(db, users, "posts")

Nested relationships can be loaded by separating them with dots.

Load(db, users, "posts.comments")

func LoadContext

func LoadContext(ctx context.Context, tx database.DB, models any, relation string) error

LoadContext is Load with a context used when executing the relationship queries.

func LoadMissing

func LoadMissing(tx database.DB, models any, relation string) error

LoadMissing loads the given relationship on each of the models, skipping any that have already been loaded.

func LoadMissingContext

func LoadMissingContext(ctx context.Context, tx database.DB, models any, relation string) error

LoadMissingContext is LoadMissing with a context used when executing the relationship queries.

Types

type BelongsTo

type BelongsTo[T model.Model] struct {
	// contains filtered or unexported fields
}

BelongsTo represents a belongs to relationship on a model. The parent model with a BelongsTo property will have a column referencing another tables primary key. For example if model Foo had a BelongsTo[*Bar] property the foos table would have a foos.bar_id column related to the bars.id column. Struct tags can be used to change the column names if they don't follow the default naming convention. The column on the parent model can be set with a foreign tag and the column on the related model can be set with an owner tag.

Tags:

  • owner: parent model
  • foreign: related model
Example
sqlite.UseSQLite()
type Bar struct {
	model.BaseModel
	ID   int    `db:"id,autoincrement,primary"`
	Name string `db:"name"`
}

type Foo struct {
	model.BaseModel
	ID    int `db:"id,autoincrement,primary"`
	BarID int `db:"bar_id"`
	Bar   *builder.BelongsTo[*Bar]
}

db := sqlx.MustOpen("sqlite3", ":memory:")
defer db.Close()

createFoo, err := migrate.CreateFromModel(&Foo{})
check(err)
err = createFoo.Run(context.Background(), db)
check(err)
createBar, err := migrate.CreateFromModel(&Bar{})
check(err)
err = createBar.Run(context.Background(), db)
check(err)

foo := &Foo{BarID: 1}
err = model.Save(db, foo)
check(err)
bar := &Bar{ID: 1, Name: "bar name"}
err = model.Save(db, bar)
check(err)

err = builder.Load(db, foo, "Bar")
check(err)
relatedBar, _ := foo.Bar.Value()

fmt.Println(relatedBar.Name)
Output:
bar name

func (*BelongsTo[T]) ForeignKeys

func (r *BelongsTo[T]) ForeignKeys() []*ForeignKey

ForeignKeys returns a list of related tables and what columns they are related on.

func (*BelongsTo[T]) Initialize

func (r *BelongsTo[T]) Initialize(parent any, field reflect.StructField) error

Initialize configures the relationship from the parent model and the struct field that holds it.

func (*BelongsTo[T]) Load

func (r *BelongsTo[T]) Load(ctx context.Context, tx database.DB, relations []Relationship) error

Load fills the related value on each of the relationships in relations.

func (*BelongsTo) Loaded

func (v *BelongsTo) Loaded() bool

Loaded returns true if the relationship has been fetched and false if it has not.

func (*BelongsTo) MarshalJSON

func (v *BelongsTo) MarshalJSON() ([]byte, error)

func (BelongsTo) Query

func (r BelongsTo) Query() *ModelBuilder[T]

Query returns a ModelBuilder scoped to the relationship.

func (BelongsTo) Subquery

func (r BelongsTo) Subquery() *Builder

Subquery returns a Builder scoped to the relationship.

func (*BelongsTo) Value

func (v *BelongsTo) Value() (T, bool)

Value will return the related value and if it has been fetched.

type Builder

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

Builder is a query builder that constructs SQL statements without any knowledge of a specific model. It exposes the query operations used by ModelBuilder and can be built up directly, for example to pass a subquery to WhereExists or WhereSubquery.

Example
package main

import (
	"fmt"

	"gosalusa.com/database/builder"
	"gosalusa.com/database/dialects/sqlite"
	"gosalusa.com/internal/test"
)

func main() {
	q := builder.
		From[*test.Foo]().
		Where("column", "=", "value")

	r, err := sqlite.New().EncodeSelectQuery(q.Query())
	if err != nil {
		panic(err)
	}

	fmt.Println(r.SQL)
	fmt.Println(r.Bindings)
}
Output:
SELECT "foos".* FROM "foos" WHERE "column" = ?
[value]

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new Builder with no columns selected.

func (*Builder) ActiveScopes

func (b *Builder) ActiveScopes() []*Scope

ActiveScopes returns the local scopes and the model's global scopes that are currently applied to queries.

func (*Builder) AddGroupBy

func (b *Builder) AddGroupBy(columns ...string) *Builder

GroupBy adds a "group by" clause to the query.

func (*Builder) AddSelect

func (b *Builder) AddSelect(columns ...string) *Builder

AddSelect adds new columns to be selected.

func (*Builder) AddSelectFunction

func (b *Builder) AddSelectFunction(function, column string) *Builder

SelectFunction adds a column to be selected with a function applied.

func (*Builder) AddSelectRaw

func (b *Builder) AddSelectRaw(columns ...string) *Builder

AddSelect adds new columns to be selected.

func (*Builder) AddSelectSubquery

func (b *Builder) AddSelectSubquery(sb dialects.QueryBuilder, as string) *Builder

AddSelectSubquery adds a subquery to be selected.

func (*Builder) And

func (b *Builder) And(cb func(q *Conditions)) *Builder

And adds a group of conditions to the query

func (*Builder) Clone

func (b *Builder) Clone() *Builder

Clone returns an independent copy of the query. Mutating the returned builder, or the original, will not affect the other.

func (*Builder) Context

func (b *Builder) Context() context.Context

Context returns the context value from the query.

func (*Builder) Count

func (b *Builder) Count(tx database.DB) (int, error)

Count executes select and returns the number of records.

func (*Builder) CrossJoin

func (b *Builder) CrossJoin(table, localColumn, operator, foreignColumn string) *Builder

CrossJoin adds a cross join clause to the query.

func (*Builder) CrossJoinOn

func (b *Builder) CrossJoinOn(table string, cb func(q *Conditions)) *Builder

CrossJoinOn adds a cross join clause to the query with a complex on statement.

func (*Builder) Delete

func (b *Builder) Delete(tx database.DB) error

Delete executes a delete statement using the current where clauses, applying any active delete scopes.

func (*Builder) DeleteQuery

func (b *Builder) DeleteQuery() *dialects.DeleteQuery

DeleteQuery returns the dialects.DeleteQuery that Delete will execute.

func (*Builder) Distinct

func (b *Builder) Distinct() *Builder

Distinct forces the query to only return distinct results.

func (*Builder) Dump

func (b *Builder) Dump() *Builder

Dump prints the encoded SQL statement for the query to stdout and returns the receiver so it can be used in the middle of a chain.

func (*Builder) ForUpdate

func (b *Builder) ForUpdate() *Builder

ForUpdate adds a FOR UPDATE clause to the query, locking the selected rows until the transaction is committed.

func (*Builder) ForUpdateSkipLocked

func (b *Builder) ForUpdateSkipLocked() *Builder

ForUpdateSkipLocked adds a FOR UPDATE SKIP LOCKED clause to the query, locking the selected rows while skipping any rows that are already locked.

func (*Builder) From

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

From sets the table which the query is targeting.

func (*Builder) GetTable

func (b *Builder) GetTable() string

GetTable returns the table the query is targeting

func (*Builder) GroupBy

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

GroupBy sets the "group by" clause to the query.

func (*Builder) Having

func (b *Builder) Having(column, operator string, value any) *Builder

Having adds a basic having clause to the query.

func (*Builder) HavingAnd

func (b *Builder) HavingAnd(cb func(q *Conditions)) *Builder

HavingAnd adds a group of conditions to the query

func (*Builder) HavingColumn

func (b *Builder) HavingColumn(column, operator string, valueColumn string) *Builder

HavingColumn adds a having clause to the query comparing two columns.

func (*Builder) HavingExists

func (b *Builder) HavingExists(query dialects.QueryBuilder) *Builder

HavingExists add an exists clause to the query.

func (*Builder) HavingHas

func (b *Builder) HavingHas(relation string, cb func(q *Builder) *Builder) *Builder

HavingHas adds a relationship exists condition to the query with having clauses.

func (*Builder) HavingIn

func (b *Builder) HavingIn(column string, values []any) *Builder

HavingIn adds a having in clause to the query.

func (*Builder) HavingNotExists

func (b *Builder) HavingNotExists(query dialects.QueryBuilder) *Builder

HavingNotExists add a not exists clause to the query.

func (*Builder) HavingOr

func (b *Builder) HavingOr(cb func(q *Conditions)) *Builder

HavingOr adds a group of conditions to the query with an or

func (*Builder) HavingRaw

func (b *Builder) HavingRaw(rawSql string, bindings ...any) *Builder

HavingRaw adds a raw having clause to the query.

func (*Builder) HavingSubquery

func (b *Builder) HavingSubquery(subquery dialects.QueryBuilder, operator string, value any) *Builder

HavingSubquery adds a having clause to the query comparing a column and a subquery.

func (*Builder) InnerJoin

func (b *Builder) InnerJoin(table, localColumn, operator, foreignColumn string) *Builder

InnerJoin adds an inner join clause to the query.

func (*Builder) InnerJoinOn

func (b *Builder) InnerJoinOn(table string, cb func(q *Conditions)) *Builder

InnerJoinOn adds an inner join clause to the query with a complex on statement.

func (*Builder) Join

func (b *Builder) Join(table, localColumn, operator, foreignColumn string) *Builder

Join adds a join clause to the query.

func (*Builder) JoinOn

func (b *Builder) JoinOn(table string, cb func(q *Conditions)) *Builder

JoinOn adds a join clause to the query with a complex on statement.

func (*Builder) LeftJoin

func (b *Builder) LeftJoin(table, localColumn, operator, foreignColumn string) *Builder

LeftJoin adds a left join clause to the query.

func (*Builder) LeftJoinOn

func (b *Builder) LeftJoinOn(table string, cb func(q *Conditions)) *Builder

LeftJoinOn adds a left join clause to the query with a complex on statement.

func (*Builder) Limit

func (b *Builder) Limit(limit int) *Builder

Limit set the maximum number of rows to return.

func (*Builder) Load

func (b *Builder) Load(tx database.DB, v any) (err error)

Load executes the query as a select statement and sets v to the result.

func (*Builder) LoadOne deprecated

func (b *Builder) LoadOne(tx database.DB, v any) error

Load executes the query as a select statement and sets v to the first record.

Deprecated: Use Builder.Load

func (*Builder) Offset

func (b *Builder) Offset(offset int) *Builder

Offset sets the number of rows to skip before returning the result.

func (*Builder) Or

func (b *Builder) Or(cb func(q *Conditions)) *Builder

Or adds a group of conditions to the query with an or

func (*Builder) OrHaving

func (b *Builder) OrHaving(column, operator string, value any) *Builder

OrHaving adds an or having clause to the query

func (*Builder) OrHavingColumn

func (b *Builder) OrHavingColumn(column, operator string, valueColumn string) *Builder

OrHavingColumn adds an or having clause to the query comparing two columns.

func (*Builder) OrHavingExists

func (b *Builder) OrHavingExists(query dialects.QueryBuilder) *Builder

OrHavingExists add an or exists clause to the query.

func (*Builder) OrHavingHas

func (b *Builder) OrHavingHas(relation string, cb func(q *Builder) *Builder) *Builder

OrHavingHas adds a relationship exists condition to the query with having clauses and an or.

func (*Builder) OrHavingIn

func (b *Builder) OrHavingIn(column string, values []any) *Builder

OrHavingIn adds an or having in clause to the query.

func (*Builder) OrHavingNotExists

func (b *Builder) OrHavingNotExists(query dialects.QueryBuilder) *Builder

OrHavingNotExists add an or not exists clause to the query.

func (*Builder) OrHavingRaw

func (b *Builder) OrHavingRaw(rawSql string, bindings ...any) *Builder

OrHavingRaw adds a raw or having clause to the query.

func (*Builder) OrHavingSubquery

func (b *Builder) OrHavingSubquery(subquery dialects.QueryBuilder, operator string, value any) *Builder

OrHavingSubquery adds an or having clause to the query comparing a column and a subquery.

func (*Builder) OrWhere

func (b *Builder) OrWhere(column, operator string, value any) *Builder

OrWhere adds an or where clause to the query

func (*Builder) OrWhereColumn

func (b *Builder) OrWhereColumn(column, operator string, valueColumn string) *Builder

OrWhereColumn adds an or where clause to the query comparing two columns.

func (*Builder) OrWhereExists

func (b *Builder) OrWhereExists(query dialects.QueryBuilder) *Builder

OrWhereExists add an or exists clause to the query.

func (*Builder) OrWhereHas

func (b *Builder) OrWhereHas(relation string, cb func(q *Builder) *Builder) *Builder

OrWhereHas adds a relationship exists condition to the query with where clauses and an or.

func (*Builder) OrWhereIn

func (b *Builder) OrWhereIn(column string, values []any) *Builder

OrWhereIn adds an or where in clause to the query.

func (*Builder) OrWhereNotExists

func (b *Builder) OrWhereNotExists(query dialects.QueryBuilder) *Builder

OrWhereNotExists add an or not exists clause to the query.

func (*Builder) OrWhereRaw

func (b *Builder) OrWhereRaw(rawSql string, bindings ...any) *Builder

OrWhereRaw adds a raw or where clause to the query.

func (*Builder) OrWhereSubquery

func (b *Builder) OrWhereSubquery(subquery dialects.QueryBuilder, operator string, value any) *Builder

OrWhereSubquery adds an or where clause to the query comparing a column and a subquery.

func (*Builder) OrderBy

func (b *Builder) OrderBy(column string) *Builder

OrderBy adds an order by clause to the query.

func (*Builder) OrderByDesc

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

OrderByDesc adds a descending order by clause to the query.

func (*Builder) Query

func (b *Builder) Query() *dialects.SelectQuery

Query implements dialects.QueryBuilder.

func (*Builder) RightJoin

func (b *Builder) RightJoin(table, localColumn, operator, foreignColumn string) *Builder

RightJoin adds a right join clause to the query.

func (*Builder) RightJoinOn

func (b *Builder) RightJoinOn(table string, cb func(q *Conditions)) *Builder

RightJoinOn adds a right join clause to the query with a complex on statement.

func (*Builder) Select

func (b *Builder) Select(columns ...string) *Builder

Select sets the columns to be selected.

func (*Builder) SelectFunction

func (b *Builder) SelectFunction(function, column string) *Builder

SelectFunction sets a column to be selected with a function applied.

func (*Builder) SelectRaw

func (b *Builder) SelectRaw(columns ...string) *Builder

Select sets the columns to be selected.

func (*Builder) SelectSubquery

func (b *Builder) SelectSubquery(sb dialects.QueryBuilder, as string) *Builder

SelectSubquery sets a subquery to be selected.

func (*Builder) Unordered

func (b *Builder) Unordered() *Builder

Unordered removes all order by clauses from the query.

func (*Builder) Update

func (b *Builder) Update(tx database.DB, updates Updates) error

Update updates the records matched by the query with the given columns.

func (*Builder) UpdateQuery

func (b *Builder) UpdateQuery(updates Updates) *dialects.UpdateQuery

UpdateQuery returns the dialects.UpdateQuery that Update will execute.

func (*Builder) Where

func (b *Builder) Where(column, operator string, value any) *Builder

Where adds a basic where clause to the query.

func (*Builder) WhereColumn

func (b *Builder) WhereColumn(column, operator string, valueColumn string) *Builder

WhereColumn adds a where clause to the query comparing two columns.

func (*Builder) WhereExists

func (b *Builder) WhereExists(query dialects.QueryBuilder) *Builder

WhereExists add an exists clause to the query.

func (*Builder) WhereHas

func (b *Builder) WhereHas(relation string, cb func(q *Builder) *Builder) *Builder

WhereHas adds a relationship exists condition to the query with where clauses.

Example
package main

import (
	"fmt"

	"gosalusa.com/database/builder"
	"gosalusa.com/database/dialects/sqlite"
	"gosalusa.com/internal/test"
)

func main() {
	q := builder.
		From[*test.Foo]().
		WhereHas("Bar", func(q *builder.Builder) *builder.Builder {
			return q.Where("id", "=", 7)
		})
	r, err := sqlite.New().EncodeSelectQuery(q.Query())
	if err != nil {
		panic(err)
	}

	fmt.Println(r.SQL)
	fmt.Println(r.Bindings)
}
Output:
SELECT "foos".* FROM "foos" WHERE EXISTS (SELECT "bars".* FROM "bars" WHERE "foo_id" = "foos"."id" AND "id" = ?)
[7]

func (*Builder) WhereIn

func (b *Builder) WhereIn(column string, values []any) *Builder

WhereIn adds a where in clause to the query.

func (*Builder) WhereNotExists

func (b *Builder) WhereNotExists(query dialects.QueryBuilder) *Builder

WhereNotExists add a not exists clause to the query.

func (*Builder) WhereRaw

func (b *Builder) WhereRaw(rawSql string, bindings ...any) *Builder

WhereRaw adds a raw where clause to the query.

func (*Builder) WhereSubquery

func (b *Builder) WhereSubquery(subquery dialects.QueryBuilder, operator string, value any) *Builder

WhereSubquery adds a where clause to the query comparing a column and a subquery.

func (*Builder) WithContext

func (b *Builder) WithContext(ctx context.Context) *Builder

WithContext adds a context to the query that will be used when fetching results.

func (*Builder) WithScope

func (b *Builder) WithScope(scope *Scope) *Builder

WithScope adds a local scope to a query.

func (*Builder) WithoutGlobalScope

func (b *Builder) WithoutGlobalScope(scope *Scope) *Builder

WithoutGlobalScope removes a global scope from the query.

func (*Builder) WithoutScope

func (b *Builder) WithoutScope(scope *Scope) *Builder

WithoutScope removes the given scope from the local scopes.

type Conditions

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

Conditions is a mutable collection of where clauses that can be built up with the same methods exposed on Builder. It is used to build where and having clauses as well as the on conditions of a join.

func NewConditionBuilder

func NewConditionBuilder() *Conditions

NewConditionBuilder returns a new empty Conditions.

func (*Conditions) And

func (b *Conditions) And(cb func(q *Conditions)) *Conditions

And adds a group of conditions to the query

func (*Conditions) Build

func (c *Conditions) Build() []dialects.Condition

Build returns the conditions that have been added.

func (*Conditions) Clone

func (c *Conditions) Clone() *Conditions

Clone returns a copy of the conditions. Mutating the returned conditions, or the original, will not affect the other.

func (*Conditions) Or

func (b *Conditions) Or(cb func(q *Conditions)) *Conditions

Or adds a group of conditions to the query with an or

func (*Conditions) OrWhere

func (b *Conditions) OrWhere(column, operator string, value any) *Conditions

OrWhere adds an or where clause to the query

func (*Conditions) OrWhereColumn

func (b *Conditions) OrWhereColumn(column, operator string, valueColumn string) *Conditions

OrWhereColumn adds an or where clause to the query comparing two columns.

func (*Conditions) OrWhereExists

func (b *Conditions) OrWhereExists(query dialects.QueryBuilder) *Conditions

OrWhereExists add an or exists clause to the query.

func (*Conditions) OrWhereHas

func (b *Conditions) OrWhereHas(relation string, cb func(q *Builder) *Builder) *Conditions

OrWhereHas adds a relationship exists condition to the query with where clauses and an or.

func (*Conditions) OrWhereIn

func (b *Conditions) OrWhereIn(column string, values []any) *Conditions

OrWhereIn adds an or where in clause to the query.

func (*Conditions) OrWhereNotExists

func (b *Conditions) OrWhereNotExists(query dialects.QueryBuilder) *Conditions

OrWhereNotExists add an or not exists clause to the query.

func (*Conditions) OrWhereRaw

func (b *Conditions) OrWhereRaw(rawSql string, bindings ...any) *Conditions

OrWhereRaw adds a raw or where clause to the query.

func (*Conditions) OrWhereSubquery

func (b *Conditions) OrWhereSubquery(subquery dialects.QueryBuilder, operator string, value any) *Conditions

OrWhereSubquery adds an or where clause to the query comparing a column and a subquery.

func (*Conditions) Where

func (b *Conditions) Where(column, operator string, value any) *Conditions

Where adds a basic where clause to the query.

func (*Conditions) WhereColumn

func (b *Conditions) WhereColumn(column, operator string, valueColumn string) *Conditions

WhereColumn adds a where clause to the query comparing two columns.

func (*Conditions) WhereExists

func (b *Conditions) WhereExists(query dialects.QueryBuilder) *Conditions

WhereExists add an exists clause to the query.

func (*Conditions) WhereHas

func (b *Conditions) WhereHas(relation string, cb func(q *Builder) *Builder) *Conditions

WhereHas adds a relationship exists condition to the query with where clauses.

func (*Conditions) WhereIn

func (b *Conditions) WhereIn(column string, values []any) *Conditions

WhereIn adds a where in clause to the query.

func (*Conditions) WhereNotExists

func (b *Conditions) WhereNotExists(query dialects.QueryBuilder) *Conditions

WhereNotExists add a not exists clause to the query.

func (*Conditions) WhereRaw

func (b *Conditions) WhereRaw(rawSql string, bindings ...any) *Conditions

WhereRaw adds a raw where clause to the query.

func (*Conditions) WhereSubquery

func (b *Conditions) WhereSubquery(subquery dialects.QueryBuilder, operator string, value any) *Conditions

WhereSubquery adds a where clause to the query comparing a column and a subquery.

type ForeignKey

type ForeignKey struct {
	LocalKey     string
	RelatedTable string
	RelatedKey   string
}

ForeignKey describes how two tables are related: the local column on the parent model and the column on the related table it references.

func (*ForeignKey) Equal

func (f *ForeignKey) Equal(v *ForeignKey) bool

Equal reports whether v references the same columns and tables as f.

type HasMany

type HasMany[T model.Model] struct {
	// contains filtered or unexported fields
}

Tags:

  • local: parent model
  • foreign: related model

func (*HasMany[T]) ForeignKeys

func (r *HasMany[T]) ForeignKeys() []*ForeignKey

ForeignKeys returns a list of related tables and what columns they are related on.

func (*HasMany[T]) Initialize

func (r *HasMany[T]) Initialize(parent any, field reflect.StructField) error

Initialize configures the relationship from the parent model and the struct field that holds it.

func (*HasMany[T]) Load

func (r *HasMany[T]) Load(ctx context.Context, tx database.DB, relations []Relationship) error

Load fills the related value on each of the relationships in relations.

func (*HasMany) Loaded

func (v *HasMany) Loaded() bool

Loaded returns true if the relationship has been fetched and false if it has not.

func (*HasMany) MarshalJSON

func (v *HasMany) MarshalJSON() ([]byte, error)

func (HasMany) Query

func (r HasMany) Query() *ModelBuilder[T]

Query returns a ModelBuilder scoped to the relationship.

func (HasMany) Subquery

func (r HasMany) Subquery() *Builder

Subquery returns a Builder scoped to the relationship.

func (*HasMany) Value

func (v *HasMany) Value() (T, bool)

Value will return the related value and if it has been fetched.

type HasOne

type HasOne[T model.Model] struct {
	// contains filtered or unexported fields
}

Tags:

  • local: parent model
  • foreign: related model

func (*HasOne[T]) ForeignKeys

func (r *HasOne[T]) ForeignKeys() []*ForeignKey

ForeignKeys returns a list of related tables and what columns they are related on.

func (*HasOne[T]) Initialize

func (r *HasOne[T]) Initialize(parent any, field reflect.StructField) error

Initialize configures the relationship from the parent model and the struct field that holds it.

func (*HasOne[T]) Load

func (r *HasOne[T]) Load(ctx context.Context, tx database.DB, relations []Relationship) error

Load fills the related value on each of the relationships in relations.

func (*HasOne) Loaded

func (v *HasOne) Loaded() bool

Loaded returns true if the relationship has been fetched and false if it has not.

func (*HasOne) MarshalJSON

func (v *HasOne) MarshalJSON() ([]byte, error)

func (HasOne) Query

func (r HasOne) Query() *ModelBuilder[T]

Query returns a ModelBuilder scoped to the relationship.

func (HasOne) Subquery

func (r HasOne) Subquery() *Builder

Subquery returns a Builder scoped to the relationship.

func (*HasOne) Value

func (v *HasOne) Value() (T, bool)

Value will return the related value and if it has been fetched.

type ModelBuilder

type ModelBuilder[T model.Model] struct {
	// contains filtered or unexported fields
}

ModelBuilder represents a query bound to a model type T, along with the relationships to eager load and the scopes to apply.

func From

func From[T model.Model]() *ModelBuilder[T]

From creates a new query from the model's table and with table.* selected.

func New

func New[T model.Model]() *ModelBuilder[T]

New creates a new query from the model's table with * selected.

func NewEmpty

func NewEmpty[T model.Model]() *ModelBuilder[T]

NewEmpty creates a new query with nothing selected and without a table set.

func (*ModelBuilder[T]) ActiveScopes

func (b *ModelBuilder[T]) ActiveScopes() []*Scope

ActiveScopes returns the local scopes and the model's global scopes that are currently applied to queries.

func (*ModelBuilder[T]) AddGroupBy

func (b *ModelBuilder[T]) AddGroupBy(columns ...string) *ModelBuilder[T]

GroupBy adds a "group by" clause to the query.

func (*ModelBuilder[T]) AddSelect

func (b *ModelBuilder[T]) AddSelect(columns ...string) *ModelBuilder[T]

AddSelect adds new columns to be selected.

func (*ModelBuilder[T]) AddSelectFunction

func (b *ModelBuilder[T]) AddSelectFunction(function, column string) *ModelBuilder[T]

SelectFunction adds a column to be selected with a function applied.

func (*ModelBuilder[T]) AddSelectRaw

func (b *ModelBuilder[T]) AddSelectRaw(columns ...string) *ModelBuilder[T]

AddSelect adds new columns to be selected.

func (*ModelBuilder[T]) AddSelectSubquery

func (b *ModelBuilder[T]) AddSelectSubquery(sb dialects.QueryBuilder, as string) *ModelBuilder[T]

AddSelectSubquery adds a subquery to be selected.

func (*ModelBuilder[T]) And

func (b *ModelBuilder[T]) And(cb func(q *Conditions)) *ModelBuilder[T]

And adds a group of conditions to the query

func (*ModelBuilder[T]) Chunk

func (b *ModelBuilder[T]) Chunk(tx database.DB, cb func(v []T) error) error

Chunk iterates over the results of the query in batches of 1000 records, calling cb for each batch.

func (*ModelBuilder[T]) ChunkN

func (b *ModelBuilder[T]) ChunkN(tx database.DB, limit int, cb func(v []T) error) error

ChunkN iterates over the results of the query in batches of limit records, calling cb for each batch.

func (*ModelBuilder[T]) Clone

func (b *ModelBuilder[T]) Clone() *ModelBuilder[T]

Clone returns an independent copy of the query. Mutating the returned builder, or the original, will not affect the other.

func (*ModelBuilder[T]) Context

func (b *ModelBuilder[T]) Context() context.Context

Context returns the context value from the query.

func (*ModelBuilder[T]) Count

func (b *ModelBuilder[T]) Count(tx database.DB) (int, error)

Count executes select and returns the number of records.

func (*ModelBuilder[T]) CrossJoin

func (b *ModelBuilder[T]) CrossJoin(table, localColumn, operator, foreignColumn string) *ModelBuilder[T]

CrossJoin adds a cross join clause to the query.

func (*ModelBuilder[T]) CrossJoinOn

func (b *ModelBuilder[T]) CrossJoinOn(table string, cb func(q *Conditions)) *ModelBuilder[T]

CrossJoinOn adds a cross join clause to the query with a complex on statement.

func (*ModelBuilder[T]) Delete

func (b *ModelBuilder[T]) Delete(tx database.DB) error

Delete executes a delete statement against the model's table using the current where clauses.

func (*ModelBuilder[T]) DeleteQuery

func (b *ModelBuilder[T]) DeleteQuery() *dialects.DeleteQuery

DeleteQuery returns the dialects.DeleteQuery that Delete will execute.

func (*ModelBuilder[T]) Distinct

func (b *ModelBuilder[T]) Distinct() *ModelBuilder[T]

Distinct forces the query to only return distinct results.

func (*ModelBuilder[T]) Dump

func (b *ModelBuilder[T]) Dump() *ModelBuilder[T]

Dump prints the encoded SQL statement for the query to stdout and returns the receiver so it can be used in the middle of a chain.

func (*ModelBuilder[T]) Each

func (b *ModelBuilder[T]) Each(tx database.DB, cb func(v T) error) error

Each iterates over the results of the query in chunks, calling cb for every record.

func (*ModelBuilder[T]) Find

func (b *ModelBuilder[T]) Find(tx database.DB, primaryKeyValue any) (T, error)

Find returns the record with a matching primary key. It will fail on tables with multiple primary keys.

func (*ModelBuilder[T]) First

func (b *ModelBuilder[T]) First(tx database.DB) (T, error)

First executes the query as a select statement and returns the first record, or the zero value of T if no records match.

func (*ModelBuilder[T]) ForUpdate

func (b *ModelBuilder[T]) ForUpdate() *ModelBuilder[T]

ForUpdate adds a FOR UPDATE clause to the query, locking the selected rows until the transaction is committed.

func (*ModelBuilder[T]) ForUpdateSkipLocked

func (b *ModelBuilder[T]) ForUpdateSkipLocked() *ModelBuilder[T]

ForUpdateSkipLocked adds a FOR UPDATE SKIP LOCKED clause to the query, locking the selected rows while skipping any rows that are already locked.

func (*ModelBuilder[T]) From

func (b *ModelBuilder[T]) From(table string) *ModelBuilder[T]

From sets the table which the query is targeting.

func (*ModelBuilder[T]) Get

func (b *ModelBuilder[T]) Get(tx database.DB) ([]T, error)

Get executes the query as a select statement and returns the result.

func (*ModelBuilder[T]) GetTable

func (b *ModelBuilder[T]) GetTable() string

GetTable returns the table the query is targeting

func (*ModelBuilder[T]) GroupBy

func (b *ModelBuilder[T]) GroupBy(columns ...string) *ModelBuilder[T]

GroupBy sets the "group by" clause to the query.

func (*ModelBuilder[T]) Having

func (b *ModelBuilder[T]) Having(column, operator string, value any) *ModelBuilder[T]

Having adds a basic having clause to the query.

func (*ModelBuilder[T]) HavingAnd

func (b *ModelBuilder[T]) HavingAnd(cb func(q *Conditions)) *ModelBuilder[T]

HavingAnd adds a group of conditions to the query

func (*ModelBuilder[T]) HavingColumn

func (b *ModelBuilder[T]) HavingColumn(column, operator string, valueColumn string) *ModelBuilder[T]

HavingColumn adds a having clause to the query comparing two columns.

func (*ModelBuilder[T]) HavingExists

func (b *ModelBuilder[T]) HavingExists(query dialects.QueryBuilder) *ModelBuilder[T]

HavingExists add an exists clause to the query.

func (*ModelBuilder[T]) HavingHas

func (b *ModelBuilder[T]) HavingHas(relation string, cb func(q *Builder) *Builder) *ModelBuilder[T]

HavingHas adds a relationship exists condition to the query with having clauses.

func (*ModelBuilder[T]) HavingIn

func (b *ModelBuilder[T]) HavingIn(column string, values []any) *ModelBuilder[T]

HavingIn adds a having in clause to the query.

func (*ModelBuilder[T]) HavingNotExists

func (b *ModelBuilder[T]) HavingNotExists(query dialects.QueryBuilder) *ModelBuilder[T]

HavingNotExists add a not exists clause to the query.

func (*ModelBuilder[T]) HavingOr

func (b *ModelBuilder[T]) HavingOr(cb func(q *Conditions)) *ModelBuilder[T]

HavingOr adds a group of conditions to the query with an or

func (*ModelBuilder[T]) HavingRaw

func (b *ModelBuilder[T]) HavingRaw(rawSql string, bindings ...any) *ModelBuilder[T]

HavingRaw adds a raw having clause to the query.

func (*ModelBuilder[T]) HavingSubquery

func (b *ModelBuilder[T]) HavingSubquery(subquery dialects.QueryBuilder, operator string, value any) *ModelBuilder[T]

HavingSubquery adds a having clause to the query comparing a column and a subquery.

func (*ModelBuilder[T]) InnerJoin

func (b *ModelBuilder[T]) InnerJoin(table, localColumn, operator, foreignColumn string) *ModelBuilder[T]

InnerJoin adds an inner join clause to the query.

func (*ModelBuilder[T]) InnerJoinOn

func (b *ModelBuilder[T]) InnerJoinOn(table string, cb func(q *Conditions)) *ModelBuilder[T]

InnerJoinOn adds an inner join clause to the query with a complex on statement.

func (*ModelBuilder[T]) Join

func (b *ModelBuilder[T]) Join(table, localColumn, operator, foreignColumn string) *ModelBuilder[T]

Join adds a join clause to the query.

func (*ModelBuilder[T]) JoinOn

func (b *ModelBuilder[T]) JoinOn(table string, cb func(q *Conditions)) *ModelBuilder[T]

JoinOn adds a join clause to the query with a complex on statement.

func (*ModelBuilder[T]) LeftJoin

func (b *ModelBuilder[T]) LeftJoin(table, localColumn, operator, foreignColumn string) *ModelBuilder[T]

LeftJoin adds a left join clause to the query.

func (*ModelBuilder[T]) LeftJoinOn

func (b *ModelBuilder[T]) LeftJoinOn(table string, cb func(q *Conditions)) *ModelBuilder[T]

LeftJoinOn adds a left join clause to the query with a complex on statement.

func (*ModelBuilder[T]) Limit

func (b *ModelBuilder[T]) Limit(limit int) *ModelBuilder[T]

Limit set the maximum number of rows to return.

func (*ModelBuilder[T]) Load

func (b *ModelBuilder[T]) Load(tx database.DB, v any) error

Load executes the query as a select statement and sets v to the result.

func (*ModelBuilder[T]) LoadOne deprecated

func (b *ModelBuilder[T]) LoadOne(tx database.DB, v any) error

Load executes the query as a select statement and sets v to the result.

Deprecated: Use ModelBuilder.Load

func (*ModelBuilder[T]) Offset

func (b *ModelBuilder[T]) Offset(offset int) *ModelBuilder[T]

Offset sets the number of rows to skip before returning the result.

func (*ModelBuilder[T]) Or

func (b *ModelBuilder[T]) Or(cb func(q *Conditions)) *ModelBuilder[T]

Or adds a group of conditions to the query with an or

func (*ModelBuilder[T]) OrHaving

func (b *ModelBuilder[T]) OrHaving(column, operator string, value any) *ModelBuilder[T]

OrHaving adds an or having clause to the query

func (*ModelBuilder[T]) OrHavingColumn

func (b *ModelBuilder[T]) OrHavingColumn(column, operator string, valueColumn string) *ModelBuilder[T]

OrHavingColumn adds an or having clause to the query comparing two columns.

func (*ModelBuilder[T]) OrHavingExists

func (b *ModelBuilder[T]) OrHavingExists(query dialects.QueryBuilder) *ModelBuilder[T]

OrHavingExists add an or exists clause to the query.

func (*ModelBuilder[T]) OrHavingHas

func (b *ModelBuilder[T]) OrHavingHas(relation string, cb func(q *Builder) *Builder) *ModelBuilder[T]

OrHavingHas adds a relationship exists condition to the query with having clauses and an or.

func (*ModelBuilder[T]) OrHavingIn

func (b *ModelBuilder[T]) OrHavingIn(column string, values []any) *ModelBuilder[T]

OrHavingIn adds an or having in clause to the query.

func (*ModelBuilder[T]) OrHavingNotExists

func (b *ModelBuilder[T]) OrHavingNotExists(query dialects.QueryBuilder) *ModelBuilder[T]

OrHavingNotExists add an or not exists clause to the query.

func (*ModelBuilder[T]) OrHavingRaw

func (b *ModelBuilder[T]) OrHavingRaw(rawSql string, bindings ...any) *ModelBuilder[T]

OrHavingRaw adds a raw or having clause to the query.

func (*ModelBuilder[T]) OrHavingSubquery

func (b *ModelBuilder[T]) OrHavingSubquery(subquery dialects.QueryBuilder, operator string, value any) *ModelBuilder[T]

OrHavingSubquery adds an or having clause to the query comparing a column and a subquery.

func (*ModelBuilder[T]) OrWhere

func (b *ModelBuilder[T]) OrWhere(column, operator string, value any) *ModelBuilder[T]

OrWhere adds an or where clause to the query

func (*ModelBuilder[T]) OrWhereColumn

func (b *ModelBuilder[T]) OrWhereColumn(column, operator string, valueColumn string) *ModelBuilder[T]

OrWhereColumn adds an or where clause to the query comparing two columns.

func (*ModelBuilder[T]) OrWhereExists

func (b *ModelBuilder[T]) OrWhereExists(query dialects.QueryBuilder) *ModelBuilder[T]

OrWhereExists add an or exists clause to the query.

func (*ModelBuilder[T]) OrWhereHas

func (b *ModelBuilder[T]) OrWhereHas(relation string, cb func(q *Builder) *Builder) *ModelBuilder[T]

OrWhereHas adds a relationship exists condition to the query with where clauses and an or.

func (*ModelBuilder[T]) OrWhereIn

func (b *ModelBuilder[T]) OrWhereIn(column string, values []any) *ModelBuilder[T]

OrWhereIn adds an or where in clause to the query.

func (*ModelBuilder[T]) OrWhereNotExists

func (b *ModelBuilder[T]) OrWhereNotExists(query dialects.QueryBuilder) *ModelBuilder[T]

OrWhereNotExists add an or not exists clause to the query.

func (*ModelBuilder[T]) OrWhereRaw

func (b *ModelBuilder[T]) OrWhereRaw(rawSql string, bindings ...any) *ModelBuilder[T]

OrWhereRaw adds a raw or where clause to the query.

func (*ModelBuilder[T]) OrWhereSubquery

func (b *ModelBuilder[T]) OrWhereSubquery(subquery dialects.QueryBuilder, operator string, value any) *ModelBuilder[T]

OrWhereSubquery adds an or where clause to the query comparing a column and a subquery.

func (*ModelBuilder[T]) OrderBy

func (b *ModelBuilder[T]) OrderBy(column string) *ModelBuilder[T]

OrderBy adds an order by clause to the query.

func (*ModelBuilder[T]) OrderByDesc

func (b *ModelBuilder[T]) OrderByDesc(column string) *ModelBuilder[T]

OrderByDesc adds a descending order by clause to the query.

func (*ModelBuilder[T]) Query

func (b *ModelBuilder[T]) Query() *dialects.SelectQuery

Query implements dialects.QueryBuilder.

func (*ModelBuilder[T]) RightJoin

func (b *ModelBuilder[T]) RightJoin(table, localColumn, operator, foreignColumn string) *ModelBuilder[T]

RightJoin adds a right join clause to the query.

func (*ModelBuilder[T]) RightJoinOn

func (b *ModelBuilder[T]) RightJoinOn(table string, cb func(q *Conditions)) *ModelBuilder[T]

RightJoinOn adds a right join clause to the query with a complex on statement.

func (*ModelBuilder[T]) Select

func (b *ModelBuilder[T]) Select(columns ...string) *ModelBuilder[T]

Select sets the columns to be selected.

func (*ModelBuilder[T]) SelectFunction

func (b *ModelBuilder[T]) SelectFunction(function, column string) *ModelBuilder[T]

SelectFunction sets a column to be selected with a function applied.

func (*ModelBuilder[T]) SelectRaw

func (b *ModelBuilder[T]) SelectRaw(columns ...string) *ModelBuilder[T]

Select sets the columns to be selected.

func (*ModelBuilder[T]) SelectSubquery

func (b *ModelBuilder[T]) SelectSubquery(sb dialects.QueryBuilder, as string) *ModelBuilder[T]

SelectSubquery sets a subquery to be selected.

func (*ModelBuilder[T]) Unordered

func (b *ModelBuilder[T]) Unordered() *ModelBuilder[T]

Unordered removes all order by clauses from the query.

func (*ModelBuilder[T]) Update

func (b *ModelBuilder[T]) Update(tx database.DB, updates Updates) error

Update updates the records matched by the query with the given columns.

func (*ModelBuilder[T]) UpdateQuery

func (b *ModelBuilder[T]) UpdateQuery(updates Updates) *dialects.UpdateQuery

UpdateQuery returns the dialects.UpdateQuery that Update will execute.

func (*ModelBuilder[T]) UpdateReturning

func (b *ModelBuilder[T]) UpdateReturning(tx database.DB, updates Updates) ([]T, error)

UpdateReturning updates the records matched by the query with the given columns and returns the updated records that were matched.

func (*ModelBuilder[T]) Where

func (b *ModelBuilder[T]) Where(column, operator string, value any) *ModelBuilder[T]

Where adds a basic where clause to the query.

func (*ModelBuilder[T]) WhereColumn

func (b *ModelBuilder[T]) WhereColumn(column, operator string, valueColumn string) *ModelBuilder[T]

WhereColumn adds a where clause to the query comparing two columns.

func (*ModelBuilder[T]) WhereExists

func (b *ModelBuilder[T]) WhereExists(query dialects.QueryBuilder) *ModelBuilder[T]

WhereExists add an exists clause to the query.

func (*ModelBuilder[T]) WhereHas

func (b *ModelBuilder[T]) WhereHas(relation string, cb func(q *Builder) *Builder) *ModelBuilder[T]

WhereHas adds a relationship exists condition to the query with where clauses.

func (*ModelBuilder[T]) WhereIn

func (b *ModelBuilder[T]) WhereIn(column string, values []any) *ModelBuilder[T]

WhereIn adds a where in clause to the query.

func (*ModelBuilder[T]) WhereNotExists

func (b *ModelBuilder[T]) WhereNotExists(query dialects.QueryBuilder) *ModelBuilder[T]

WhereNotExists add a not exists clause to the query.

func (*ModelBuilder[T]) WhereRaw

func (b *ModelBuilder[T]) WhereRaw(rawSql string, bindings ...any) *ModelBuilder[T]

WhereRaw adds a raw where clause to the query.

func (*ModelBuilder[T]) WhereSubquery

func (b *ModelBuilder[T]) WhereSubquery(subquery dialects.QueryBuilder, operator string, value any) *ModelBuilder[T]

WhereSubquery adds a where clause to the query comparing a column and a subquery.

func (*ModelBuilder[T]) With

func (b *ModelBuilder[T]) With(withs ...string) *ModelBuilder[T]

With registers relationships to be eager loaded when the query returns results. Nested relationships can be loaded by separating them with dots.

builder.From[User]().With("posts", "posts.comments")

func (*ModelBuilder[T]) WithContext

func (b *ModelBuilder[T]) WithContext(ctx context.Context) *ModelBuilder[T]

WithContext adds a context to the query that will be used when fetching results.

func (*ModelBuilder[T]) WithScope

func (b *ModelBuilder[T]) WithScope(scope *Scope) *ModelBuilder[T]

WithScope adds a local scope to a query.

func (*ModelBuilder[T]) WithoutGlobalScope

func (b *ModelBuilder[T]) WithoutGlobalScope(scope *Scope) *ModelBuilder[T]

WithoutGlobalScope removes a global scope from the query.

func (*ModelBuilder[T]) WithoutScope

func (b *ModelBuilder[T]) WithoutScope(scope *Scope) *ModelBuilder[T]

WithoutScope removes the given scope from the local scopes.

type QueryError

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

QueryError wraps an error with the SQL statement that produced it.

func (*QueryError) Error

func (e *QueryError) Error() string

Error returns a string describing the failed query and the underlying error.

func (*QueryError) Unwrap

func (e *QueryError) Unwrap() error

Unwrap returns the underlying error so it can be inspected with errors.Is and errors.As.

type Relationship

type Relationship interface {
	relationship.Relationship
	Subquery() *Builder
	Load(ctx context.Context, tx database.DB, relations []Relationship) error
	ForeignKeys() []*ForeignKey
}

Relationship is a model relationship that can be initialized from a parent model, give back a query for the related records, and load those records from the database.

type Scope

type Scope struct {
	Name   string
	Query  ScopeQueryFunc
	Delete ScopeDeleteFunc
}

Scope is a modifier for a query that can be easily applied.

type ScopeDeleteFunc

type ScopeDeleteFunc func(next func(q *Builder, tx database.DB) error) func(q *Builder, tx database.DB) error

ScopeDeleteFunc wraps a delete statement so the scope can alter or block it (for example, a soft delete scope rewrites deletes into updates).

type ScopeQueryFunc

type ScopeQueryFunc func(b *Builder) *Builder

ScopeQueryFunc modifies a query when the scope is applied.

type Scoper

type Scoper interface {
	Scopes() []*Scope
}

Scoper is implemented by models that define global scopes that should be applied to every query against them.

type Updates

type Updates map[string]any

Updates maps column names to the values they should be set to.

Jump to

Keyboard shortcuts

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