queries

package
v0.0.0-...-94fd837 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2025 License: GPL-2.0 Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Maximum number of results to return when using the `Get` method.
	//
	// Also the maximum number of results to return when querying the database
	// inside of the `String` method.
	MAX_GET_RESULTS = 21

	// Maximum default number of results to return when using the `All` method.
	//
	// This can be overridden by the `Limit` method.
	MAX_DEFAULT_RESULTS = 1000
)
View Source
const (
	// MetaUniqueTogetherKey is the key used to store the unique together
	// fields in the model's metadata.
	//
	// It is used to determine which fields are unique together in the model
	// and can be used to enforce uniqueness, generate SQL clauses for selections,
	// and to generate unique keys for the model in code.
	MetaUniqueTogetherKey = "unique_together"
)

Variables

View Source
var (

	// Signal to be executed before inserting / updating a model instance.
	SignalPreModelSave = signals_saving.Get("queries.model.pre_save")

	// Signal to be executed after inserting / updating a model instance.
	SignalPostModelSave = signals_saving.Get("queries.model.post_save")

	// Signal to be executed before deleting a model instance.
	SignalPreModelDelete = signals_deleting.Get("queries.model.pre_delete")

	// Signal to be executed after deleting a model instance.
	SignalPostModelDelete = signals_deleting.Get("queries.model.post_delete")
)
View Source
var QUERYSET_CREATE_IMPLICIT_TRANSACTION = true

CREATE_IMPLICIT_TRANSACTION is a constant that determines whether the QuerySet should create a transaction implicitly each time a query is executed.

If false, the queryset will not automatically start a transaction on each write / update / delete operation to the database.

View Source
var QUERYSET_USE_CACHE_DEFAULT = true

QUERYSET_USE_CACHE_DEFAULT is the default value for the useCache field in the QuerySet.

It is used to determine whether the QuerySet should cache the results of the latest query until the QuerySet is modified.

Functions

func CT_GetObject

func CT_GetObject(obj attrs.Definer) func(ctx context.Context, identifier any) (interface{}, error)

CT_GetObject retrieves an object from the database by its identifier.

This is a function with the CT_ prefix to indicate that it is a function to be used in a `contenttypes.ContentTypeDefinition` context.

func CT_ListObjects

func CT_ListObjects(obj attrs.Definer) func(ctx context.Context, offset, limit uint) ([]interface{}, error)

CT_ListObjects lists objects from the database.

This is a function with the CT_ prefix to indicate that it is a function to be used in a `contenttypes.ContentTypeDefinition` context.

func CT_ListObjectsByIDs

func CT_ListObjectsByIDs(obj attrs.Definer) func(ctx context.Context, i []interface{}) ([]interface{}, error)

CT_ListObjectsByIDs lists objects from the database by their IDs.

This is a function with the CT_ prefix to indicate that it is a function to be used in a `contenttypes.ContentTypeDefinition` context.

func CountObjects

func CountObjects[T attrs.Definer](obj T) (int64, error)

CountObjects counts the number of objects in the database.

func CreateObject

func CreateObject[T attrs.Definer](obj T) error

CreateObject creates a new object in the database and sets its default values.

It sends a pre-save signal before saving and a post-save signal after saving.

If the object implements the models.Saver interface, it will call the Save method instead of executing a query.

func DeleteObject

func DeleteObject[T attrs.Definer](obj T) (int64, error)

DeleteObject deletes an object from the database.

It sends a pre-delete signal before deleting and a post-delete signal after deleting.

If the object implements the models.Deleter interface, it will call the Delete method instead of executing a query.

func ForDBEdit

func ForDBEdit(f attrs.FieldDefinition) bool

ForDBEdit returns true if the field should be saved to the database.

* If the field is nil, it returns false. * If the field has no column name, it returns false. * If the field is a ForUseInQueriesField, it checks if it is for select all. * If the field implements ForDBEditableField, it checks if it is for edit.

func ForSelectAll

func ForSelectAll(f attrs.FieldDefinition) bool

ForSelectAll returns true if the field should be selected in the query.

If the field is nil, it returns false.

If the field is a ForUseInQueriesField, it returns the result of `ForSelectAll()`.

Otherwise, it returns true.

func ForSelectAllFields

func ForSelectAllFields[T any](fields any) []T

func GenerateObjectsWhereClause

func GenerateObjectsWhereClause[T attrs.Definer](objects ...T) ([]expr.ClauseExpression, error)

GenerateObjectsWhereClause generates a where clause for the given objects.

This where clause is used to reference the given objects in the database.

  • If the model has a primary key defined, it will generate a where clause based on the primary key.

  • If the model does not have a primary key defined, it will try to generate a where clause based on the unique fields or unique together attrs.

  • If no primary key, unique fields or unique together fields are defined, it will return an error.

func GetObject

func GetObject[T attrs.Definer](object T, identifier any) (T, error)

GetObject retrieves an object from the database by its identifier.

It takes an identifier as a parameter and returns the object of type T.

The identifier can be any type, but it is expected to be the primary key of the object.

func GetUniqueKey

func GetUniqueKey(modelObject any) (any, error)

Use the model meta to get the unique key for an object.

If the model has a primary key defined, it will return the primary key value.

If the model does not have a primary key defined, it will return the unique fields or unique together fields as a string of [fieldName]:[fieldValue]:[fieldName]:[fieldValue] pairs.

func ListObjects

func ListObjects[T attrs.Definer](object T, offset, limit uint64, ordering ...string) ([]T, error)

ListObjects lists objects from the database.

It takes an offset and a limit as parameters and returns a slice of objects of type T.

func ListObjectsByIDs

func ListObjectsByIDs[T attrs.Definer, T2 any](object T, offset, limit uint64, ids []T2) ([]T, error)

ListObjectsByIDs lists objects from the database by their IDs.

It takes an offset, limit, and a slice of IDs as parameters and returns a slice of objects of type T.

func NullTransaction

func NullTransaction() drivers.Transaction

NullTransaction returns a no-op transaction that does not commit or rollback anything.

It cannot be used for any database operations - the underlying DB is nil.

The transaction Rollback and Commit methods are no-ops and will not perform any actions.

func OptExpressions

func OptExpressions(exprs ...any) func(*WalkOptions)

func OptFlags

func OptFlags(flags ...WalkFlag) func(*WalkOptions)

func PluckRowValues

func PluckRowValues[ValueT any, ModelT attrs.Definer](rows Rows[ModelT], pathToField string) iter.Seq2[int, ValueT]

PluckRowValues returns a sequence of values from the rows based on the provided path to the field.

The path to the field is a dot-separated string that specifies the field to pluck from each row. It traverses the field definitions of each row's object to find the specified field, and yields the index of that field along with its value. The index will be increased by one for each field processed.

func ProxyFields

func ProxyFields(definer attrs.Definer) *proxyTree

func RegisterCompiler

func RegisterCompiler(driver driver.Driver, compiler func(defaultDB string) QueryCompiler)

RegisterCompiler registers a compiler for a given driver.

It should be used in the init() function of the package that implements the compiler.

The compiler function should take a model and a default database name as arguments, and return a QueryCompiler.

The default database name is used to determine the database connection to use and retrieve from the django.Global.Settings object.

func RunInTransaction

func RunInTransaction[T attrs.Definer](c context.Context, fn func(ctx context.Context, NewQuerySet ObjectsFunc[T]) (commit bool, err error), database ...string) error

RunInTransaction runs the given function in a transaction.

The function should return a boolean indicating whether the transaction should be committed or rolled back. If the function returns an error, the transaction will be rolled back.

The queryset passed to the function will have the transaction bound to it, so that it can be used to execute queries within the transaction.

If the function panics, the transaction will be rolled back and the panic will be recovered.

func SaveObject

func SaveObject[T attrs.Definer](obj T) error

SaveObject saves an object to the database.

It checks if the primary key is set. If it is not set, it creates a new object. If it is set, it updates the existing object.

It sends a pre-save signal before saving and a post-save signal after saving.

If the object implements the models.Saver interface, it will call the Save method instead of executing a query.

func Subquery

func Subquery[T attrs.Definer, QS BaseQuerySet[T, QS]](qs QS) expr.Expression

func UpdateObject

func UpdateObject[T attrs.Definer](obj T) (int64, error)

UpdateObject updates an existing object in the database.

It sends a pre-save signal before saving and a post-save signal after saving.

If the object implements the models.Saver interface, it will call the Save method instead of executing a query.

func Validate

func Validate(ctx context.Context, validate any) error

Validate allows a model to be validated before being saved to the database

Types

type ActsAfterCreate

type ActsAfterCreate interface {
	AfterCreate(ctx context.Context) error
}

type ActsAfterDelete

type ActsAfterDelete interface {
	AfterDelete(ctx context.Context) error
}

type ActsAfterQuery

type ActsAfterQuery interface {
	AfterQuery(ctx context.Context) error
}

type ActsAfterSave

type ActsAfterSave interface {
	AfterSave(ctx context.Context) error
}

type ActsAfterUpdate

type ActsAfterUpdate interface {
	AfterUpdate(ctx context.Context) error
}

type ActsBeforeCreate

