gocrud

package module
v1.0.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: BSD-2-Clause Imports: 24 Imported by: 0

README

gocrud

Package gocrud uses reflection to create CRUD operations for structs, on PostgreSQL and SQLite.

It fits applications whose data is mostly records of structs, e.g. the backend of a REST API, an internal tool or an admin panel: it creates and migrates the tables, validates and saves the objects, and gets them with filters, relations, pagination and reports, in transactions. It is not an SQL query builder: queries that do not fit, e.g. with window functions or joins of many tables, are better written as SQL, and run in the same transactions. Tables need an ID field, a number or a UUID, so tables with composite primary keys are not supported.

Documentation

Development

  • scripts/test.sh checks the formatting, and runs go vet and the tests, also of the bench module, and the tests of PostgreSQL again with the pgx driver. The tests start PostgreSQL in docker.
  • scripts/concurcheck.sh runs the tests with the race detector, and checks that no goroutines are still running after the tests of each package.
  • scripts/lint.sh runs the static analysis: golangci-lint, with the linters of .golangci.yml, which include gosec, and gosec itself, also on the tests.
  • scripts/vulncheck.sh checks the code and the dependencies for known vulnerabilities with govulncheck.
  • scripts/bench.sh runs the benchmarks of gocrud, next to the same queries written with database/sql.

The GitHub workflows run the tests, the static analysis and the vulnerability check on pull requests and on main, and Dependabot proposes updates of the dependencies and of the actions every week.

Documentation

Index

Constants

View Source
const (
	DialectPostgres = "postgres"
	DialectSQLite   = "sqlite"
)
View Source
const (
	// ViolationType is set when a value cannot be assigned to a field because of its type.
	ViolationType = "type"
	// ViolationRegExp is set when a value does not match the pattern from the field's <tagName>_regexp tag.
	ViolationRegExp = "regexp"
	// ViolationPassword is set for a condition of a filter on a password field, which cannot be used in filters.
	ViolationPassword = "password"
)
View Source
const (
	IDField = "ID"
)

Variables

View Source
var (
	// ErrInFilter is matched by the error of an OpIn condition whose value is not a slice, an array or a subquery.
	ErrInFilter = where.ErrInFilter
	// ErrMatchFilter is matched by the error of an OpMatch condition with a database that does not support it, SQLite.
	ErrMatchFilter = where.ErrMatchFilter
	// ErrRawFilter is matched by the error of a raw filter whose number of ? is not its number of values.
	ErrRawFilter = where.ErrRawFilter
	// ErrPasswordFilter is matched by the error of a raw filter or an order with a password field, e.g. .Password,
	// whose hashes it would reveal. A condition on a password field is a validation error, see ViolationPassword.
	ErrPasswordFilter = where.ErrPasswordField
)

The errors of filters that cannot be built, e.g. a raw filter with a wrong number of values.

View Source
var (
	// ErrNotStructPointer is matched by the error of an operation with an obj that is not a pointer to a struct.
	ErrNotStructPointer = structinfo.ErrNotStructPointer
	// ErrIDField is matched by the error of a struct whose first field is not ID, of type uint64 or string.
	ErrIDField = structinfo.ErrIDField
	// ErrNoColumns is matched by the error of a struct without a stored field other than ID.
	ErrNoColumns = structinfo.ErrNoColumns
	// ErrPasswordField is matched by the error of a struct with a field tagged with "pass" that is not a string.
	ErrPasswordField = structinfo.ErrPasswordField
	// ErrModificationFields is matched by the error of a struct whose CreatedBy and ModifiedBy are of different types.
	ErrModificationFields = structinfo.ErrModificationFields
	// ErrVersionField is matched by the error of a struct with more than one field tagged with "version", or with one
	// that is not an integer, and of UpdateMultiple with a value of the version field.
	ErrVersionField = structinfo.ErrVersionField
	// ErrRelation is matched by the error of a struct with a relation field that cannot be used, e.g. with a key field
	// that does not exist.
	ErrRelation = structinfo.ErrRelation
	// ErrForeignKey is matched by the error of a struct with an fk or on_delete tag that cannot be used.
	ErrForeignKey = structinfo.ErrForeignKey
	// ErrColumnType is matched by the error of a struct with an invalid type tag, e.g. type:varchar(20);, or with a field
	// of a Valuer type whose zero value is NULL, which needs a type tag, as the type of its column is not known.
	ErrColumnType = structinfo.ErrColumnType
)

