queries

package
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2025 License: GPL-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrNoDatabase        errs.Error = "No database connection"
	ErrUnknownDriver     errs.Error = "Unknown driver"
	ErrNoTableName       errs.Error = "No table name"
	ErrNoWhereClause     errs.Error = "No where clause in query"
	ErrFieldNull         errs.Error = "Field cannot be null"
	ErrLastInsertId      errs.Error = "Last insert id is not valid"
	ErrUnsupportedLookup errs.Error = "Unsupported lookup type"

	ErrNoResults    errs.Error = "No results found"
	ErrNoRows       errs.Error = "No rows in result set"
	ErrMultipleRows errs.Error = "Multiple rows in result set"

	ErrTransactionStarted     errs.Error = "Transaction already started"
	ErrFailedStartTransaction errs.Error = "Failed to start transaction"
	ErrNoTransaction          errs.Error = "Transaction was not started"
)
View Source
const MAX_GET_RESULTS = 21

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 (
	LogQueries = true
)

Functions

func CT_GetObject

func CT_GetObject[T attrs.Definer](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[T attrs.Definer](amount, offset 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[T attrs.Definer](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 DefinerListToList added in v1.0.7

func DefinerListToList[T attrs.Definer](list []attrs.Definer) []T

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 GetObject

func GetObject[T attrs.Definer](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 ListObjects

func ListObjects[T attrs.Definer](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](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 RegisterCompiler added in v1.0.7

func RegisterCompiler(driver driver.Driver, compiler func(model attrs.Definer) QueryCompiler)

func RegisterDriver added in v1.0.2

func RegisterDriver(driver driver.Driver, database string, supportsReturning ...SupportsReturning)

RegisterDriver registers a driver with the given database name.

This is used to determine the database type when using sqlx.

If your driver is not one of: - github.com/go-sql-driver/mysql.MySQLDriver - github.com/mattn/go-sqlite3.SQLiteDriver - github.com/jackc/pgx/v5/stdlib.Driver

Then it explicitly needs to be registered here.

func RegisterLookup added in v1.0.7

func RegisterLookup(lookup string, fn func(col string, value []any) (sql string, args []any, err error), drivers ...driver.Driver)

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 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.

Types

type CountQuery added in v1.0.3

type CountQuery Query[int64]

type DB added in v1.0.7

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

type ErrorQuery added in v1.0.7

type ErrorQuery[T any] struct {
	Obj     attrs.Definer
	Compile QueryCompiler
	Err     error
}

func (*ErrorQuery[T]) Args added in v1.0.7

func (e *ErrorQuery[T]) Args() []any

func (*ErrorQuery[T]) Compiler added in v1.0.8

func (e *ErrorQuery[T]) Compiler() QueryCompiler

func (*ErrorQuery[T]) Exec added in v1.0.7

func (e *ErrorQuery[T]) Exec() (T, error)

func (*ErrorQuery[T]) Model added in v1.0.7

func (e *ErrorQuery[T]) Model() attrs.Definer

func (*ErrorQuery[T]) SQL added in v1.0.7

func (e *ErrorQuery[T]) SQL() string

type ExistsQuery added in v1.0.3

type ExistsQuery Query[bool]

type ExprGroup

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

ExprGroup

func (*ExprGroup) And

func (g *ExprGroup) And(exprs ...Expression) Expression

func (*ExprGroup) Args

func (g *ExprGroup) Args() []any

func (*ExprGroup) Clone

func (g *ExprGroup) Clone() Expression

func (*ExprGroup) IsNot

func (g *ExprGroup) IsNot() bool

func (*ExprGroup) Not

func (g *ExprGroup) Not(not bool) Expression

func (*ExprGroup) Or

func (g *ExprGroup) Or(exprs ...Expression) Expression

func (*ExprGroup) SQL

func (g *ExprGroup) SQL(sb *strings.Builder)

func (*ExprGroup) With

func (g *ExprGroup) With(d driver.Driver, m attrs.Definer, quote string) Expression

type ExprNode

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

func Expr

func Expr(field string, operation string, value ...any) *ExprNode

func Q

func Q(fieldLookup string, value ...any) *ExprNode

func (*ExprNode) And

func (e *ExprNode) And(exprs ...Expression) Expression

func (*ExprNode) Args

func (e *ExprNode) Args() []any

func (*ExprNode) Clone

func (e *ExprNode) Clone() Expression

func (*ExprNode) IsNot

func (e *ExprNode) IsNot() bool

func (*ExprNode) Not

func (e *ExprNode) Not(not bool) Expression

func (*ExprNode) Or

func (e *ExprNode) Or(exprs ...Expression) Expression

func (*ExprNode) SQL

func (e *ExprNode) SQL(sb *strings.Builder)

func (*ExprNode) With

func (e *ExprNode) With(d driver.Driver, m attrs.Definer, quote string) Expression

type Expression

type Expression interface {
	SQL(sb *strings.Builder)
	Args() []any
	IsNot() bool
	Not(b bool) Expression
	And(...Expression) Expression
	Or(...Expression) Expression
	Clone() Expression
	With(d driver.Driver, model attrs.Definer, quote string) Expression
}

func And

func And(exprs ...Expression) Expression

func Or

func Or(exprs ...Expression) Expression

type FieldInfo added in v1.0.3

type FieldInfo struct {
	SourceField attrs.Field
	Model       attrs.Definer
	Table       string
	Chain       []string
	Fields      []attrs.Field
}

func (*FieldInfo) WriteFields added in v1.0.7

func (f *FieldInfo) WriteFields(sb *strings.Builder, quote string)

type GenericQueryBuilder added in v1.0.7

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

func (*GenericQueryBuilder) BuildCountQuery added in v1.0.7

func (g *GenericQueryBuilder) BuildCountQuery(
	ctx context.Context,
	qs *QuerySet,
	where []Expression,
	joins []JoinDef,
	groupBy []FieldInfo,
	limit int,
	offset int,
) CountQuery

func (*GenericQueryBuilder) BuildCreateQuery added in v1.0.7

func (g *GenericQueryBuilder) BuildCreateQuery(
	ctx context.Context,
	qs *QuerySet,
	fields FieldInfo,
	primary attrs.Field,
	values []any,
) Query[[]interface{}]

func (*GenericQueryBuilder) BuildDeleteQuery added in v1.0.7

func (g *GenericQueryBuilder) BuildDeleteQuery(
	ctx context.Context,
	qs *QuerySet,
	where []Expression,
	joins []JoinDef,
	groupBy []FieldInfo,
) CountQuery

func (*GenericQueryBuilder) BuildSelectQuery added in v1.0.7

func (g *GenericQueryBuilder) BuildSelectQuery(
	ctx context.Context,
	qs *QuerySet,
	fields []FieldInfo,
	where []Expression,
	having []Expression,
	joins []JoinDef,
	groupBy []FieldInfo,
	orderBy []OrderBy,
	limit int,
	offset int,
	union []Union,
	forUpdate bool,
	distinct bool,
) Query[[][]interface{}]

func (*GenericQueryBuilder) BuildUpdateQuery added in v1.0.7

func (g *GenericQueryBuilder) BuildUpdateQuery(
	ctx context.Context,
	qs *QuerySet,
	fields FieldInfo,
	where []Expression,
	joins []JoinDef,
	groupBy []FieldInfo,
	values []any,
) CountQuery

func (*GenericQueryBuilder) CommitTransaction added in v1.0.7

func (g *GenericQueryBuilder) CommitTransaction() error

func (*GenericQueryBuilder) DB added in v1.0.7

func (g *GenericQueryBuilder) DB() DB

func (*GenericQueryBuilder) InTransaction added in v1.0.7

func (g *GenericQueryBuilder) InTransaction() bool

func (*GenericQueryBuilder) Quote added in v1.0.7

func (g *GenericQueryBuilder) Quote() (string, string)

func (*GenericQueryBuilder) RollbackTransaction added in v1.0.7

func (g *GenericQueryBuilder) RollbackTransaction() error

func (*GenericQueryBuilder) StartTransaction added in v1.0.7

func (g *GenericQueryBuilder) StartTransaction(ctx context.Context) (Transaction, error)

func (*GenericQueryBuilder) SupportsReturning added in v1.0.7

func (g *GenericQueryBuilder) SupportsReturning() SupportsReturning

type JoinDef added in v1.0.3

type JoinDef struct {
	Table      string
	TypeJoin   string
	ConditionA string
	Logic      string
	ConditionB string
}

type LogicalOp

type LogicalOp string
const (
	OpAnd LogicalOp = "AND"
	OpOr  LogicalOp = "OR"
)

type OrderBy added in v1.0.3

type OrderBy struct {
	Table string
	Field string
	Desc  bool
}

type Query added in v1.0.3

type Query[T1 any] interface {
	SQL() string
	Args() []any
	Model() attrs.Definer
	Exec() (T1, error)
	Compiler() QueryCompiler
}

type QueryCompiler added in v1.0.7

type QueryCompiler interface {
	// 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() DB

	// 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)

	// 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() SupportsReturning

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

	// CommitTransaction commits the current ongoing transaction.
	CommitTransaction() error

	// RollbackTransaction rolls back the current ongoing transaction.
	RollbackTransaction() error

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

	// BuildSelectQuery builds a select query with the given parameters.
	BuildSelectQuery(
		ctx context.Context,
		qs *QuerySet,
		fields []FieldInfo,
		where []Expression,
		having []Expression,
		joins []JoinDef,
		groupBy []FieldInfo,
		orderBy []OrderBy,
		limit int,
		offset int,
		union []Union,
		forUpdate bool,
		distinct bool,
	) Query[[][]interface{}]

	// BuildCountQuery builds a count query with the given parameters.
	BuildCountQuery(
		ctx context.Context,
		qs *QuerySet,
		where []Expression,
		joins []JoinDef,
		groupBy []FieldInfo,
		limit int,
		offset int,
	) CountQuery

	// BuildCreateQuery builds a create query with the given parameters.
	BuildCreateQuery(
		ctx context.Context,
		qs *QuerySet,
		fields FieldInfo,
		primary attrs.Field,
		values []any,
	) Query[[]interface{}]

	// BuildValuesListQuery builds a values list query with the given parameters.
	BuildUpdateQuery(
		ctx context.Context,
		qs *QuerySet,
		fields FieldInfo,
		where []Expression,
		joins []JoinDef,
		groupBy []FieldInfo,
		values []any,
	) CountQuery

	// BuildUpdateQuery builds an update query with the given parameters.
	BuildDeleteQuery(
		ctx context.Context,
		qs *QuerySet,
		where []Expression,
		joins []JoinDef,
		groupBy []FieldInfo,
	) CountQuery
}

func Compiler added in v1.0.7

func Compiler(model attrs.Definer) QueryCompiler

func NewGenericQueryBuilder added in v1.0.7

func NewGenericQueryBuilder(model attrs.Definer) QueryCompiler

type QueryObject added in v1.0.7

type QueryObject[T1 any] struct {
	// contains filtered or unexported fields
}

func (*QueryObject[T1]) Args added in v1.0.7

func (q *QueryObject[T1]) Args() []any

func (*QueryObject[T1]) Compiler added in v1.0.8

func (q *QueryObject[T1]) Compiler() QueryCompiler

func (*QueryObject[T1]) Exec added in v1.0.7

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

func (*QueryObject[T1]) Model added in v1.0.7

func (q *QueryObject[T1]) Model() attrs.Definer

func (*QueryObject[T1]) SQL added in v1.0.7

func (q *QueryObject[T1]) SQL() string

type QuerySet

type QuerySet struct {
	// 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 Objects

func Objects(model attrs.Definer) *QuerySet

Objects creates a new QuerySet for the given model.

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) All

func (qs *QuerySet) All() Query[[]attrs.Definer]

func (*QuerySet) Clone

func (qs *QuerySet) Clone() *QuerySet

func (*QuerySet) Compiler added in v1.0.7

func (qs *QuerySet) Compiler() QueryCompiler

func (*QuerySet) Count

func (qs *QuerySet) Count() CountQuery

func (*QuerySet) Create added in v1.0.7

func (qs *QuerySet) Create(value attrs.Definer) Query[attrs.Definer]

func (*QuerySet) DB added in v1.0.7

func (qs *QuerySet) DB() DB

func (*QuerySet) Delete added in v1.0.3

func (qs *QuerySet) Delete() CountQuery

func (*QuerySet) Distinct added in v1.0.3

func (qs *QuerySet) Distinct() *QuerySet

func (*QuerySet) Exists added in v1.0.3

func (qs *QuerySet) Exists() ExistsQuery

func (*QuerySet) ExplicitSave added in v1.0.8

func (qs *QuerySet) ExplicitSave() *QuerySet

func (*QuerySet) Filter

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

func (*QuerySet) First

func (qs *QuerySet) First() Query[attrs.Definer]

func (*QuerySet) ForUpdate

func (qs *QuerySet) ForUpdate() *QuerySet

func (*QuerySet) Get added in v1.0.7

func (qs *QuerySet) Get() Query[attrs.Definer]

func (*QuerySet) GetOrCreate added in v1.0.7

func (qs *QuerySet) GetOrCreate(value attrs.Definer) (attrs.Definer, error)

func (*QuerySet) GoString added in v1.0.8

func (qs *QuerySet) GoString() string

func (*QuerySet) GroupBy

func (qs *QuerySet) GroupBy(fields ...string) *QuerySet

func (*QuerySet) Having

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

func (*QuerySet) Last added in v1.0.3

func (qs *QuerySet) Last() Query[attrs.Definer]

func (*QuerySet) Limit

func (qs *QuerySet) Limit(n int) *QuerySet

func (*QuerySet) Model added in v1.0.7

func (qs *QuerySet) Model() attrs.Definer

func (*QuerySet) Offset

func (qs *QuerySet) Offset(n int) *QuerySet

func (*QuerySet) OrderBy

func (qs *QuerySet) OrderBy(fields ...string) *QuerySet

func (*QuerySet) Reverse added in v1.0.3

func (qs *QuerySet) Reverse() *QuerySet

func (*QuerySet) Select added in v1.0.3

func (qs *QuerySet) Select(fields ...string) *QuerySet

func (*QuerySet) String added in v1.0.8

func (w *QuerySet) String() string

func (*QuerySet) Union

func (qs *QuerySet) Union(f func(*QuerySet) *QuerySet) *QuerySet

func (*QuerySet) Update added in v1.0.3

func (qs *QuerySet) Update(value attrs.Definer) CountQuery

func (*QuerySet) ValuesList added in v1.0.3

func (qs *QuerySet) ValuesList(fields ...string) ValuesListQuery

type RawExpr added in v1.0.3

type RawExpr struct {
	Statement string
	Fields    []string
	Params    []any
	// contains filtered or unexported fields
}

RawExpr is a function expression for SQL queries. It is used to represent a function call in SQL queries.

It can be used like so:

	RawExpr{
		// Represent the SQL function call, with each %s being replaced by the corresponding field in fields.
		sql:    `SUBSTR(TRIM(%s, " "), 0, 2) = ?``,
     	// The fields to be used in the SQL function call. Each field will be replaced by the corresponding value in args.
		fields: []string{"myField"},
		// The arguments to be used in the SQL function call. Each argument will be replaced by the corresponding value in args.
		args:   []any{"ab"},
	}

func (*RawExpr) And added in v1.0.3

func (e *RawExpr) And(exprs ...Expression) Expression

func (*RawExpr) Args added in v1.0.3

func (e *RawExpr) Args() []any

func (*RawExpr) Clone added in v1.0.3

func (e *RawExpr) Clone() Expression

func (*RawExpr) IsNot added in v1.0.3

func (e *RawExpr) IsNot() bool

func (*RawExpr) Not added in v1.0.3

func (e *RawExpr) Not(not bool) Expression

func (*RawExpr) Or added in v1.0.3

func (e *RawExpr) Or(exprs ...Expression) Expression

func (*RawExpr) SQL added in v1.0.3

func (e *RawExpr) SQL(sb *strings.Builder)

func (*RawExpr) With added in v1.0.3

func (e *RawExpr) With(d driver.Driver, m attrs.Definer, quote string) Expression

type SignalSave added in v1.0.8

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

type SupportsReturning string
const (
	SupportsReturningNone         SupportsReturning = ""
	SupportsReturningLastInsertId SupportsReturning = "last_insert_id"
	SupportsReturningColumns      SupportsReturning = "columns"
)

type Transaction added in v1.0.7

type Transaction interface {
	DB
	Commit() error
	Rollback() error
}

type Union

type Union func(*QuerySet) *QuerySet

type ValuesListQuery added in v1.0.3

type ValuesListQuery Query[[][]any]

Jump to

Keyboard shortcuts

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