type ActsBeforeCreate interface {
	BeforeCreate(ctx context.Context) error
}

type ActsBeforeDelete

type ActsBeforeDelete interface {
	BeforeDelete(ctx context.Context) error
}

type ActsBeforeSave

type ActsBeforeSave interface {
	BeforeSave(ctx context.Context) error
}

type ActsBeforeUpdate

type ActsBeforeUpdate interface {
	BeforeUpdate(ctx context.Context) error
}

type AliasField

type AliasField = expr.AliasField

A field can adhere to this interface to indicate that the field should be aliased when generating the SQL for the field.

For example: this is used in annotations to alias the field name.

type Annotator

type Annotator interface {
	Annotate(annotations map[string]any)
}

A model should adhere to this interface to indicate that it can store and retrieve annotated values from the database.

type BaseQuerySet

type BaseQuerySet[T attrs.Definer, QS any] interface {
	expr.ExpressionBuilder
	expr.FieldResolver

	Clone() QS
	Distinct() QS
	Select(fields ...any) QS
	Preload(fields ...any) QS
	Filter(key interface{}, vals ...interface{}) QS
	GroupBy(fields ...any) QS
	Limit(n int) QS
	Offset(n int) QS
	OrderBy(fields ...string) QS
	Reverse() QS
	ExplicitSave() QS
	Annotate(aliasOrAliasMap interface{}, exprs ...expr.Expression) QS

	// Read operations
	All() (Rows[T], error)
	Exists() (bool, error)
	Count() (int64, error)
	First() (*Row[T], error)
	Last() (*Row[T], error)
	Get() (*Row[T], error)
	Values(fields ...any) ([]map[string]any, error)
	ValuesList(fields ...any) ([][]interface{}, error)
	Aggregate(annotations map[string]expr.Expression) (map[string]any, error)

	// Write, update, and delete operations
	Create(value T) (T, error)
	Update(value T, expressions ...any) (int64, error)
	GetOrCreate(value T) (T, bool, error)
	BatchCreate(objects []T) ([]T, error)
	BatchUpdate(objects []T, exprs ...any) (int64, error)
	BulkCreate(objects []T) ([]T, error)
	BulkUpdate(objects []T, expressions ...any) (int64, error)
	Delete(objects ...T) (int64, error)

	// Raw SQL operations
	Row(sqlStr string, args ...interface{}) drivers.SQLRow
	Rows(sqlStr string, args ...interface{}) (drivers.SQLRows, error)
	Exec(sqlStr string, args ...interface{}) (sql.Result, error)

	// Transactions
	GetOrCreateTransaction() (tx drivers.Transaction, err error)
	StartTransaction(ctx context.Context) (drivers.Transaction, error)
	WithTransaction(tx drivers.Transaction) (drivers.Transaction, error)

	// Generic queryset methods
	ForUpdate() QS
	Prefix(prefix string) QS
	DB() drivers.DB
	Meta() expr.ModelMeta
	Compiler() QueryCompiler
	Having(key interface{}, vals ...interface{}) QS
	LatestQuery() QueryInfo
	WithContext(ctx context.Context) QS

	// Lazy methods for retrieving queries
	QueryAll(fields ...any) CompiledQuery[[][]interface{}]
	QueryAggregate() CompiledQuery[[][]interface{}]
	QueryCount() CompiledQuery[int64]
}

A queryset is a collection of queries that can be executed against a database.

It is used to retrieve, create, update, and delete objects from the database. It is also used to filter, order, and annotate the objects in the database.

type CTE

type CTE[T attrs.Definer] struct {
	Name      CTEName
	QuerySets []*QuerySet[T]
}

type CTEName

type CTEName = string

type CTEQueryCompiler

type CTEQueryCompiler struct {
	QueryCompiler
}

func (*CTEQueryCompiler) BuildSelectQuery

func (c *CTEQueryCompiler) BuildSelectQuery(
	ctx context.Context,
	qs *CTEQuerySet[attrs.Definer],
	internals *QuerySetInternals,
) CompiledQuery[[][]interface{}]

BuildSelectQuery builds a select query with the given parameters.

type CTEQuerySet

type CTEQuerySet[T attrs.Definer] struct {
	*WrappedQuerySet[T, *CTEQuerySet[T], *QuerySet[T]]
	// contains filtered or unexported fields
}

func NewCTEQuerySet

func NewCTEQuerySet[T attrs.Definer](base *QuerySet[T]) *CTEQuerySet[T]

func (*CTEQuerySet[T]) CloneQuerySet

func (qs *CTEQuerySet[T]) CloneQuerySet(wrapped *WrappedQuerySet[T, *CTEQuerySet[T], *QuerySet[T]]) *CTEQuerySet[T]

func (*CTEQuerySet[T]) Join

func (c *CTEQuerySet[T]) Join(name CTEName, options ...JoinOption[T]) *CTEQuerySet[T]

type CanSetup

type CanSetup interface {
	// Setup is called to set up the model with the given value.
	Setup(value attrs.Definer) error
}

CanSetup is an interface that can be implemented by models to indicate that the model can be set up with a the given model value.

This is mainly useful for embedded models, where the embedded model needs a reference to the parent model to be able to set up the relation properly.

type ClauseTarget

type ClauseTarget struct {
	Model attrs.Definer
	Table Table
	Field attrs.FieldDefinition
}

type CompiledCountQuery

type CompiledCountQuery CompiledQuery[int64]

A compiledQuery which returns the number of rows affected by the query.

type CompiledExistsQuery

type CompiledExistsQuery CompiledQuery[bool]

A compiledQuery which returns a boolean indicating if any rows were affected by the query.

type CompiledQuery

type CompiledQuery[T1 any] interface {
	QueryInfo
	Exec() (T1, error)
}

A CompiledQuery interface is used to execute a query.

It is possible to execute the query and retrieve the results.

The compiler will generally return a CompiledQuery interface, which the queryset will then store to be used as result on `LatestQuery()`.

type CompiledValuesListQuery

type CompiledValuesListQuery CompiledQuery[[][]any]

A compiledQuery which returns a list of values from the query.

type ContextValidator

type ContextValidator interface {
	// Validate is called to validate the model before it is saved to the database.
	// It should return an error if the validation fails.
	Validate(ctx context.Context) error
}

Validator is a generic interface that can be implemented by objects, fields and more to indicate that the object can be validated before being saved to the database.

type DataModel

type DataModel interface {
	DataStore() ModelDataStore
}

A model can adhere to this interface to indicate that the queries package should use the model to store and retrieve annotated values.

Relations will also be stored here.

Annotations will also be stored using the Annotator interface.

type DatabaseSpecificTransaction

type DatabaseSpecificTransaction interface {
	drivers.Transaction
	DatabaseName() string
}

DatabaseSpecificTransaction is an interface for transactions that are specific to a database.

func StartTransaction

func StartTransaction(ctx context.Context, database ...string) (context.Context, DatabaseSpecificTransaction, error)

StartTransaction starts a new transaction for the given database.

If a transaction already exists in the context, it will return a no-op transaction, meaning that Rollback and Commit will do nothing, it is assumed that the transaction is managed by a higher-level function in the call stack.

If the database name is not provided, it will use the default database name from the compiler. If the database name is provided, it will use that database name to start the transaction.

The transaction can not be retrieved from the context if the database name is different, a new transaction will be started for the given database name.

The context returned will have the transaction stored in it, so that it can be used later, the transaction is stored in the context - a queryset will automatically use the transaction from the context if it exists when using QuerySet.WithContext.

type FieldInfo

type FieldInfo[FieldType attrs.FieldDefinition] struct {
	Annotating  bool // Whether the field is being annotated
	SourceField FieldType
	Model       attrs.Definer
	RelType     attrs.RelationType
	Table       Table
	Chain       []string
	Fields      []FieldType
	Through     *FieldInfo[FieldType]
}

FieldInfo represents information about a field in a query.

It is both used by the QuerySet and by the QueryCompiler.

func (*FieldInfo[T]) WriteField

func (f *FieldInfo[T]) WriteField(sb *strings.Builder, inf *expr.ExpressionInfo, field attrs.FieldDefinition, forUpdate bool) (args []any, isSQL, written bool)

func (*FieldInfo[T]) WriteFields

func (f *FieldInfo[T]) WriteFields(sb *strings.Builder, inf *expr.ExpressionInfo) []any

func (*FieldInfo[T]) WriteUpdateFields

func (f *FieldInfo[T]) WriteUpdateFields(sb *strings.Builder, inf *expr.ExpressionInfo) []any

type ForDBEditableField

type ForDBEditableField interface {
	attrs.Field
	AllowDBEdit() bool
}

ForDBEditableField returns true if the field should be saved to the database. If the field is nil, it returns false.

type ForUseInQueries

type ForUseInQueries interface {
	attrs.Definer
	ForUseInQueries() bool
}

A model can adhere to this interface to indicate that the queries package should not automatically save or delete the model to/from the database when `django/models.SaveObject()` or `django/models.DeleteObject()` is called.

type ForUseInQueriesField

type ForUseInQueriesField interface {
	attrs.Field
	// ForUseInQueries returns true if the field is for use in queries.
	// This is used to determine if the field should be included in the query.
	// If the field does not implement this method, it is assumed to be for use in queries.
	ForSelectAll() bool
}