The errors of structs that cannot be used, which every operation on such a struct returns, see Struct in the docs.

View Source
var ErrAggregate = errors.New("invalid aggregate")

ErrAggregate is matched by the error of Aggregate with a result struct or options that cannot be used.

View Source
var ErrAliasedColumnsMigrate = errors.New("struct with aliased column names cannot be migrated")

ErrAliasedColumnsMigrate is returned by Migrate for a struct with aliased column names, which reads from several tables.

View Source
var ErrCursor = errors.New("invalid cursor")

ErrCursor is matched by the error of Get with an After cursor that cannot be used, e.g. of another Order, or with an Offset, and of NextCursor with an Order of fields that cannot be in a cursor.

View Source
var ErrFilterPath = where.ErrRelationPath

ErrFilterPath is matched by the error of an operation with a filter on a path through a field that is not a relation field, e.g. Status.Name.

View Source
var ErrForeignKeyViolation = errors.New("foreign key violation")

ErrForeignKeyViolation is matched by the errors of queries that violate a foreign key, e.g. a save of an object that references an object that does not exist, or a delete of an object that is referenced.

View Source
var ErrInsertMultiple = errors.New("objects of different types")

ErrInsertMultiple is matched by the error of InsertMultiple with objects of different types.

View Source
var ErrInvalidID = errors.New("invalid id")

ErrInvalidID is matched by the error of an operation that gets an ID of the wrong type, e.g. a number for a struct with a UUID, or a string that is not a UUID.

View Source
var ErrInvalidOrder = errors.New("invalid order")

ErrInvalidOrder is matched by the error of Get with an Order that has a field that does not exist, a path through a field that is not a belongs-to relation, or an odd number of elements.

View Source
var ErrNotFound = errors.New("object not found")

ErrNotFound is returned by Load when there is no object with the given ID.

View Source
var ErrPreload = errors.New("invalid preload")

ErrPreload is returned when a name in the Preload option is not a relation field of the struct.

View Source
var ErrQueryMethod = errors.New("invalid query method")

ErrQueryMethod is matched by the error of an operation on a struct that has a query method, e.g. SelectQuery, with a signature other than the one that gocrud calls.

View Source
var ErrSchemaDiffers = errors.New("database schema differs from the structs")

ErrSchemaDiffers is matched by the error of CheckSchema when the tables do not match the structs.

View Source
var ErrSubquery = where.ErrSubquery

ErrSubquery is matched by the error of an operation with a filter that has a subquery that cannot be used, e.g. on a field that is not stored, or with an operator other than OpIn.

View Source
var ErrUnsupportedOption = errors.New("option not supported by the generic function, use the CRUD method instead")

ErrUnsupportedOption is returned by Get when an option that it does not support is set.

View Source
var ErrVerifyPasswords = errors.New("invalid passwords to verify")

ErrVerifyPasswords is matched by the error of VerifyPasswords without passwords, or with a field that is not a password field, which could not be verified.

View Source
var ErrVersionConflict = errors.New("version conflict")

ErrVersionConflict is matched by the error of Save of an object whose version field has another value than the stored one, as the object was changed since it was loaded, see the "version" tag.

Functions

func Aggregate

func Aggregate[T any, R any](ctx context.Context, c *CRUD, options AggregateOptions) ([]*R, error)

Aggregate returns the aggregated values of the objects of type T, e.g. their number and sums, grouped by fields, as objects of the result struct R. A field of R is tagged with one of:

  • group:<field>, e.g. group:Status, or a path through belongs-to relations, e.g. group:Customer.Country, which groups the objects by the value of the field,
  • group:<field>:<unit>, e.g. group:CreatedAt:month, which groups them by the time truncated to a day, a month or a year,
  • agg:count, the number of the objects,
  • agg:count:<field>, the number of the objects in which the field is not NULL,
  • agg:sum:<field>, agg:avg:<field>, agg:min:<field> or agg:max:<field>.