ForUseInQueriesField is an interface that can be implemented by fields to indicate that the field should be included in the query.

For example, this is used in fields.RelationField to exclude the relation from the query, otherwise scanning errors will occur.

This is mostly for fields that do not actually exist in the database, I.E. reverse fk, o2o

type GenericQuerySet

type GenericQuerySet = QuerySet[attrs.Definer]

QuerySet is a struct that represents a query set in the database.

It contains methods to filter, order, and limit the results of a query.

It is used to build and execute queries against the database.

Every method on the queryset returns a new queryset, so that the original queryset is not modified.

It also has a chainable api, so that you can easily build complex queries by chaining methods together.

Queries are built internally with the help of the QueryCompiler interface, which is responsible for generating the SQL queries for the database.

type JoinDef

type JoinDef struct {
	Table            Table
	TypeJoin         expr.JoinType
	JoinDefCondition *JoinDefCondition
}

JoinDef represents a join definition in a query.

It contains the table to join, the type of join, and the fields to join on.

See [JoinType] for different types of joins. See expr.LogicalOp for different logical operators.

func (*JoinDef) Condition

func (j *JoinDef) Condition() expr.JoinCondition

func (*JoinDef) TableAlias

func (j *JoinDef) TableAlias() string

func (*JoinDef) TableName

func (j *JoinDef) TableName() string

func (*JoinDef) Type

func (j *JoinDef) Type() expr.JoinType

type JoinDefCondition

type JoinDefCondition struct {
	ConditionA expr.TableColumn  // The first condition to join on
	ConditionB expr.TableColumn  // The second condition to join on
	Operator   expr.LogicalOp    // The operator to use to join the two conditions
	Next       *JoinDefCondition // The next join condition, if any
}

func (*JoinDefCondition) LHS

func (*JoinDefCondition) NextCondition

func (j *JoinDefCondition) NextCondition() expr.JoinCondition

func (*JoinDefCondition) Op

func (*JoinDefCondition) RHS

func (*JoinDefCondition) String

func (j *JoinDefCondition) String() string

type JoinOption

type JoinOption[T attrs.Definer] func(*CTEQuerySet[T], *JoinDef)

func JoinOptionCondition

func JoinOptionCondition[T attrs.Definer](condition *JoinDefCondition) JoinOption[T]

func JoinOptionJoinType

func JoinOptionJoinType[T attrs.Definer](joinType expr.JoinType) JoinOption[T]

func JoinOptionTargetField

func JoinOptionTargetField[T attrs.Definer](source, target string) JoinOption[T]

type ModelDataStore

type ModelDataStore interface {
	HasValue(key string) bool
	GetValue(key string) (any, bool)
	SetValue(key string, value any) error
	DeleteValue(key string) error
}

Annotations from the database are stored in the `Row` struct, and if the model has a `ModelDataStore()` method that implements this interface, annotated values will be stored there too.

Relations are also stored in the model's data store.

type MultiRelationValue

type MultiRelationValue interface {
	attrs.Binder
	ParentInfo() *ParentInfo
	GetValues() []attrs.Definer
	SetValues(instances []attrs.Definer)
}

A model field's value can adhere to this interface to indicate that the field's relation values can be set or retrieved.

This is used for OneToMany relations without a through table, if a through table is specified, the field's value should be of type MultiThroughRelationValue

type MultiThroughRelationValue

type MultiThroughRelationValue interface {
	attrs.Binder
	ParentInfo() *ParentInfo
	SetValues(instances []Relation)
	GetValues() []Relation
}

A model field's value can adhere to this interface to indicate that the field's relation values can be set or retrieved.

This is used for ManyToMany relations with a through table, a through table is required for ManyToMany relations.

A default implementation is provided with the RelM2M type.

type NoJoins

type NoJoins string

custom string type for preloads, this allows us to skip having to set up possible expensive database joins

type ObjectActor

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

ObjectActor is a struct that can be used to run actions on objects that implement the respective actor interfaces.

The Actor function must be called to create a new ObjectActor instance, otherwise the ObjectActor's methods will immediately return the context unchanged.

If the object does not implement the respective actor interface, the method called will return the context unchanged and no error.

It can be used to run the following actions: - BeforeSave: runs before the object is saved to the database. - AfterSave: runs after the object is saved to the database. - BeforeCreate: runs before the object is created in the database. - AfterCreate: runs after the object is created in the database. - BeforeUpdate: runs before the object is updated in the database. - AfterUpdate: runs after the object is updated in the database. - BeforeDelete: runs before the object is deleted from the database. - AfterDelete: runs after the object is deleted from the database.

When an object has it's actor methods called, it will automatically mark the object as seen in the context. This prevents the same actor from being run multiple times for the same object in the same context.

It is only needed for advanced use cases if you are saving objects to the database manually and want to ensure that the BeforeSave and AfterSave methods are called.

func Actor

func Actor(obj attrs.Definer) *ObjectActor

Actor returns a new ObjectActor that can be used to run actions on objects. If the object does not implement the respective actor interface, the method called will return the context unchanged and no error.

func (*ObjectActor) AfterCreate

func (s *ObjectActor) AfterCreate(ctx context.Context) (context.Context, error)

func (*ObjectActor) AfterDelete

func (s *ObjectActor) AfterDelete(ctx context.Context) (context.Context, error)

func (*ObjectActor) AfterQuery

func (s *ObjectActor) AfterQuery(ctx context.Context) (context.Context, error)

func (*ObjectActor) AfterSave

func (s *ObjectActor) AfterSave(ctx context.Context) (context.Context, error)

func (*ObjectActor) AfterUpdate

func (s *ObjectActor) AfterUpdate(ctx context.Context) (context.Context, error)

func (*ObjectActor) BeforeCreate

func (s *ObjectActor) BeforeCreate(ctx context.Context) (context.Context, error)

func (*ObjectActor) BeforeDelete

func (s *ObjectActor) BeforeDelete(ctx context.Context) (context.Context, error)

func (*ObjectActor) BeforeSave

func (s *ObjectActor) BeforeSave(ctx context.Context) (context.Context, error)

func (*ObjectActor) BeforeUpdate

func (s *ObjectActor) BeforeUpdate(ctx context.Context) (context.Context, error)

func (*ObjectActor) Fake

func (s *ObjectActor) Fake(ctx context.Context, flags ...actorFlag) context.Context

Fake is a no-op method that marks the actor as seen in the context.

It is used to ensure that the actor is seen in the context.

This is useful if a function which might execute an actor returns no context - if an actor was already executed in said function the actor could be executed again

See QuerySet.Create and QuerySet.Update for examples of this.

type ObjectsFunc

type ObjectsFunc[T attrs.Definer] func(model T) *QuerySet[T]

ObjectsFunc is a function type that takes a model of type T and returns a QuerySet for that model.

It is used to create a new QuerySet for a model which is automatically initialized with a transaction.

See RunInTransaction for more details.

type OrderByDefiner

type OrderByDefiner interface {
	attrs.Definer
	OrderBy() []string
}

OrderByDefiner is an interface that can be implemented by models to indicate that the model has a default ordering that should be used when executing queries.

type ParentInfo

type ParentInfo struct {
	Object attrs.Definer
	Field  attrs.Field
}

ParentInfo holds information about a relation's parent model instance and the field on the parent model that holds the relation.

type Preload

type Preload struct {
	FieldName  string
	Path       string
	ParentPath string
	Chain      []string
	Rel        attrs.Relation
	Primary    attrs.FieldDefinition
	Model      attrs.Definer
	QuerySet   *QuerySet[attrs.Definer]
	Field      attrs.FieldDefinition
	Results    *PreloadResults
}

type PreloadResults

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

type ProxyField

type ProxyField interface {
	attrs.FieldDefinition
	TargetClauseField
	IsProxy() bool
}

type ProxyThroughField

type ProxyThroughField interface {
	attrs.FieldDefinition
	TargetClauseThroughField
	IsProxy() bool
}

type QueryCompiler

type QueryCompiler interface {
	// DatabaseName returns the name of the database connection used by the query compiler.
	//
	// This is the name of the database connection as defined in the django.Global.Settings object.
	DatabaseName() string

	// DB returns the database connection used by the query compiler.
	//
	// If a transaction was started, it will return the transaction instead of the database connection.
	DB() drivers.DB

	// ExpressionInfo returns a usable [expr.ExpressionInfo] for the compiler.
	//
	// This is used to parse raw queries inside of [QuerySet.Rows], [QuerySet.Row] and [QuerySet.Exec].
	//
	// Allowing for the use of GO field names in a raw SQL query.
	ExpressionInfo(qs *QuerySet[attrs.Definer], internals *QuerySetInternals) *expr.ExpressionInfo

	// Quote returns the quotes used by the database.
	//
	// This is used to quote table and field names.
	// For example, MySQL uses backticks (`) and PostgreSQL uses double quotes (").
	Quote() (front string, back string)

	// Placeholder returns the placeholder used by the database for query parameters.
	// This is used to format query parameters in the SQL query.
	// For example, MySQL uses `?` and PostgreSQL uses `$1`, `$2` (but can support `?` as well).
	Placeholder() string

	// FormatColumn formats the given field column to be used in a query.
	// It should return the column name with the quotes applied.
	// Expressions should use this method to format the column name.
	FormatColumn(aliasGen *alias.Generator, tableColumn *expr.TableColumn) (string, []any)

	// SupportsReturning returns the type of returning supported by the database.
	// It can be one of the following:
	//
	// - SupportsReturningNone: no returning supported
	// - SupportsReturningLastInsertId: last insert id supported
	// - SupportsReturningColumns: returning columns supported
	SupportsReturning() drivers.SupportsReturningType

	// StartTransaction starts a new transaction.
	StartTransaction(ctx context.Context) (drivers.Transaction, error)

	// WithTransaction wraps the transaction and binds it to the compiler.
	WithTransaction(tx drivers.Transaction) (drivers.Transaction, error)

	// Transaction returns the current transaction if one is active.
	Transaction() drivers.Transaction

	// InTransaction returns true if the current query compiler is in a transaction.
	InTransaction() bool

	// PrepForLikeQuery prepares a value for a LIKE query.
	//
	// It should return the value as a string, with values like `%` and `_` escaped
	// according to the database's LIKE syntax.
	PrepForLikeQuery(v any) string

	// BuildSelectQuery builds a select query with the given parameters.
	BuildSelectQuery(
		ctx context.Context,
		qs *QuerySet[attrs.Definer],
		internals *QuerySetInternals,
	) CompiledQuery[[][]interface{}]

	// BuildCountQuery builds a count query with the given parameters.
	BuildCountQuery(
		ctx context.Context,
		qs *QuerySet[attrs.Definer],
		internals *QuerySetInternals,
	) CompiledQuery[int64]

	// BuildCreateQuery builds a create query with the given parameters.
	BuildCreateQuery(
		ctx context.Context,
		qs *QuerySet[attrs.Definer],
		internals *QuerySetInternals,
		objects []UpdateInfo,
	) CompiledQuery[[][]interface{}]

	BuildUpdateQuery(
		ctx context.Context,
		qs *GenericQuerySet,
		internals *QuerySetInternals,
		objects []UpdateInfo,
	) CompiledQuery[int64]

	// BuildUpdateQuery builds an update query with the given parameters.
	BuildDeleteQuery(
		ctx context.Context,
		qs *QuerySet[attrs.Definer],
		internals *QuerySetInternals,
	) CompiledQuery[int64]
}

A QueryCompiler interface is used to compile a query.

It should be able to generate SQL queries and execute them.

It does not need to know about the model nor its field types.

func Compiler

func Compiler(defaultDB string) QueryCompiler

Compiler returns a QueryCompiler for the given model and default database name.

If the default database name is empty, it will use the APPVAR_DATABASE setting.

If the database is not found in the settings, it will panic.

func NewGenericQueryBuilder

func NewGenericQueryBuilder(db string) QueryCompiler

func NewMariaDBQueryBuilder

func NewMariaDBQueryBuilder(db string) QueryCompiler

func NewMySQLQueryBuilder

func NewMySQLQueryBuilder(db string) QueryCompiler

func NewPostgresQueryBuilder

func NewPostgresQueryBuilder(db string) QueryCompiler

type QueryInfo

type QueryInfo interface {
	SQL() string
	Args() []any
	Model() attrs.Definer
	Compiler() QueryCompiler
}

A QueryInfo interface is used to retrieve information about a query.

It is possible to introspect the queries' SQL, arguments, model, and compiler.

type QueryInformation

type QueryInformation struct {
	Object  attrs.Definer
	Params  []any
	Stmt    string
	Builder QueryCompiler
}

func (*QueryInformation) Args

func (q *QueryInformation) Args() []any

func (*QueryInformation) Compiler

func (q *QueryInformation) Compiler() QueryCompiler

func (*QueryInformation) Model

func (q *QueryInformation) Model() attrs.Definer

func (*QueryInformation) SQL

func (q *QueryInformation) SQL() string

type QueryObject

type QueryObject[T1 any] struct {
	QueryInfo
	Execute func(sql string, args ...any) (T1, error)
}

func ErrorQueryObject

func ErrorQueryObject[T1 any](object attrs.Definer, builder QueryCompiler, possibleError error) *QueryObject[T1]

func (*QueryObject[T1]) Exec

func (q *QueryObject[T1]) Exec() (T1, error)

type QuerySet

type QuerySet[T attrs.Definer] struct {
	AliasGen *alias.Generator
	// contains filtered or unexported fields
}

QuerySet is a struct that represents a query set in the database.

It contains methods to filter, order, and limit the results of a query.

It is used to build and execute queries against the database.

Every method on the queryset returns a new queryset, so that the original queryset is not modified.

It also has a chainable api, so that you can easily build complex queries by chaining methods together.

Queries are built internally with the help of the QueryCompiler interface, which is responsible for generating the SQL queries for the database.

func ChangeObjectsType

func ChangeObjectsType[OldT, NewT attrs.Definer](qs *QuerySet[OldT]) *QuerySet[NewT]

Change the type of the objects in the QuerySet.

Mostly used to change the type of the QuerySet from the generic QuerySet[attrs.Definer] to a concrete non-interface type

Some things to note: - This does not clone the QuerySet - If the type mismatches and is not assignable, it will panic.

func GetQuerySet

func GetQuerySet[T attrs.Definer](model T) *QuerySet[T]

GetQuerySet creates a new QuerySet for the given model.

If the model implements the QuerySetDefiner interface, it will use the GetQuerySet method to get the initial QuerySet.

A model should use Objects[T](model) to get the default QuerySet inside of it's GetQuerySet method. If not, it will recursively call itself.

See Objects for more details.

func GetQuerySetWithContext

func GetQuerySetWithContext[T attrs.Definer](ctx context.Context, model T) *QuerySet[T]

GetQuerySetWithContext creates a new QuerySet for the given model with the given context bound to it.

For more information, see GetQuerySet.

func Objects

func Objects[T attrs.Definer](model T, database ...string) *QuerySet[T]

Objects creates a new QuerySet for the given model.

This function should only be called in a model's GetQuerySet method.

In other places the GetQuerySet function should be used instead.

It panics if: - the model is nil - the base query info cannot be retrieved

It returns a pointer to a new QuerySet.

The model must implement the Definer interface.

func (*QuerySet[T]) Aggregate

func (qs *QuerySet[T]) Aggregate(annotations map[string]expr.Expression) (map[string]any, error)

Aggregate is used to perform aggregation on the results of a query.

It takes a map of field names to expr.Expressions as arguments and returns a Query that can be executed to get the results.

func (*QuerySet[T]) Alias

func (qs *QuerySet[T]) Alias() *alias.Generator

func (*QuerySet[T]) All

func (qs *QuerySet[T]) All() (Rows[T], error)

All is used to retrieve all rows from the database.

It returns a Query that can be executed to get the results, which is a slice of Row objects.

Each Row object contains the model object and a map of annotations.

If no fields are provided, it selects all fields from the model, see `Select()` for more details.

func (*QuerySet[T]) Annotate

func (qs *QuerySet[T]) Annotate(aliasOrAliasMap interface{}, exprs ...expr.Expression) *QuerySet[T]

Annotate is used to add annotations to the results of a query.

It takes a string or a map of strings to expr.Expressions as arguments and returns a new QuerySet with the annotations.

If a string is provided, it is used as the alias for the expr.Expression.

If a map is provided, the keys are used as aliases for the expr.Expressions.

func (*QuerySet[T]) BatchCreate

func (qs *QuerySet[T]) BatchCreate(objects []T) ([]T, error)

BatchCreate is used to create multiple objects in the database.

It takes a list of definer objects as arguments and returns a Query that can be executed to get the result, which is a slice of the created objects.

The query is executed in a transaction, so if any error occurs, the transaction is rolled back. You can specify the batch size to limit the number of objects created in a single query.

The batch size is based on the [Limit] method of the queryset, which defaults to 1000.

func (*QuerySet[T]) BatchUpdate

func (qs *QuerySet[T]) BatchUpdate(objects []T, exprs ...any) (int64, error)

BatchUpdate is used to update multiple objects in the database.

It takes a list of definer objects as arguments and returns a Query that can be executed to get the result, which is a slice of the updated objects.

The query is executed in a transaction, so if any error occurs, the transaction is rolled back. You can specify the batch size to limit the number of objects updated in a single query.

The batch size is based on the [Limit] method of the queryset, which defaults to 1000.

func (*QuerySet[T]) BuildExpression

func (qs *QuerySet[T]) BuildExpression() expr.Expression

func (*QuerySet[T]) BulkCreate

func (qs *QuerySet[T]) BulkCreate(objects []T) ([]T, error)

BulkCreate is used to create multiple objects in the database.

It takes a list of definer objects as arguments and returns a Query that can be executed to get the result, which is a slice of the created objects.

It panics if a non- nullable field is null or if the field is not found in the model.

This function will run the ActsBeforeCreate and ActsAfterCreate actor methods for each object, as well as send the SignalPreModelSave and SignalPostModelSave signals.

func (*QuerySet[T]) BulkUpdate