Without group fields, the result is one object with the values of all the objects. A field that is not a pointer gets the zero value instead of NULL, e.g. the sum of the values that are all NULL, except for times.

func CreateTable

func CreateTable[T any](ctx context.Context, c *CRUD) error

CreateTable creates the table for objects of type T, if it does not exist.

func DeleteMultiple

func DeleteMultiple[T any](ctx context.Context, c *CRUD, options DeleteMultipleOptions) ([]any, error)

DeleteMultiple deletes all the objects of type T that match the options, and returns their IDs, of the type of the ID field.

func DropTable

func DropTable[T any](ctx context.Context, c *CRUD) error

DropTable drops the table for objects of type T, if it exists.

func Get

func Get[T any](ctx context.Context, c *CRUD, options GetOptions) ([]*T, error)

Get returns the objects of type T that match the options. T is a struct type, e.g. Get[User]. RowObjTransformFunc is not supported, use CRUD.Get for it.

func GetCount

func GetCount[T any](ctx context.Context, c *CRUD, options GetCountOptions) (uint64, error)

GetCount returns the number of objects of type T that match the options.

func InsertMultiple

func InsertMultiple[T any](ctx context.Context, c *CRUD, objs []*T, options InsertMultipleOptions) error

InsertMultiple inserts the new objects of type T, see CRUD.InsertMultiple.

func Load

func Load[T any](ctx context.Context, c *CRUD, id any, preload ...string) (*T, error)

Load returns the object of type T with the given ID, or ErrNotFound when there is no such object. The related objects of the relation fields named in preload are loaded as well. The ID is a non-negative integer for an ID of type uint64, and a UUID for a string ID.

func MigrationSQL

func MigrationSQL(migrations ...*Migration) string

MigrationSQL returns the statements of the migrations as an SQL script, e.g. for the file of a migration tool. The differences, which have to be resolved by hand, are added as comments. Migrations without statements and differences are left out, so an empty string means that the tables match the structs.

func ObjIDIsZero

func ObjIDIsZero(obj any) bool

ObjIDIsZero checks if the ID of obj is not set, i.e. 0 or an empty string, as in an object that is not saved.

func ObjIDValue

func ObjIDValue(obj any) any

ObjIDValue returns the ID of obj: a uint64, or a string with a UUID.

func ObjSetIDValue

func ObjSetIDValue(obj any, id any) error

ObjSetIDValue sets the ID of obj. For an ID of type uint64, id is a non-negative integer or a decimal string, and for a string ID, a UUID. nil clears the ID, so that the object is inserted as a new one. Otherwise, it returns an error that matches ErrInvalidID.

func UpdateMultiple

func UpdateMultiple[T any](ctx context.Context, c *CRUD, values map[string]any, options UpdateMultipleOptions) error

UpdateMultiple sets the fields named in values of all the objects of type T that match the options.

func Validate

func Validate(obj any, restrictFields map[string]bool, tagName string) (bool, map[string]string, error)

Validate validates obj field values against their go-playground `validate` tags and their <tagName>_regexp tags. If restrictFields is not empty, only the listed fields are validated. Violations map field names to the name of the failed validation tag, eg. "required" or "min".

func ValidateValues

func ValidateValues(obj any, values map[string]any, tagName string) (bool, map[string]string, error)

ValidateValues validates values as if they were set on obj fields, without modifying obj. Only the fields present in values are validated.

Types

type AggregateOptions

type AggregateOptions struct {
	// Filters select the objects that are aggregated, as in Get.
	Filters sqlfilters.Filter
	// Having selects the results, by the fields of the result struct, e.g. Revenue > 1000.
	Having sqlfilters.Filter
	// Order is a list of fields of the result struct and directions, e.g. []string{"Revenue", "desc"}.
	Order  []string
	Limit  int
	Offset int
}

AggregateOptions are the options of Aggregate.

type CRUD

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

func New