func (qs *QuerySet[T]) BulkUpdate(objects []T, expressions ...any) (int64, error)

BulkUpdate is used to update multiple objects in the database.

It takes a list of definer objects as arguments and any possible NamedExpressions. It does not try to call any save methods on the objects.

It will run the actor methods of ActsBeforeUpdate and ActsAfterUpdate for each object, as well as send the SignalPreModelSave and SignalPostModelSave signals.

func (*QuerySet[T]) Clone

func (qs *QuerySet[T]) Clone() *QuerySet[T]

Clone creates a new QuerySet with the same parameters as the original one.

It is used to create a new QuerySet with the same parameters as the original one, so that the original one is not modified.

It is a shallow clone, underlying values like `*queries.Expr` are not cloned and have built- in immutability.

func (*QuerySet[T]) Compiler

func (qs *QuerySet[T]) Compiler() QueryCompiler

Return the compiler which the queryset is using.

func (*QuerySet[T]) Context

func (qs *QuerySet[T]) Context() context.Context

Context returns the context of the QuerySet.

It is used to pass a context to the QuerySet, which is mainly used for transaction management.

func (*QuerySet[T]) Count

func (qs *QuerySet[T]) Count() (int64, error)

Count is used to count the number of rows in the database.

It returns a CountQuery that can be executed to get the result, which is an int64 indicating the number of rows.

func (*QuerySet[T]) Create

func (qs *QuerySet[T]) Create(value T) (T, error)

Create is used to create a new object in the database.

It takes a definer object as an argument and returns a Query that can be executed to get the result, which is the created object.

It panics if a non- nullable field is null or if the field is not found in the model.

The model can adhere to django's `models.Saver` interface, in which case the `Save()` method will be called unless `ExplicitSave()` was called on the queryset.

If `ExplicitSave()` was called, the `Create()` method will return a query that can be executed to create the object without calling the `Save()` method on the model.

func (*QuerySet[T]) DB

func (qs *QuerySet[T]) DB() drivers.DB

Return the underlying database which the compiler is using.

func (*QuerySet[T]) Delete

func (qs *QuerySet[T]) Delete(objects ...T) (int64, error)

Delete is used to delete an object from the database.

It returns a CountQuery that can be executed to get the result, which is the number of rows affected.

If any objects are provided, it will generate a where clause based on GenerateObjectsWhereClause. It will also run the ActsBeforeDelete and ActsAfterDelete actor methods and send SignalPreModelDelete and SignalPostModelDelete signals.

func (*QuerySet[T]) Distinct

func (qs *QuerySet[T]) Distinct() *QuerySet[T]

Distinct is used to select distinct rows from the results of a query.

It is used to remove duplicate rows from the results.

func (*QuerySet[T]) Exec

func (qs *QuerySet[T]) Exec(sqlStr string, args ...interface{}) (sql.Result, error)

Exec executes the given SQL on the compilers' current database and returns the result.

It uses the same context and transaction as the rest of the QuerySet.

It first tries to resolve and parse the SQL statement, see expr.ParseExprStatement for more details.

func (*QuerySet[T]) Exists

func (qs *QuerySet[T]) Exists() (bool, error)

Exists is used to check if any rows exist in the database.

It returns a Query that can be executed to get the result, which is a boolean indicating if any rows exist.

func (*QuerySet[T]) ExplicitSave

func (qs *QuerySet[T]) ExplicitSave() *QuerySet[T]

ExplicitSave is used to indicate that the save operation should be explicit.

It is used to prevent the automatic save operation from being performed on the model.

I.E. when using the `Create` method after calling `qs.ExplicitSave()`, it will **not** automatically save the model to the database using the model's own `Save` method.

func (*QuerySet[T]) Filter

func (qs *QuerySet[T]) Filter(key interface{}, vals ...interface{}) *QuerySet[T]

Filter is used to filter the results of a query.

It takes a key and a list of values as arguments and returns a new QuerySet with the filtered results.

The key can be a field name (string), an expr.Expression (expr.Expression) or a map of field names to values.

By default the `__exact` (=) operator is used, each where clause is separated by `AND`.

func (*QuerySet[T]) First

func (qs *QuerySet[T]) First() (*Row[T], error)

First is used to retrieve the first row from the database.

It returns a Query that can be executed to get the result, which is a Row object that contains the model object and a map of annotations.

func (*QuerySet[T]) ForEachRow

func (qs *QuerySet[T]) ForEachRow(rowFunc func(qs *QuerySet[T], row *Row[T]) error) *QuerySet[T]

func (*QuerySet[T]) ForUpdate

func (qs *QuerySet[T]) ForUpdate() *QuerySet[T]

ForUpdate is used to lock the rows returned by a query for update.

It is used to prevent other transactions from modifying the rows until the current transaction is committed or rolled back.

func (*QuerySet[T]) Get

func (qs *QuerySet[T]) Get() (*Row[T], error)

Get is used to retrieve a single row from the database.

It returns a Query that can be executed to get the result, which is a Row object that contains the model object and a map of annotations.

It panics if the queryset has no where clause.

If no rows are found, it returns queries.errors.ErrNoRows.

If multiple rows are found, it returns queries.errors.ErrMultipleRows.

func (*QuerySet[T]) GetOrCreate

func (qs *QuerySet[T]) GetOrCreate(value T) (T, bool, error)

GetOrCreate is used to retrieve a single row from the database or create it if it does not exist.

It returns the definer object and an error if any occurred.

This method executes a transaction to ensure that the object is created only once.

It panics if the queryset has no where clause.

func (*QuerySet[T]) GetOrCreateTransaction

func (qs *QuerySet[T]) GetOrCreateTransaction() (tx drivers.Transaction, err error)

GetOrCreateTransaction returns the current transaction if one exists, or starts a new transaction if the QuerySet is not already in a transaction and QUERYSET_CREATE_IMPLICIT_TRANSACTION is true.

func (*QuerySet[T]) GoString

func (qs *QuerySet[T]) GoString() string

Return a detailed string representation of the QuerySet.

func (*QuerySet[T]) GroupBy

func (qs *QuerySet[T]) GroupBy(fields ...any) *QuerySet[T]

GroupBy is used to group the results of a query.

It takes a list of field names as arguments and returns a new QuerySet with the grouped results.

func (*QuerySet[T]) HasWhereClause

func (qs *QuerySet[T]) HasWhereClause() bool

HasWhereClause returns true if the QuerySet has a WHERE clause.

func (*QuerySet[T]) Having

func (qs *QuerySet[T]) Having(key interface{}, vals ...interface{}) *QuerySet[T]

Having is used to filter the results of a query after aggregation.

It takes a key and a list of values as arguments and returns a new QuerySet with the filtered results.

The key can be a field name (string), an expr.Expression (expr.Expression) or a map of field names to values.

func (*QuerySet[T]) IterAll

func (qs *QuerySet[T]) IterAll() (int, iter.Seq2[*Row[T], error], error)

IterAll returns an iterator over all rows in the QuerySet, and the amount of rows to iterate over.

If [ForEachRow] is set, it will be used to process each row inside of the iterator.

func (*QuerySet[T]) Last

func (qs *QuerySet[T]) Last() (*Row[T], error)

Last is used to retrieve the last row from the database.

It reverses the order of the results and then calls First to get the last row.

It returns a Query that can be executed to get the result, which is a Row object that contains the model object and a map of annotations.

func (*QuerySet[T]) LatestQuery

func (qs *QuerySet[T]) LatestQuery() QueryInfo

LatestQuery returns the latest query that was executed on the queryset.

func (*QuerySet[T]) Limit

func (qs *QuerySet[T]) Limit(n int) *QuerySet[T]

Limit is used to limit the number of results returned by a query.

func (*QuerySet[T]) Meta

func (qs *QuerySet[T]) Meta() expr.ModelMeta

Meta returns the model meta information for the QuerySet.

func (*QuerySet[T]) Offset

func (qs *QuerySet[T]) Offset(n int) *QuerySet[T]

Offset is used to set the offset of the results returned by a query.

func (*QuerySet[T]) OrderBy

func (qs *QuerySet[T]) OrderBy(fields ...string) *QuerySet[T]

OrderBy is used to order the results of a query.

It takes a list of field names as arguments and returns a new QuerySet with the ordered results.

The field names can be prefixed with a minus sign (-) to indicate descending order.

func (*QuerySet[T]) Peek

func (qs *QuerySet[T]) Peek() expr.QueryInformation

func (*QuerySet[T]) Prefix

func (qs *QuerySet[T]) Prefix(prefix string) *QuerySet[T]

Prefix sets the prefix for the alias generator

func (*QuerySet[T]) Preload

func (qs *QuerySet[T]) Preload(fields ...any) *QuerySet[T]

func (*QuerySet[T]) QueryAggregate

func (qs *QuerySet[T]) QueryAggregate() CompiledQuery[[][]interface{}]

func (*QuerySet[T]) QueryAll

func (qs *QuerySet[T]) QueryAll(fields ...any) CompiledQuery[[][]interface{}]

func (*QuerySet[T]) QueryCount

func (qs *QuerySet[T]) QueryCount() CompiledQuery[int64]

func (*QuerySet[T]) Resolve

func (qs *QuerySet[T]) Resolve(fieldName string, inf *expr.ExpressionInfo) (attrs.Definer, attrs.FieldDefinition, *expr.TableColumn, error)

func (*QuerySet[T]) Reverse

func (qs *QuerySet[T]) Reverse() *QuerySet[T]

Reverse is used to reverse the order of the results of a query.

It returns a new QuerySet with the reversed order.

func (*QuerySet[T]) Row

func (qs *QuerySet[T]) Row(sqlStr string, args ...interface{}) drivers.SQLRow

Row is used to execute a raw SQL query on the compilers' current database and returns a single row of type drivers.SQLRow.

It first tries to resolve and parse the SQL statement, see expr.ParseExprStatement for more details.

func (*QuerySet[T]) Rows

func (qs *QuerySet[T]) Rows(sqlStr string, args ...interface{}) (drivers.SQLRows, error)

Rows is used to execute a raw SQL query on the compilers' current database.

It returns a drivers.SQLRows object that can be used to iterate over the results. The same transaction and context as the rest of the QuerySet will be used.

It first tries to resolve and parse the SQL statement, see expr.ParseExprStatement for more details.

func (*QuerySet[T]) Scope

func (qs *QuerySet[T]) Scope(scopes ...func(*QuerySet[T], *QuerySetInternals) *QuerySet[T]) *QuerySet[T]

Scope is used to apply a scope to the QuerySet.

It takes a function that modifies the QuerySet as an argument and returns a QuerySet with the applied scope.

The queryset is modified in place, so the original QuerySet is changed.

func (*QuerySet[T]) Select

func (qs *QuerySet[T]) Select(fields ...any) *QuerySet[T]

Select is used to select specific fields from the model.

It takes a list of field names as arguments and returns a new QuerySet with the selected fields.

If no fields are provided, it selects all fields from the model.

If the first field is "*", it selects all fields from the model, extra fields (i.e. relations) can be provided thereafter - these will also be added to the selection.

How to call Select:

`Select("*")` `Select("Field1", "Field2")` `Select("Field1", "Field2", "Relation.*")` `Select("*", "Relation.*")` `Select("Relation.*")` `Select("*", "Relation.Field1", "Relation.Field2", "Relation.Nested.*")`

func (*QuerySet[T]) SelectRelated

func (qs *QuerySet[T]) SelectRelated(fields ...string) *QuerySet[T]

func (*QuerySet[T]) StartTransaction

func (qs *QuerySet[T]) StartTransaction(ctx context.Context) (drivers.Transaction, error)

StartTransaction starts a transaction on the underlying database.

It returns a transaction object which can be used to commit or rollback the transaction.

func (*QuerySet[T]) String

func (qs *QuerySet[T]) String() string

Return the string representation of the QuerySet.

It shows a truncated list of the first 20 results, or an error if one occurred.

This method WILL query the database!

func (*QuerySet[T]) Union

func (qs *QuerySet[T]) Union(other *QuerySet[attrs.Definer]) *QuerySet[T]

Union is used to combine the results of two queries.

It takes another QuerySet as an argument and returns a new QuerySet with the combined results.

func (*QuerySet[T]) Update

func (qs *QuerySet[T]) Update(value T, expressions ...any) (int64, error)

Update is used to update an object in the database.

It takes a definer object as an argument and returns a CountQuery that can be executed to get the result, which is the number of rows affected.

It panics if a non- nullable field is null or if the field is not found in the model.

If the model adheres to django's `models.Saver` interface, no where clause is provided and ExplicitSave() was not called, the `Save()` method will be called on the model

func (*QuerySet[T]) Values

func (qs *QuerySet[T]) Values(fields ...any) ([]map[string]any, error)

Values is used to retrieve a list of dictionaries from the database.

It takes a list of field names as arguments and returns a list of maps.

Each map contains the field names as keys and the field values as values. If no fields are provided, it selects all fields from the model, see [Select] for more details.

func (*QuerySet[T]) ValuesList

func (qs *QuerySet[T]) ValuesList(fields ...any) ([][]interface{}, error)

ValuesList is used to retrieve a list of values from the database.

It takes a list of field names as arguments and returns a ValuesListQuery.

func (*QuerySet[T]) WalkField

func (qs *QuerySet[T]) WalkField(selectedField string, options ...func(*WalkOptions)) (res *WalkFieldResult[T], err error)

func (*QuerySet[T]) WithContext

func (qs *QuerySet[T]) WithContext(ctx context.Context) *QuerySet[T]

WithContext sets the context for the QuerySet.

If a transaction is present in the context for the current database, it will be used for the QuerySet.

It panics if the context is nil. This is used to pass a context to the QuerySet, which is mainly used for transaction management.

func (*QuerySet[T]) WithTransaction

func (qs *QuerySet[T]) WithTransaction(tx drivers.Transaction) (drivers.Transaction, error)

WithTransaction wraps the transaction and binds it to the QuerySet compiler.

type QuerySetCanAfterExec

type QuerySetCanAfterExec interface {
	AfterExec(res any) error
}

type QuerySetCanBeforeExec

type QuerySetCanBeforeExec interface {
	BeforeExec() error
}

type QuerySetCanClone

type QuerySetCanClone[T attrs.Definer, CONV any, ORIG BaseQuerySet[T, ORIG]] interface {
	CloneQuerySet(*WrappedQuerySet[T, CONV, ORIG]) CONV
}

type QuerySetCanSetup

type QuerySetCanSetup interface {
	Setup()
}

type QuerySetChanger

type QuerySetChanger interface {
	attrs.Definer

	// ChangeQuerySet is called when the model is used in a queryset.
	// It should return a new queryset that will be used to execute the query.
	ChangeQuerySet(qs *QuerySet[attrs.Definer]) *QuerySet[attrs.Definer]
}

QuerySetChanger is an interface that can be implemented by models to indicate that the queryset should be changed when the model is used in a queryset.

type QuerySetDatabaseDefiner

type QuerySetDatabaseDefiner interface {
	attrs.Definer

	QuerySetDatabase() string
}

A model can adhere to this interface to indicate that the queries package should use the database returned by `QuerySetDatabase()` to execute the query.

The database should be retrieved from the django.Global.Settings object using the returned key.

type QuerySetDefiner

type QuerySetDefiner interface {
	attrs.Definer

	GetQuerySet() *QuerySet[attrs.Definer]
}

A model can adhere to this interface to indicate that the queries package should use the queryset returned by `GetQuerySet()` to execute the query.

Calling `queries.Objects()` with a model that implements this interface will return the queryset returned by `GetQuerySet()`.

type QuerySetInternals

type QuerySetInternals struct {
	Model       modelInfo
	Annotations *orderedmap.OrderedMap[string, attrs.Field]
	Fields      []*FieldInfo[attrs.FieldDefinition]
	Preload     *QuerySetPreloads
	Unions      []*QuerySet[attrs.Definer]
	Where       []expr.ClauseExpression
	Having      []expr.ClauseExpression
	Joins       []JoinDef
	GroupBy     []*FieldInfo[attrs.FieldDefinition]
	OrderBy     []expr.OrderBy
	Limit       int
	Offset      int
	ForUpdate   bool
	Distinct    bool
	// contains filtered or unexported fields
}

Internals contains the internal state of the QuerySet.

It includes all nescessary information for the compiler to build a query out of.

func (*QuerySetInternals) AddField

func (i *QuerySetInternals) AddField(field *FieldInfo[attrs.FieldDefinition])

func (*QuerySetInternals) AddJoin

func (i *QuerySetInternals) AddJoin(join JoinDef)

func (*QuerySetInternals) HasField

type QuerySetPreloads

type QuerySetPreloads struct {
	Preloads []*Preload
	// contains filtered or unexported fields
}

func (*QuerySetPreloads) Copy

type RebindCompiler

type RebindCompiler interface {
	QueryCompiler
	Rebind(ctx context.Context, s string) string
}

RebindCompiler is an interface that can be implemented by compilers to indicate that the compiler can rebind queries to a different database.

In simple terms, it allows the compiler to change the placeholder syntax for query parameters when the query is executed on a different database.

If the compiler does not implement this interface, it will not be able to rebind queries, rebind functionality will not be available when calling QuerySet.Rows, QuerySet.Row and QuerySet.Exec.

type RelFK

type RelFK[ModelType attrs.Definer] struct {
	Parent *ParentInfo // The parent model instance
	Object ModelType
}

func (*RelFK[T]) BindToModel

func (rl *RelFK[T]) BindToModel(parent attrs.Definer, parentField attrs.Field) error

func (*RelFK[T]) GetValue

func (rl *RelFK[T]) GetValue() attrs.Definer

GetValue returns the related object on the relation.

func (*RelFK[T]) Model

func (rl *RelFK[T]) Model() attrs.Definer

func (*RelFK[T]) ParentInfo

func (rl *RelFK[T]) ParentInfo() *ParentInfo

func (*RelFK[T]) SetValue

func (rl *RelFK[T]) SetValue(instance attrs.Definer)

SetValue sets the related object on the relation.

type RelM2M