func New(db *sql.DB, options Options) *CRUD

func (*CRUD) CheckSchema

func (c *CRUD) CheckSchema(ctx context.Context, objs ...any) error

CheckSchema checks that the tables of objs match the structs: that Migrate would not change them, and would not report differences. Otherwise, it returns a *SchemaError, which matches ErrSchemaDiffers. Use it in a test, or at the start of an application, when the tables are changed by a migration tool instead of Migrate.

func (*CRUD) CreateTable

func (c *CRUD) CreateTable(ctx context.Context, obj any) error

CreateTable creates a database table for the specified object, along with any indexes declared via 'idx'/'uidx' struct tags.

func (*CRUD) Delete

func (c *CRUD) Delete(ctx context.Context, obj any, options DeleteOptions) error

Delete deletes the object with the ID of obj, and sets the fields of obj to their zero values. An object without an ID is not deleted.

func (*CRUD) DeleteMultiple

func (c *CRUD) DeleteMultiple(ctx context.Context, obj any, options DeleteMultipleOptions) ([]any, error)

DeleteMultiple removes objects from the database based on specified filters, and returns the IDs of the removed objects, of the type of the ID field. Rows of other tables that are deleted by foreign keys are not included.

func (*CRUD) DropTable

func (c *CRUD) DropTable(ctx context.Context, obj any) error

func (*CRUD) Get

func (c *CRUD) Get(ctx context.Context, newObjFunc func() any, options GetOptions) ([]any, error)

Get returns the matching objects. Their password fields are empty, see VerifyPasswords.

func (*CRUD) GetCount

func (c *CRUD) GetCount(ctx context.Context, obj any, options GetCountOptions) (uint64, error)

GetCount returns the number of the rows that match the filters.

func (*CRUD) InsertMultiple

func (c *CRUD) InsertMultiple(ctx context.Context, objs []any, options InsertMultipleOptions) (err error)

InsertMultiple inserts the new objects, all of the same type, with INSERT queries of many rows, in a transaction, so that either all of them are inserted, or none. Each object is prepared as a new object in Save: it is validated, gets a UUID for a string ID, its creation and modification fields, version 1, and its passwords are hashed. The IDs of the inserted objects are set on them, and their password fields are empty. When it fails, the objects are as they were.

func (*CRUD) Load

func (c *CRUD) Load(ctx context.Context, obj any, id any, options LoadOptions) error

Load sets obj to the object with the given ID: a non-negative integer or a decimal string for an ID of type uint64, and a UUID for a string ID. When there is no such object, all the fields of obj are set to their zero values. The password fields of obj are empty, see VerifyPasswords.

func (*CRUD) Migrate

func (c *CRUD) Migrate(ctx context.Context, obj any) (*Migration, error)

Migrate makes the table of obj match the struct, with changes that do not lose data: it creates the table when it does not exist, adds the columns of new fields, and creates new indexes. Other differences are returned in Migration.Differences. All the changes are made in a transaction.

func (*CRUD) NextCursor

func (c *CRUD) NextCursor(obj any, order []string) (string, error)

NextCursor returns the cursor of the page after obj, the last object of a page of Get with order, for GetOptions.After. The order fields cannot be nullable, JSON fields, or fields of related objects. The cursor has the values of the order fields and the ID of obj, encoded but not encrypted.

func (*CRUD) PasswordFieldsFor

func (c *CRUD) PasswordFieldsFor(obj any) []string

PasswordFieldsFor returns the names of the password fields of obj.

func (*CRUD) PlanMigration

func (c *CRUD) PlanMigration(ctx context.Context, obj any) (*Migration, error)

PlanMigration returns the changes that Migrate would make to the table of obj, without making them, e.g. to write them to a file of a migration tool. The statements are planned for the database as it is, so they have to be run in their order, and before the database changes in another way.

func (*CRUD) ReferencedTables

func (c *CRUD) ReferencedTables(obj any) ([]string, error)

ReferencedTables returns the names of the tables that the foreign keys of obj reference, without duplicates.

func (*CRUD) RelatedType

func (c *CRUD) RelatedType(obj any, field string) (reflect.Type, bool)

RelatedType returns the type of the related struct of the relation field of obj, e.g. Customer for the field Customer of an order, or Order for the field Orders of a customer. It returns false when field is not a relation field.

func (*CRUD) RunInTx

func (c *CRUD) RunInTx(ctx context.Context, fn func(tx *CRUD) error) error

RunInTx runs fn in a transaction. The transaction is committed when fn returns nil, and rolled back when fn returns an error or panics. All the queries in fn must be run using the tx CRUD passed to it. When the CRUD already runs in a transaction, fn joins that transaction instead of starting a new one.

func (*CRUD) RunInTxWithOptions

func (c *CRUD) RunInTxWithOptions(ctx context.Context, opts *sql.TxOptions, fn func(tx *CRUD) error) (err error)

RunInTxWithOptions is RunInTx with options, such as isolation level, for starting the transaction. The options are ignored when the CRUD already runs in a transaction.

func (*CRUD) Save

func (c *CRUD) Save(ctx context.Context, obj any, options SaveOptions) (err error)

Save takes an object, validates its field values, and saves it in the database. If ID is not present, then an INSERT will be performed. If ID is set, then an "upsert" is performed. Password fields are hashed with bcrypt. An empty password field keeps the stored password of an object that is updated, and leaves a new object without a password that can be verified. The password fields are empty after the object is saved.

func (*CRUD) TableName

func (c *CRUD) TableName(obj any) (string, error)

func (*CRUD) TimeValue

func (c *CRUD) TimeValue(t time.Time) any

TimeValue returns t in the form that the database expects in the arguments of a query. gocrud converts times itself, so it is needed only for queries run directly on the database, e.g. with Tx().ExecContext.

func (*CRUD) Tx

func (c *CRUD) Tx() *sql.Tx

Tx returns the transaction that the CRUD runs its queries in, or nil if it does not run in a transaction.

func (*CRUD) UpdateMultiple

func (c *CRUD) UpdateMultiple(ctx context.Context, obj any, fieldsToUpdate map[string]any, options UpdateMultipleOptions) error

UpdateMultiple sets the fields of fieldsToUpdate in all the rows that match the filters. The values of password fields are hashed with bcrypt, once, so the rows get the same hash. An empty password keeps the stored passwords, as in Save. fieldsToUpdate is not changed.

func (*CRUD) ValidateFilters

func (c *CRUD) ValidateFilters(obj any, filter sqlfilters.Filter) error

ValidateFilters validates the values of the conditions of a filter as if they were the values of the fields. A nil value is valid only for a nullable field, with OpEqual or OpNotEqual. The fields of related structs, e.g. Customer.Country, are validated with the tags of the related struct, and the filters of subqueries with the tags of their structs. A condition on a password field is a ViolationPassword. Raw filters are not validated.

func (*CRUD) VerifyPasswords

func (c *CRUD) VerifyPasswords(ctx context.Context, obj any, options VerifyPasswordsOptions) (bool, error)

VerifyPasswords sets obj to the object that matches the filters, e.g. the user with the e-mail of a login, and returns true when it is the only one, and all the passwords match the hashes of their fields. Otherwise, it sets the fields of obj to their zero values, and returns false. The passwords are compared also when no object or more than one matches, with a dummy hash, so that the time of VerifyPasswords does not show whether such an object exists.

func (*CRUD) WithTx

func (c *CRUD) WithTx(tx *sql.Tx) *CRUD

WithTx returns a copy of the CRUD that runs all its queries in the tx transaction. The caller is responsible for committing or rolling back the transaction.

type CRUDError

type CRUDError struct {
	Op  string
	Err error
}

CRUDError is the error of most operations. Op describes the step that failed, e.g. "database query row", for the message of the error, and can change in any version, so check the errors with errors.Is and errors.As instead, e.g. errors.Is(err, gocrud.ErrNotFound).

func (*CRUDError) Error

func (e *CRUDError) Error() string

func (*CRUDError) Unwrap

func (e *CRUDError) Unwrap() error

type DBTX

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