type RelM2M[ModelType, ThroughModelType attrs.Definer] struct {
	Parent *ParentInfo // The parent model instance
	// contains filtered or unexported fields
}

A value which can be used on models to represent a Many-to-Many relation with a through model.

This implements the [SettableMultiThroughRelation] interface, which allows setting the related objects and their through objects.

func (*RelM2M[T1, T2]) AsList

func (rl *RelM2M[T1, T2]) AsList() []RelO2O[T1, T2]

func (*RelM2M[T1, T2]) BindToModel

func (rl *RelM2M[T1, T2]) BindToModel(parent attrs.Definer, parentField attrs.Field) error

func (*RelM2M[T1, T2]) Cache

func (rl *RelM2M[T1, T2]) Cache() *orderedmap.OrderedMap[any, RelO2O[T1, T2]]

func (*RelM2M[T1, T2]) GetValues

func (rl *RelM2M[T1, T2]) GetValues() []Relation

GetValues returns the related objects and their through objects.

func (*RelM2M[T1, T2]) Len

func (rl *RelM2M[T1, T2]) Len() int

func (*RelM2M[T1, T2]) Objects

func (rl *RelM2M[T1, T2]) Objects() *RelManyToManyQuerySet[T1]

func (*RelM2M[T1, T2]) ParentInfo

func (rl *RelM2M[T1, T2]) ParentInfo() *ParentInfo

func (*RelM2M[T1, T2]) SetValues

func (rl *RelM2M[T1, T2]) SetValues(rel []Relation)

type RelManyToManyQuerySet

type RelManyToManyQuerySet[T attrs.Definer] struct {
	// contains filtered or unexported fields
}

func ManyToManyQuerySet

func ManyToManyQuerySet[T attrs.Definer](backRef MultiThroughRelationValue) *RelManyToManyQuerySet[T]

func (*RelManyToManyQuerySet[T]) AddTarget

func (r *RelManyToManyQuerySet[T]) AddTarget(target T) (created bool, err error)

func (*RelManyToManyQuerySet[T]) AddTargets

func (r *RelManyToManyQuerySet[T]) AddTargets(targets ...T) (int64, error)

func (RelManyToManyQuerySet) All

func (t RelManyToManyQuerySet) All() (Rows[T], error)

func (*RelManyToManyQuerySet[T]) ClearTargets

func (r *RelManyToManyQuerySet[T]) ClearTargets() (int64, error)

func (RelManyToManyQuerySet) Filter

func (t RelManyToManyQuerySet) Filter(key any, vals ...any) T2

func (RelManyToManyQuerySet) Get

func (t RelManyToManyQuerySet) Get() (*Row[T], error)

func (RelManyToManyQuerySet) Limit

func (t RelManyToManyQuerySet) Limit(limit int) T2

func (RelManyToManyQuerySet) Offset

func (t RelManyToManyQuerySet) Offset(offset int) T2

func (RelManyToManyQuerySet) OrderBy

func (t RelManyToManyQuerySet) OrderBy(fields ...string) T2

func (*RelManyToManyQuerySet[T]) RemoveTargets

func (r *RelManyToManyQuerySet[T]) RemoveTargets(targets ...any) (int64, error)

func (*RelManyToManyQuerySet[T]) SetTargets

func (r *RelManyToManyQuerySet[T]) SetTargets(targets []T) (added int64, err error)

func (RelManyToManyQuerySet) WithContext

func (t RelManyToManyQuerySet) WithContext(ctx context.Context) T2

type RelManyToOneQuerySet

type RelManyToOneQuerySet[T attrs.Definer] struct {
	// contains filtered or unexported fields
}

func ManyToOneQuerySet

func ManyToOneQuerySet[T attrs.Definer](backRef MultiRelationValue) *RelManyToOneQuerySet[T]

func (RelManyToOneQuerySet) All

func (t RelManyToOneQuerySet) All() (Rows[T], error)

func (RelManyToOneQuerySet) Filter

func (t RelManyToOneQuerySet) Filter(key any, vals ...any) T2

func (RelManyToOneQuerySet) Get

func (t RelManyToOneQuerySet) Get() (*Row[T], error)

func (RelManyToOneQuerySet) Limit

func (t RelManyToOneQuerySet) Limit(limit int) T2

func (RelManyToOneQuerySet) Offset

func (t RelManyToOneQuerySet) Offset(offset int) T2

func (RelManyToOneQuerySet) OrderBy

func (t RelManyToOneQuerySet) OrderBy(fields ...string) T2

func (RelManyToOneQuerySet) WithContext

func (t RelManyToOneQuerySet) WithContext(ctx context.Context) T2

type RelO2O

type RelO2O[ModelType, ThroughModelType attrs.Definer] struct {
	Parent        *ParentInfo // The parent model instance
	Object        ModelType
	ThroughObject ThroughModelType
}

A value which can be used on models to represent a One-to-One relation with a through model.

This implements the [SettableThroughRelation] interface, which allows setting the related object and its through object.

func (*RelO2O[T1, T2]) BindToModel

func (rl *RelO2O[T1, T2]) BindToModel(parent attrs.Definer, parentField attrs.Field) error

func (*RelO2O[T1, T2]) GetValue

func (rl *RelO2O[T1, T2]) GetValue() (obj attrs.Definer, through attrs.Definer)

func (*RelO2O[T1, T2]) Model

func (rl *RelO2O[T1, T2]) Model() attrs.Definer

func (*RelO2O[T1, T2]) ParentInfo

func (rl *RelO2O[T1, T2]) ParentInfo() *ParentInfo

func (*RelO2O[T1, T2]) SetValue

func (rl *RelO2O[T1, T2]) SetValue(instance attrs.Definer, through attrs.Definer)

func (*RelO2O[T1, T2]) Through

func (rl *RelO2O[T1, T2]) Through() attrs.Definer

type RelRevFK

type RelRevFK[ModelType attrs.Definer] struct {
	Parent *ParentInfo // The parent model instance
	// contains filtered or unexported fields
}

func (*RelRevFK[T]) AsList

func (rl *RelRevFK[T]) AsList() []T

Objects returns the related objects as a slice of ModelType.

func (*RelRevFK[T]) BindToModel

func (rl *RelRevFK[T]) BindToModel(parent attrs.Definer, parentField attrs.Field) error

func (*RelRevFK[T]) Cache

func (rl *RelRevFK[T]) Cache() *orderedmap.OrderedMap[any, T]

func (*RelRevFK[T]) GetValues

func (rl *RelRevFK[T]) GetValues() []attrs.Definer

GetValues returns the related objects on the relation.

func (*RelRevFK[T]) Objects

func (rl *RelRevFK[T]) Objects() *RelManyToOneQuerySet[T]

func (*RelRevFK[T]) ParentInfo

func (rl *RelRevFK[T]) ParentInfo() *ParentInfo

func (*RelRevFK[T]) SetValues

func (rl *RelRevFK[T]) SetValues(objects []attrs.Definer)

SetValues sets the related objects on the relation.

type RelatedField

type RelatedField interface {
	attrs.Field

	// This is used to determine the column name for the field, for example for a through table.
	GetTargetField() attrs.Field

	RelatedName() string
}

RelatedField is an interface that can be implemented by fields to indicate that the field is a related field.

For example, this is used in fields.RelationField to determine the column name for the target field.

If `GetTargetField()` returns nil, the primary field of the target model should be used instead.

type Relation

type Relation interface {

	// The target model of the relation.
	Model() attrs.Definer

	// The through model of the relation.
	Through() attrs.Definer
}

A base interface for relations.

This interface should only be used for OneToOne relations with a through table, or for ManyToMany relations with a through table.

It should contain the actual instances of the models involved in the relation, and the through model if applicable.

type RelationValue

type RelationValue interface {
	attrs.Binder
	ParentInfo() *ParentInfo
	GetValue() (obj attrs.Definer)
	SetValue(instance attrs.Definer)
}

A model field's value can adhere to this interface to indicate that the field's relation value can be set or retrieved.

This is used for OneToOne relations without a through table, if a through table is specified, the field's value should be of type ThroughRelationValue

A default implementation is provided with the RelO2O type.

type Row

type Row[T any] struct {
	Object          T
	ObjectFieldDefs attrs.Definitions
	Through         attrs.Definer // The through model instance, if applicable
	Annotations     map[string]any
}

A row represents a single row in the result set of a QuerySet.

It contains the model object, a map of annotations, and a pointer to the QuerySet.

The annotations map contains additional data that is not part of the model object, such as calculated fields or additional information derived from the query.

type Rows

type Rows[T any] []*Row[T]

A collection of Row[T] objects, where T is a type that implements attrs.Definer.

This collection is used to represent the result set of a QuerySet.

func (Rows[T]) Len

func (r Rows[T]) Len() int

func (Rows[T]) Objects

func (rows Rows[T]) Objects() iter.Seq[T]

Objects returns a sequence of model objects from the rows.

func (Rows[T]) Pluck

func (rows Rows[T]) Pluck(pathToField string) iter.Seq2[int, attrs.Field]

Pluck returns a sequence of field values from the rows based on the provided path to the field.

The path to the field is a dot-separated string that specifies the field to pluck from each row.