DBTX is the database connection that CRUD runs its queries on. It is implemented by *sql.DB, *sql.Conn and *sql.Tx.

type DeleteMultipleOptions

type DeleteMultipleOptions struct {
	Filters sqlfilters.Filter
}

type DeleteOptions

type DeleteOptions struct{}

type GetCountOptions

type GetCountOptions struct {
	Filters                  sqlfilters.Filter
	ConvertFiltersFromString bool
}

type GetOptions

type GetOptions struct {
	Order  []string
	Limit  int
	Offset int
	// After is the cursor of NextCursor: Get returns the objects after the object of the cursor, in the same Order.
	// It cannot be combined with an Offset.
	After                    string
	Filters                  sqlfilters.Filter
	RowObjTransformFunc      func(any) any
	ConvertFiltersFromString bool

	// Preload contains the names of relation fields whose related objects are loaded, e.g. []string{"Customer", "Items"}.
	Preload []string
}

type InsertMultipleOptions

type InsertMultipleOptions struct {
	// ModifiedBy is the ID of the user who inserts the objects, stored in their CreatedBy and ModifiedBy fields, as in
	// SaveOptions.
	ModifiedBy any
	// ModifiedAt is the time stored in the CreatedAt and ModifiedAt fields, or the current time when it is zero.
	ModifiedAt time.Time
}

type LoadOptions

type LoadOptions struct {
	// Preload contains the names of relation fields whose related objects are loaded, e.g. []string{"Customer", "Items"}.
	Preload []string
}

type Migration

type Migration struct {
	Table string
	// CreatedTable is set to true when the table does not exist, and is created.
	CreatedTable bool
	// AddedColumns contains the names of the columns that are added to the table.
	AddedColumns []string
	// CreatedIndexes contains the names of the indexes that are created on the table.
	CreatedIndexes []string
	// Statements contains the SQL statements that make the changes, in the order in which they are run.
	Statements []string
	// Differences describes the differences between the struct and the table that Migrate does not change,
	// because changing them could lose data: columns that are not fields of the struct, columns of a different
	// type or nullability, existing columns of uniq fields that are not unique, and indexes created by gocrud
	// that are no longer declared in the struct.
	Differences []string
}

Migration describes the changes that Migrate makes to a table, or that PlanMigration plans.

func Migrate

func Migrate[T any](ctx context.Context, c *CRUD) (*Migration, error)

Migrate makes the table of objects of type T match the struct, see CRUD.Migrate.

func PlanMigration

func PlanMigration[T any](ctx context.Context, c *CRUD) (*Migration, error)

PlanMigration returns the changes that Migrate would make to the table of objects of type T, see CRUD.PlanMigration.

type ObjectError

type ObjectError struct {
	// Index is the index of the object in the objects of InsertMultiple.
	Index int
	Err   error
}

ObjectError is the error of one of the objects of InsertMultiple, e.g. a ValidationError of its fields.

func (*ObjectError) Error

func (e *ObjectError) Error() string

func (*ObjectError) Unwrap

func (e *ObjectError) Unwrap() error

type Options

type Options struct {
	TableNamePrefix string
	TagName         string
	Dialect         string
	// GetCountOnUniq makes Save count the rows with the values of the unique fields before it saves an object, and
	// return a UniqError for a value that another row has, also when the table has no UNIQUE constraint.
	GetCountOnUniq bool
	// QueryHook is called around each query, see QueryHook.
	QueryHook QueryHook
}

type QueryEvent

type QueryEvent struct {
	// Op is the operation that runs the query, e.g. "Save", "Get" or "Migrate", or "RunInTx" for BEGIN, COMMIT and
	// ROLLBACK, and Table is the table of its struct, or empty for a transaction. They name few values, e.g. for the
	// labels of metrics, unlike Query.
	Op    string
	Table string
	Query string
	// Args are the values of the placeholders, as database/sql converts them for the driver, e.g. the value of a
	// pointer to a field, or of the Value method of a Valuer. They include the hashes of the passwords that are saved.
	Args     []any
	Duration time.Duration
	Err      error
}

type QueryHook

type QueryHook interface {
	// BeforeQuery is called before the query is sent. The context it returns is the context of the query, and of
	// AfterQuery, e.g. with the span of a trace.
	BeforeQuery(ctx context.Context, event *QueryEvent) context.Context
	// AfterQuery is called when the database has run the query, with Duration and Err of event set. For a query that
	// returns rows, it is called when the database starts returning them, before they are read, so an error that the
	// driver returns only when the rows are read is not in Err.
	AfterQuery(ctx context.Context, event *QueryEvent)
}

QueryHook is called around each query that gocrud runs, e.g. to log the queries, to find the slow ones, or to trace them. It is set in Options.QueryHook.

type QueryHookFunc

type QueryHookFunc func(ctx context.Context, event *QueryEvent)

QueryHookFunc is a QueryHook of only AfterQuery, e.g. for a log of the queries.

func (QueryHookFunc) AfterQuery

func (f QueryHookFunc) AfterQuery(ctx context.Context, event *QueryEvent)

func (QueryHookFunc) BeforeQuery

func (f QueryHookFunc) BeforeQuery(ctx context.Context, _ *QueryEvent) context.Context

type SaveOptions

type SaveOptions struct {
	// NoInsert updates the object without trying to insert it. When there is no object with the ID, Save returns an
	// error that matches ErrNotFound.
	NoInsert bool
	// ModifiedBy is the ID of the user who saves the object. It is stored in the ModifiedBy field, and in the
	// CreatedBy field when the object is created: a non-negative integer for fields of type uint64, and a string
	// for fields of type string. nil stores the zero value.
	ModifiedBy any
	// ModifiedAt is the time of the change, stored like ModifiedBy. When it is zero, the current time is used.
	ModifiedAt time.Time
}

type SchemaError

type SchemaError struct {
	Migrations []*Migration
}

SchemaError is returned by CheckSchema. It describes the tables that do not match the structs, with the changes that Migrate would make, and the differences that it would report.

func (*SchemaError) Error

func (e *SchemaError) Error() string

func (*SchemaError) Unwrap

func (e *SchemaError) Unwrap() error

type UniqError

type UniqError struct {
	// Field is the first of Fields, or the name of the constraint when it is not one that gocrud creates, e.g. a
	// constraint created by hand.
	Field string
	// Fields are the fields of the unique column or index, in its order.
	Fields []string
}

func (*UniqError) Error

func (e *UniqError) Error() string

type UpdateMultipleOptions

type UpdateMultipleOptions struct {
	Filters                 sqlfilters.Filter
	ConvertValuesFromString bool
}

type ValidationError

type ValidationError struct {
	Violations map[string]string
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

type VerifyPasswordsOptions

type VerifyPasswordsOptions struct {
	// Filters select the object, e.g. the user with the e-mail of a login, as in Get.
	Filters                  sqlfilters.Filter
	ConvertFiltersFromString bool
	// Passwords are the passwords to verify, by the names of the password fields.
	Passwords map[string]string
}

Directories

Path Synopsis
internal
dialect
Package dialect has what differs between the databases that gocrud supports, PostgreSQL and SQLite, in the SQL of the queries.
Package dialect has what differs between the databases that gocrud supports, PostgreSQL and SQLite, in the SQL of the queries.
fixtures
Package fixtures has the TestStruct struct of the tests, with the checks of its rows in the database.
Package fixtures has the TestStruct struct of the tests, with the checks of its rows in the database.
sqlbuilder/where
Package where builds the conditions of a WHERE clause from filters, for any database.
Package where builds the conditions of a WHERE clause from filters, for any database.
otelhook module
pkg
gocrudtest
Package gocrudtest has helpers for the tests of packages that use gocrud, e.g.
Package gocrudtest has helpers for the tests of packages that use gocrud, e.g.
registry
Package registry works with structs registered under keys, e.g.
Package registry works with structs registered under keys, e.g.
sqlfilters
Package sqlfilters has the filters of the operations of gocrud, e.g.
Package sqlfilters has the filters of the operations of gocrud, e.g.

Jump to

Keyboard shortcuts

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