It traverses the field definitions of each row's object to find the specified field, and yields the index of that field. The index will be increased by one for each field processed.

type SaveableDependantField

type SaveableDependantField interface {
	attrs.Field

	// Save is called to save the field's value to the database.
	Save(ctx context.Context, parent attrs.Definer) error
}

type SaveableField

type SaveableField interface {
	attrs.Field
	// Save is called to save the field's value to the database.
	// It should return an error if the save operation fails.
	Save(ctx context.Context) error
}

type SignalSave

type SignalSave struct {
	Instance attrs.Definer
	Using    QueryCompiler
}

Signals are used to notify when a model instance is saved or deleted.

SignalSave is only meant to hold the model instance and the query compiler'

type Table

type Table struct {
	Name  string
	Alias string
}

A table represents a database table.

type TargetClauseField

type TargetClauseField interface {
	GenerateTargetClause(qs *QuerySet[attrs.Definer], internals *QuerySetInternals, lhs ClauseTarget, rhs ClauseTarget) JoinDef
}

type TargetClauseThroughField

type TargetClauseThroughField interface {
	GenerateTargetThroughClause(qs *QuerySet[attrs.Definer], internals *QuerySetInternals, lhs ClauseTarget, through ThroughClauseTarget, rhs ClauseTarget) (JoinDef, JoinDef)
}

type ThroughClauseTarget

type ThroughClauseTarget struct {
	Model attrs.Definer
	Table Table
	Left  attrs.FieldDefinition
	Right attrs.FieldDefinition
}

type ThroughModelSetter

type ThroughModelSetter interface {
	SetThroughModel(throughModel attrs.Definer)
}

A model can adhere to this interface to indicate that it can receive a through model for a relation.

This is used for OneToOne relations with a through table, or for ManyToMany relations with a through table.

The through model will be set on the target end of the relation.

type ThroughRelationValue

type ThroughRelationValue interface {
	attrs.Binder
	ParentInfo() *ParentInfo
	GetValue() (obj attrs.Definer, through attrs.Definer)
	SetValue(instance attrs.Definer, through attrs.Definer)
}

A model field's value can adhere to this interface to indicate that the field's relation value can be set or retrieved.

This is used for OneToOne relations with a through table, if no through table is specified, the field's value should be of type attrs.Definer

A default implementation is provided with the RelO2O type.

type UniqueTogetherDefiner

type UniqueTogetherDefiner interface {
	attrs.Definer
	UniqueTogether() [][]string
}

A model can adhere to this interface to indicate fields which are unique together.

type UpdateInfo

type UpdateInfo struct {
	FieldInfo[attrs.Field]
	Where  []expr.ClauseExpression
	Joins  []JoinDef
	Values []any
}

type ValidationContext

type ValidationContext struct {
	context.Context
	Data map[string]interface{}
}

func (*ValidationContext) HasValue

func (vc *ValidationContext) HasValue(key string) bool

func (*ValidationContext) SetValue

func (vc *ValidationContext) SetValue(key string, value any)

func (*ValidationContext) Value

func (vc *ValidationContext) Value(key any) any

type VirtualField

type VirtualField = expr.VirtualField

A field can adhere to this interface to indicate that the field should be rendered as SQL.

For example: this is used in fields.ExpressionField to render the expression as SQL.

type WalkFieldResult

type WalkFieldResult[T attrs.Definer] struct {
	Chain      *attrs.RelationChain
	Aliases    []string
	Annotation attrs.Field
	Fields     []*FieldInfo[attrs.FieldDefinition]
	Joins      []JoinDef
	// contains filtered or unexported fields
}

type WalkFlag

type WalkFlag int
const (
	WalkFlagNone      WalkFlag = 0
	WalkFlagAllFields WalkFlag = 1 << iota
	WalkFlagAddJoins
	WalkFlagSelectSubFields
	WalkFlagAddProxies
)

type WalkOptions

type WalkOptions struct {
	Expressions map[string]expr.NamedExpression // named expressions to use for the field
	Flags       WalkFlag                        // flags to use for the walk
}

type WrappedQuerySet

type WrappedQuerySet[T attrs.Definer, CONV any, ORIG BaseQuerySet[T, ORIG]] struct {
	BaseQuerySet[T, ORIG]
	// contains filtered or unexported fields
}

func WrapQuerySet

func WrapQuerySet[T attrs.Definer, CONV any, ORIG BaseQuerySet[T, ORIG]](qs ORIG, embedder CONV) *WrappedQuerySet[T, CONV, ORIG]

func (*WrappedQuerySet[T, CONV, ORIG]) Aggregate

func (w *WrappedQuerySet[T, CONV, ORIG]) Aggregate(annotations map[string]expr.Expression) (map[string]any, error)

func (*WrappedQuerySet[T, CONV, ORIG]) All

func (w *WrappedQuerySet[T, CONV, ORIG]) All() (Rows[T], error)

func (*WrappedQuerySet[T, CONV, ORIG]) Annotate

func (w *WrappedQuerySet[T, CONV, ORIG]) Annotate(aliasOrAliasMap interface{}, exprs ...expr.Expression) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Base

func (w *WrappedQuerySet[T, CONV, ORIG]) Base() ORIG

func (*WrappedQuerySet[T, CONV, ORIG]) BuildExpression

func (w *WrappedQuerySet[T, CONV, ORIG]) BuildExpression() expr.Expression

func (*WrappedQuerySet[T, CONV, ORIG]) Clone

func (w *WrappedQuerySet[T, CONV, ORIG]) Clone() CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Count

func (w *WrappedQuerySet[T, CONV, ORIG]) Count() (int64, error)

func (*WrappedQuerySet[T, CONV, ORIG]) Distinct

func (w *WrappedQuerySet[T, CONV, ORIG]) Distinct() CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Exists

func (w *WrappedQuerySet[T, CONV, ORIG]) Exists() (bool, error)

func (*WrappedQuerySet[T, CONV, ORIG]) ExplicitSave

func (w *WrappedQuerySet[T, CONV, ORIG]) ExplicitSave() CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Filter

func (w *WrappedQuerySet[T, CONV, ORIG]) Filter(key interface{}, vals ...interface{}) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) First

func (w *WrappedQuerySet[T, CONV, ORIG]) First() (*Row[T], error)

func (*WrappedQuerySet[T, CONV, ORIG]) ForUpdate

func (w *WrappedQuerySet[T, CONV, ORIG]) ForUpdate() CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Get

func (w *WrappedQuerySet[T, CONV, ORIG]) Get() (*Row[T], error)

func (*WrappedQuerySet[T, CONV, ORIG]) GroupBy

func (w *WrappedQuerySet[T, CONV, ORIG]) GroupBy(fields ...any) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Having

func (w *WrappedQuerySet[T, CONV, ORIG]) Having(key interface{}, vals ...interface{}) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Last

func (w *WrappedQuerySet[T, CONV, ORIG]) Last() (*Row[T], error)

func (*WrappedQuerySet[T, CONV, ORIG]) Limit

func (w *WrappedQuerySet[T, CONV, ORIG]) Limit(n int) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Offset

func (w *WrappedQuerySet[T, CONV, ORIG]) Offset(n int) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) OrderBy

func (w *WrappedQuerySet[T, CONV, ORIG]) OrderBy(fields ...string) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Prefix

func (w *WrappedQuerySet[T, CONV, ORIG]) Prefix(prefix string) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Preload

func (w *WrappedQuerySet[T, CONV, ORIG]) Preload(fields ...any) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) QueryAggregate

func (w *WrappedQuerySet[T, CONV, ORIG]) QueryAggregate() CompiledQuery[[][]interface{}]

this method is pretty much only used in subquery expressions.

func (*WrappedQuerySet[T, CONV, ORIG]) QueryAll

func (w *WrappedQuerySet[T, CONV, ORIG]) QueryAll(fields ...any) CompiledQuery[[][]interface{}]

this method is pretty much only used in subquery expressions.

func (*WrappedQuerySet[T, CONV, ORIG]) QueryCount

func (w *WrappedQuerySet[T, CONV, ORIG]) QueryCount() CompiledQuery[int64]

this method is pretty much only used in subquery expressions.

func (*WrappedQuerySet[T, CONV, ORIG]) Reverse

func (w *WrappedQuerySet[T, CONV, ORIG]) Reverse() CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Select

func (w *WrappedQuerySet[T, CONV, ORIG]) Select(fields ...any) CONV

func (*WrappedQuerySet[T, CONV, ORIG]) Values

func (w *WrappedQuerySet[T, CONV, ORIG]) Values(fields ...any) ([]map[string]any, error)

func (*WrappedQuerySet[T, CONV, ORIG]) ValuesList

func (w *WrappedQuerySet[T, CONV, ORIG]) ValuesList(fields ...any) ([][]interface{}, error)

func (*WrappedQuerySet[T, CONV, ORIG]) WithContext

func (w *WrappedQuerySet[T, CONV, ORIG]) WithContext(ctx context.Context) CONV

Directories

Path Synopsis
sql/mysql
Package mysql provides a MySQL implementation of the migrator.SchemaEditor interface.
Package mysql provides a MySQL implementation of the migrator.SchemaEditor interface.

Jump to

Keyboard shortcuts

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