orm

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: May 23, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ManifestVersion           = manifest.Version
	WarningManifestStale      = manifest.WarningStale
	WarningManifestUnreadable = manifest.WarningUnreadable
)
View Source
const (
	AddTable         = migration.AddTable
	DropTable        = migration.DropTable
	AddColumn        = migration.AddColumn
	DropColumn       = migration.DropColumn
	RenameColumn     = migration.RenameColumn
	AlterColumnType  = migration.AlterColumnType
	AlterNullability = migration.AlterNullability
	AddIndex         = migration.AddIndex
	DropIndex        = migration.DropIndex
	UnsupportedStep  = migration.UnsupportedStep

	WarningMigrationUnsupported           = migration.WarningMigrationUnsupported
	WarningMigrationDropTable             = migration.WarningMigrationDropTable
	WarningMigrationDropColumn            = migration.WarningMigrationDropColumn
	WarningMigrationAddNotNullColumn      = migration.WarningMigrationAddNotNullColumn
	WarningMigrationRenameColumn          = migration.WarningMigrationRenameColumn
	WarningMigrationAlterColumnType       = migration.WarningMigrationAlterColumnType
	WarningMigrationTypeNarrowing         = migration.WarningMigrationTypeNarrowing
	WarningMigrationSetNotNull            = migration.WarningMigrationSetNotNull
	WarningMigrationAddIndexNonConcurrent = migration.WarningMigrationAddIndexNonConcurrent
	WarningMigrationDropIndex             = migration.WarningMigrationDropIndex
)
View Source
const (
	OperationSpecSelect                = operation.OperationSelect
	WarningOperationSpecPIISelected    = operation.WarningOperationPIISelected
	WarningOperationSpecRequiredFilter = operation.WarningOperationRequiredFilter
	WarningOperationSpecMissingLimit   = operation.WarningOperationMissingLimit
	WarningOperationSpecStaleManifest  = operation.WarningOperationStaleManifest
)
View Source
const (
	MySQL    = "mysql"
	Postgres = "postgres"
)

Database driver names.

View Source
const (
	OperationSelect = query.OperationSelect
	OperationInsert = query.OperationInsert
	OperationUpdate = query.OperationUpdate
	OperationDelete = query.OperationDelete
	OperationRaw    = query.OperationRaw

	RiskLow         = query.RiskLow
	RiskMedium      = query.RiskMedium
	RiskHigh        = query.RiskHigh
	RiskDestructive = query.RiskDestructive
	RiskBlocked     = query.RiskBlocked

	AnalysisPrecise     = query.AnalysisPrecise
	AnalysisPartial     = query.AnalysisPartial
	AnalysisUnsupported = query.AnalysisUnsupported

	WarningRawSQLUsed              = query.WarningRawSQLUsed
	WarningUpdateWithoutWhere      = query.WarningUpdateWithoutWhere
	WarningDeleteWithoutWhere      = query.WarningDeleteWithoutWhere
	WarningSelectStarUsed          = query.WarningSelectStarUsed
	WarningLimitMissing            = query.WarningLimitMissing
	WarningBulkUpdateDetected      = query.WarningBulkUpdateDetected
	WarningBulkDeleteDetected      = query.WarningBulkDeleteDetected
	WarningDestructiveSQL          = query.WarningDestructiveSQL
	WarningWeakPredicate           = query.WarningWeakPredicate
	WarningSuppressionExpired      = query.WarningSuppressionExpired
	WarningSuppressionNotAllowed   = query.WarningSuppressionNotAllowed
	WarningStaticReviewPartial     = query.WarningStaticReviewPartial
	WarningStaticReviewUnsupported = query.WarningStaticReviewUnsupported
	WarningTenantFilterMissing     = query.WarningTenantFilterMissing
	WarningSoftDeleteFilterMissing = query.WarningSoftDeleteFilterMissing
	WarningPIIColumnSelected       = query.WarningPIIColumnSelected
	WarningRequiredFilterMissing   = query.WarningRequiredFilterMissing

	SuppressionScopeQuery  = query.SuppressionScopeQuery
	SuppressionScopeInline = query.SuppressionScopeInline
	SuppressionScopeConfig = query.SuppressionScopeConfig

	PolicyModeWarn    = query.PolicyModeWarn
	PolicyModeEnforce = query.PolicyModeEnforce
	PolicyModeBlock   = query.PolicyModeBlock
)

Variables

View Source
var (
	ErrOperationManifestRequired        = operation.ErrManifestRequired
	ErrOperationUnsupportedOperation    = operation.ErrUnsupportedOperation
	ErrOperationModelRequired           = operation.ErrModelRequired
	ErrOperationUnknownModel            = operation.ErrUnknownModel
	ErrOperationSelectRequired          = operation.ErrSelectRequired
	ErrOperationUnknownField            = operation.ErrUnknownField
	ErrOperationForbiddenField          = operation.ErrForbiddenField
	ErrOperationInvalidFilter           = operation.ErrInvalidFilter
	ErrOperationInvalidOrder            = operation.ErrInvalidOrder
	ErrOperationRequiredFilterMissing   = operation.ErrRequiredFilterMissing
	ErrOperationPIIAccessReasonRequired = operation.ErrPIIAccessReasonRequired
	ErrOperationStaleManifest           = operation.ErrStaleManifest
)
View Source
var (
	ErrApprovalRequired       = query.ErrApprovalRequired
	ErrApprovalReasonRequired = query.ErrApprovalReasonRequired
	ErrAccessReasonRequired   = query.ErrAccessReasonRequired
	ErrBlockedOperation       = query.ErrBlockedOperation
	DefaultRiskEngine         = query.DefaultRiskEngine
)
View Source
var ErrConflict = errors.New("goquent: conflict")

ErrConflict represents an explicit optimistic-concurrency or stale-write conflict chosen by the caller.

View Source
var ErrNotFound = sql.ErrNoRows

ErrNotFound is returned by one-row read helpers when no row is available.

It aliases sql.ErrNoRows for compatibility with existing callers.

View Source
var ErrRowsAffected = errors.New("goquent: unexpected rows affected")

ErrRowsAffected reports that a write did not affect the requested number of rows.

Functions

func ApplyScopes added in v0.4.0

func ApplyScopes(q *query.Query, scopes ...Scope) *query.Query

ApplyScopes applies scopes to q in order. Nil scopes are ignored. If a scope returns nil, the current query is kept.

func DecodeJSON added in v0.6.0

func DecodeJSON[T any](src any, fallback T) (T, error)

DecodeJSON decodes a JSON/JSONB or text-JSON database value. NULL returns fallback without error.

func DeleteBy added in v0.4.0

func DeleteBy(ctx context.Context, base *query.Query, scopes ...Scope) (sql.Result, error)

DeleteBy applies scopes to base and executes a DELETE using the resulting query.

func EncodeJSON added in v0.6.0

func EncodeJSON(v any) (string, error)

EncodeJSON marshals v for JSON/JSONB or text-JSON columns.

func GetDriver added in v0.2.0

func GetDriver(name string) (sqldriver.Driver, bool)

GetDriver retrieves a registered driver.

func Insert added in v0.3.0

func Insert[T any](ctx context.Context, db *DB, v T, opts ...WriteOpt) (sql.Result, error)

Insert inserts v into its table.

func InsertMany added in v0.6.0

func InsertMany[T any](ctx context.Context, db *DB, values []T, opts ...WriteOpt) (sql.Result, error)

InsertMany inserts all values in one INSERT statement.

Empty slices return an error instead of a no-op result. Map writes require Table, and every row must provide the selected column set.

func InsertManyReturning added in v0.6.0

func InsertManyReturning[R any, T any](ctx context.Context, db *DB, values []T, opts ...WriteOpt) ([]R, error)

InsertManyReturning inserts all values and scans PostgreSQL RETURNING rows.

func InsertOnceReturning added in v0.5.3

func InsertOnceReturning[T any, V any](ctx context.Context, db *DB, v V, opts ...WriteOpt) (T, bool, error)

InsertOnceReturning inserts v once and scans the inserted or existing row.

It uses ON CONFLICT DO NOTHING RETURNING for the insert attempt. If the conflict path returns no row, it looks up the existing row by ConflictColumns or WherePK primary-key columns. Expression-only raw conflict targets need ConflictColumns or WherePK as a lookup key.

func InsertReturning added in v0.5.1

func InsertReturning[T any, V any](ctx context.Context, db *DB, v V, opts ...WriteOpt) (T, error)

InsertReturning inserts v and scans the Postgres RETURNING row into T.

func IsConflict added in v0.6.0

func IsConflict(err error) bool

IsConflict reports whether err represents an explicit write conflict.

func IsNotFound added in v0.6.0

func IsNotFound(err error) bool

IsNotFound reports whether err represents a no-row result.

func ManifestJSONSchema added in v0.5.0

func ManifestJSONSchema() ([]byte, error)

func NullString added in v0.5.3

func NullString(value string) sql.NullString

NullString returns a valid sql.NullString.

func NullStringEmpty added in v0.5.3

func NullStringEmpty(value string) sql.NullString

NullStringEmpty returns NULL when value is empty and a valid sql.NullString otherwise.

func NullStringPtr added in v0.5.3

func NullStringPtr(value *string) sql.NullString

NullStringPtr returns NULL when value is nil and a valid sql.NullString otherwise.

func OperationSpecJSONSchema added in v0.5.0

func OperationSpecJSONSchema() ([]byte, error)

func RegisterDialect added in v0.2.0

func RegisterDialect(name string, d driver.Dialect)

RegisterDialect registers a SQL dialect for a driver name.

func RegisterDriver added in v0.2.0

func RegisterDriver(name string, d sqldriver.Driver)

RegisterDriver registers a database driver.

func RegisterDriverWithDialect added in v0.2.0

func RegisterDriverWithDialect(name string, d sqldriver.Driver, dialect driver.Dialect)

RegisterDriverWithDialect registers a database driver along with its dialect.

func RegisterTablePolicy added in v0.5.0

func RegisterTablePolicy(policy TablePolicy) error

RegisterTablePolicy registers a table policy directly.

func ResetMetaCache added in v0.3.0

func ResetMetaCache()

ResetMetaCache clears cached reflection metadata. Intended for tests.

func ResetModelPolicies added in v0.5.0

func ResetModelPolicies()

ResetModelPolicies clears registered model policies. Intended for tests.

func SelectAll added in v0.3.0

func SelectAll[T any](ctx context.Context, db *DB, q string, args ...any) ([]T, error)

SelectAll runs the query and scans all rows into []T.

func SelectAllBy added in v0.4.0

func SelectAllBy[T any](ctx context.Context, db *DB, base *query.Query, scopes ...Scope) ([]T, error)

SelectAllBy builds a scoped query and scans all rows into []T.

func SelectOne added in v0.3.0

func SelectOne[T any](ctx context.Context, db *DB, q string, args ...any) (T, error)

SelectOne runs the query and scans the first row into T.

func SelectOneBy added in v0.4.0

func SelectOneBy[T any](ctx context.Context, db *DB, base *query.Query, scopes ...Scope) (T, error)

SelectOneBy builds a scoped query and scans the first row into T.

func SelectStruct deprecated added in v0.3.0

func SelectStruct[T any](ctx context.Context, db *DB, q string, args ...any) (T, error)

Deprecated: Use SelectOne instead.

func SelectStructs deprecated added in v0.3.0

func SelectStructs[T any](ctx context.Context, db *DB, q string, args ...any) ([]T, error)

Deprecated: Use SelectAll instead.

func Update added in v0.3.0

func Update[T any](ctx context.Context, db *DB, v T, opts ...WriteOpt) (sql.Result, error)

Update updates record v.

func UpdateBy added in v0.4.0

func UpdateBy(ctx context.Context, base *query.Query, data any, scopes ...Scope) (sql.Result, error)

UpdateBy applies scopes to base and executes an UPDATE using the resulting query.

func UpdateByReturning added in v0.5.1

func UpdateByReturning[T any](ctx context.Context, db *DB, base *query.Query, data any, scopes ...Scope) (T, error)

UpdateByReturning applies scopes, executes an UPDATE, and scans the Postgres RETURNING row into T.

func UpdateByReturningWithOptions added in v0.6.0

func UpdateByReturningWithOptions[T any](ctx context.Context, db *DB, base *query.Query, data any, opts []WriteOpt, scopes ...Scope) (T, error)

UpdateByReturningWithOptions applies scopes, executes an UPDATE with RETURNING, and applies write options such as NoRowsAs for guarded updates.

func UpdateReturning added in v0.5.1

func UpdateReturning[T any, V any](ctx context.Context, db *DB, v V, opts ...WriteOpt) (T, error)

UpdateReturning updates v and scans the Postgres RETURNING row into T.

func Upsert added in v0.3.0

func Upsert[T any](ctx context.Context, db *DB, v T, opts ...WriteOpt) (sql.Result, error)

Upsert inserts or updates v using primary keys.

func UpsertReturning added in v0.5.1

func UpsertReturning[T any, V any](ctx context.Context, db *DB, v V, opts ...WriteOpt) (T, error)

UpsertReturning upserts v and scans the Postgres RETURNING row into T.

func ValidateManifest added in v0.5.0

func ValidateManifest(m *Manifest) error

Types

type AnalysisPrecision added in v0.5.0

type AnalysisPrecision = query.AnalysisPrecision

type Approval added in v0.5.0

type Approval = query.Approval

type BoolScanPolicy added in v0.3.1

type BoolScanPolicy int
const (
	BoolStrict BoolScanPolicy = iota
	BoolCompat
	BoolLenient
)

func (BoolScanPolicy) String added in v0.3.1

func (p BoolScanPolicy) String() string

type ColumnRef added in v0.5.0

type ColumnRef = query.ColumnRef

type ColumnSchema added in v0.5.0

type ColumnSchema = migration.ColumnSchema

type CursorColumn added in v0.5.3

type CursorColumn = query.CursorColumn

CursorColumn describes an ordered column used by keyset cursor scopes.

func CursorAsc added in v0.5.3

func CursorAsc(name string) CursorColumn

CursorAsc returns an ascending keyset cursor column.

func CursorAscAlias added in v0.6.0

func CursorAscAlias(alias string) CursorColumn

CursorAscAlias returns an ascending selected alias cursor column.

func CursorAscExpr added in v0.6.0

func CursorAscExpr(expr string) CursorColumn

CursorAscExpr returns an ascending trusted SQL expression cursor column.

func CursorDesc added in v0.5.3

func CursorDesc(name string) CursorColumn

CursorDesc returns a descending keyset cursor column.

func CursorDescAlias added in v0.6.0

func CursorDescAlias(alias string) CursorColumn

CursorDescAlias returns a descending selected alias cursor column.

func CursorDescExpr added in v0.6.0

func CursorDescExpr(expr string) CursorColumn

CursorDescExpr returns a descending trusted SQL expression cursor column.

type DB

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

DB provides main ORM interface.

func NewDB added in v0.3.1

func NewDB(sqlDB *sql.DB, dialect driver.Dialect, opts ...Option) *DB

NewDB wraps an existing sql.DB with a dialect into DB.

func NewDBWithExecutor added in v0.6.0

func NewDBWithExecutor(exec Executor, dialect driver.Dialect, opts ...Option) *DB

NewDBWithExecutor wraps an existing sql.DB/sql.Tx-compatible executor with a dialect into DB. The returned DB does not own the executor; Close is a no-op unless the executor was created by Open/OpenWithDriver/NewDB with *sql.DB.

func NewTxDB added in v0.6.0

func NewTxDB(tx *sql.Tx, dialect driver.Dialect, opts ...Option) *DB

NewTxDB wraps an existing sql.Tx with a dialect into DB.

func Open

func Open(dsn string) (*DB, error)

Open opens a MySQL database with default pooling. Deprecated: use OpenWithDriver to specify a driver explicitly.

func OpenWithDriver added in v0.1.0

func OpenWithDriver(driverName, dsn string) (*DB, error)

OpenWithDriver opens a database with default pooling for the given driver.

func OpenWithDriverOptions added in v0.3.1

func OpenWithDriverOptions(driverName, dsn string, opts ...Option) (*DB, error)

OpenWithDriverOptions opens a database with options for the given driver.

func (*DB) Begin added in v0.0.4

func (db *DB) Begin() (Tx, error)

Begin starts a transaction for manual control.

func (*DB) BeginTx added in v0.1.2

func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (Tx, error)

BeginTx starts a transaction using ctx and returns the Tx.

func (*DB) Close

func (db *DB) Close() error

Close closes the owned underlying DB. DB values created around an external executor or transaction do not own a sql.DB, so Close is a no-op for them.

func (*DB) Exec added in v0.0.3

func (db *DB) Exec(q string, args ...any) (sql.Result, error)

Exec executes a raw SQL statement.

func (*DB) ExecContext added in v0.0.3

func (db *DB) ExecContext(ctx context.Context, q string, args ...any) (sql.Result, error)

ExecContext executes a raw SQL statement with a context.

func (*DB) Model

func (db *DB) Model(v any) *query.Query

Model creates a query for the struct table.

func (*DB) Query added in v0.0.3

func (db *DB) Query(q string, args ...any) (*sql.Rows, error)

Query runs a raw SQL query returning multiple rows.

func (*DB) QueryContext added in v0.0.3

func (db *DB) QueryContext(ctx context.Context, q string, args ...any) (*sql.Rows, error)

QueryContext runs Query with a context.

func (*DB) QueryRow deprecated added in v0.0.3

func (db *DB) QueryRow(q string, args ...any) *sql.Row

QueryRow executes a query that is expected to return at most one row.

Deprecated: use QueryRowE so raw SQL safety errors can be returned before Scan. QueryRow cannot surface pre-execution approval errors because *sql.Row has no public error constructor. When raw SQL approval checks fail, QueryRow does not execute the caller-supplied SQL.

func (*DB) QueryRowContext deprecated added in v0.0.3

func (db *DB) QueryRowContext(ctx context.Context, q string, args ...any) *sql.Row

QueryRowContext executes a query with context returning at most one row.

Deprecated: use QueryRowE so raw SQL safety errors can be returned before Scan. QueryRowContext cannot surface pre-execution approval errors because *sql.Row has no public error constructor. When raw SQL approval checks fail, QueryRowContext does not execute the caller-supplied SQL.

func (*DB) QueryRowE added in v0.5.0

func (db *DB) QueryRowE(ctx context.Context, q string, args ...any) (*sql.Row, error)

QueryRowE validates raw SQL policy and executes a context-aware single-row query.

func (*DB) RawPlan added in v0.5.0

func (db *DB) RawPlan(ctx context.Context, q string, args ...any) (*QueryPlan, error)

RawPlan creates a plan for caller-supplied SQL without executing it.

func (*DB) RequireRawApproval added in v0.5.0

func (db *DB) RequireRawApproval(reason string) *DB

RequireRawApproval returns a shallow DB copy that can execute risky raw SQL with an explicit approval reason.

func (*DB) SQLDB added in v0.0.5

func (db *DB) SQLDB() *sql.DB

SQLDB returns the underlying *sql.DB.

func (*DB) SelectMap deprecated added in v0.3.0

func (db *DB) SelectMap(ctx context.Context, q string, args ...any) (map[string]any, error)

Deprecated: Use SelectOne with map type instead.

func (*DB) SelectMaps deprecated added in v0.3.0

func (db *DB) SelectMaps(ctx context.Context, q string, args ...any) ([]map[string]any, error)

Deprecated: Use SelectAll with map type instead.

func (*DB) Table

func (db *DB) Table(name string) *query.Query

Table creates a query for table name.

func (*DB) TablePath added in v0.6.0

func (db *DB) TablePath(parts ...string) *query.Query

TablePath creates a query for a schema-qualified or otherwise path-qualified table name.

func (*DB) TouchedTables added in v0.6.0

func (db *DB) TouchedTables(tables ...string) *DB

TouchedTables returns a shallow DB copy that annotates raw SQL QueryPlans with the tables the caller reviewed.

func (*DB) Transaction

func (db *DB) Transaction(fn func(tx Tx) error) error

Transaction executes fn in a transaction.

func (*DB) TransactionContext added in v0.1.2

func (db *DB) TransactionContext(ctx context.Context, fn func(tx Tx) error) error

TransactionContext executes fn in a transaction using ctx.

func (*DB) WrapTx added in v0.6.0

func (db *DB) WrapTx(tx *sql.Tx, opts ...Option) *DB

WrapTx returns a DB copy that executes through tx while preserving this DB's dialect, scan options, and raw-SQL approval state.

type ErrBoolParse added in v0.3.1

type ErrBoolParse struct {
	Column string
	Src    any
	Policy BoolScanPolicy
}

func (ErrBoolParse) Error added in v0.3.1

func (e ErrBoolParse) Error() string

type Evidence added in v0.5.0

type Evidence = query.Evidence

type Executor added in v0.6.0

type Executor interface {
	// Query runs a SQL statement returning multiple rows.
	Query(query string, args ...any) (*sql.Rows, error)
	// QueryContext is the context-aware version of Query.
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	// QueryRow executes a query expected to return at most one row.
	QueryRow(query string, args ...any) *sql.Row
	// QueryRowContext executes a single-row query with context.
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
	// Exec runs a SQL statement that doesn't return rows.
	Exec(query string, args ...any) (sql.Result, error)
	// ExecContext runs Exec with a context.
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

Executor abstracts sql.DB, sql.Tx, and compatible transaction wrappers.

type FilterSpec added in v0.5.0

type FilterSpec = operation.FilterSpec

type IndexSchema added in v0.5.0

type IndexSchema = migration.IndexSchema

type JSONField added in v0.5.3

type JSONField[T any] struct {
	Data  T
	Valid bool
}

JSONField maps a JSON/JSONB column to a typed Go value.

A NULL database value scans to Valid=false and leaves Data as the zero value. Use OrDefault when repository code wants a stable default for nullable JSON.

func JSONNull added in v0.5.3

func JSONNull[T any]() JSONField[T]

JSONNull returns an invalid JSONField that stores as SQL NULL.

func JSONOf added in v0.5.3

func JSONOf[T any](v T) JSONField[T]

JSONOf returns a valid JSONField for v.

func (JSONField[T]) OrDefault added in v0.5.3

func (j JSONField[T]) OrDefault(def T) T

OrDefault returns Data when valid, otherwise def.

func (*JSONField[T]) Scan added in v0.5.3

func (j *JSONField[T]) Scan(src any) error

Scan implements sql.Scanner.

func (JSONField[T]) Validate added in v0.5.3

func (j JSONField[T]) Validate(fn func(T) error) error

Validate runs fn for valid JSON values.

func (JSONField[T]) Value added in v0.5.3

func (j JSONField[T]) Value() (driver.Value, error)

Value implements driver.Valuer.

type JoinRef added in v0.5.0

type JoinRef = query.JoinRef

type Manifest added in v0.5.0

type Manifest = manifest.Manifest

func GenerateManifest added in v0.5.0

func GenerateManifest(opts ManifestOptions) (*Manifest, error)

func LoadManifest added in v0.5.0

func LoadManifest(path string) (*Manifest, error)

type ManifestColumn added in v0.5.0

type ManifestColumn = manifest.Column

type ManifestFreshnessCheck added in v0.5.0

type ManifestFreshnessCheck = manifest.FreshnessCheck

type ManifestIndex added in v0.5.0

type ManifestIndex = manifest.Index

type ManifestOptions added in v0.5.0

type ManifestOptions = manifest.Options

type ManifestPolicy added in v0.5.0

type ManifestPolicy = manifest.Policy

type ManifestQueryExample added in v0.5.0

type ManifestQueryExample = manifest.QueryExample

type ManifestRelation added in v0.5.0

type ManifestRelation = manifest.Relation

type ManifestTable added in v0.5.0

type ManifestTable = manifest.Table

type ManifestVerification added in v0.5.0

type ManifestVerification = manifest.Verification

func VerifyManifest added in v0.5.0

func VerifyManifest(stored, current *Manifest) ManifestVerification

type MigrationPlan added in v0.5.0

type MigrationPlan = migration.MigrationPlan

func DiffSchemas added in v0.5.0

func DiffSchemas(current, desired Schema) *MigrationPlan

func PlanMigrationSQL added in v0.5.0

func PlanMigrationSQL(ctx context.Context, sqlText string) (*MigrationPlan, error)

func PlanMigrationSteps added in v0.5.0

func PlanMigrationSteps(steps []MigrationStep) *MigrationPlan

type MigrationStatement added in v0.5.0

type MigrationStatement = migration.MigrationStatement

type MigrationStep added in v0.5.0

type MigrationStep = migration.MigrationStep

type MigrationStepType added in v0.5.0

type MigrationStepType = migration.MigrationStepType

type Migrator added in v0.5.0

type Migrator = migration.Migrator

func NewMigrator added in v0.5.0

func NewMigrator(sqlText string) *Migrator

type ModelPolicyBuilder added in v0.5.0

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

ModelPolicyBuilder registers table policy metadata for a model/table.

func Model added in v0.5.0

func Model(v any) *ModelPolicyBuilder

Model starts a policy declaration for v's table.

func (*ModelPolicyBuilder) Err added in v0.5.0

func (b *ModelPolicyBuilder) Err() error

Err returns the last registration error.

func (*ModelPolicyBuilder) PII added in v0.5.0

func (b *ModelPolicyBuilder) PII(columns ...string) *ModelPolicyBuilder

PII marks columns as personally identifiable information.

func (*ModelPolicyBuilder) PolicyMode added in v0.5.0

func (b *ModelPolicyBuilder) PolicyMode(mode PolicyMode) *ModelPolicyBuilder

PolicyMode sets all policy modes for this model declaration.

func (*ModelPolicyBuilder) Register added in v0.5.0

func (b *ModelPolicyBuilder) Register() error

Register explicitly registers the current policy.

func (*ModelPolicyBuilder) RequiredFilter added in v0.5.0

func (b *ModelPolicyBuilder) RequiredFilter(columns ...string) *ModelPolicyBuilder

RequiredFilter requires filters on the provided columns.

func (*ModelPolicyBuilder) SoftDelete added in v0.5.0

func (b *ModelPolicyBuilder) SoftDelete(column string, mode ...PolicyMode) *ModelPolicyBuilder

SoftDelete marks column as the soft delete column.

func (*ModelPolicyBuilder) Table added in v0.5.0

Table overrides the table name for this policy declaration.

func (*ModelPolicyBuilder) TenantScoped added in v0.5.0

func (b *ModelPolicyBuilder) TenantScoped(column string, mode ...PolicyMode) *ModelPolicyBuilder

TenantScoped marks column as the tenant scope column.

type OperationOptions added in v0.5.0

type OperationOptions = operation.Options

type OperationSpec added in v0.5.0

type OperationSpec = operation.OperationSpec

type OperationType added in v0.5.0

type OperationType = query.OperationType

type Option added in v0.3.1

type Option func(*DB)

Option configures DB at creation.

func WithBoolScanPolicy added in v0.3.1

func WithBoolScanPolicy(p BoolScanPolicy) Option

WithBoolScanPolicy sets the bool scanning policy.

type OrderSpec added in v0.5.0

type OrderSpec = operation.OrderSpec

type PolicyMode added in v0.5.0

type PolicyMode = query.PolicyMode

type PredicateRef added in v0.5.0

type PredicateRef = query.PredicateRef

type QueryPlan added in v0.5.0

type QueryPlan = query.QueryPlan

func CompileOperationSpec added in v0.5.0

func CompileOperationSpec(ctx context.Context, spec OperationSpec, opts OperationOptions) (*QueryPlan, error)

type RiskConfig added in v0.5.0

type RiskConfig = query.RiskConfig

type RiskEngine added in v0.5.0

type RiskEngine = query.RiskEngine

func NewRiskEngine added in v0.5.0

func NewRiskEngine(config RiskConfig) RiskEngine

type RiskLevel added in v0.5.0

type RiskLevel = query.RiskLevel

type RiskResult added in v0.5.0

type RiskResult = query.RiskResult

type RiskRuleConfig added in v0.5.0

type RiskRuleConfig = query.RiskRuleConfig

type RowsAffectedError added in v0.6.0

type RowsAffectedError struct {
	Expected int64
	Actual   int64
	Cause    error
}

RowsAffectedError describes a failed rows-affected expectation.

func (RowsAffectedError) Error added in v0.6.0

func (e RowsAffectedError) Error() string

func (RowsAffectedError) Is added in v0.6.0

func (e RowsAffectedError) Is(target error) bool

func (RowsAffectedError) Unwrap added in v0.6.0

func (e RowsAffectedError) Unwrap() error

type ScanOptions added in v0.3.1

type ScanOptions struct {
	BoolPolicy BoolScanPolicy
}

type Schema added in v0.5.0

type Schema = migration.Schema

type Scope added in v0.4.0

type Scope func(*query.Query) *query.Query

Scope applies reusable query mutations for advanced read and write flows.

func ComposeScopes added in v0.4.0

func ComposeScopes(scopes ...Scope) Scope

ComposeScopes bundles scopes into a single reusable scope.

func CursorAfter added in v0.5.3

func CursorAfter(columns []CursorColumn, values ...any) Scope

CursorAfter adds a keyset pagination predicate after the given cursor.

func CursorBefore added in v0.5.3

func CursorBefore(columns []CursorColumn, values ...any) Scope

CursorBefore adds a keyset pagination predicate before the given cursor.

func TenantScope added in v0.5.2

func TenantScope(tenantID any, column ...string) Scope

TenantScope adds a tenant filter scope. The default column is tenant_id.

type SourceLocation added in v0.5.0

type SourceLocation = query.SourceLocation

type Suppression added in v0.5.0

type Suppression = query.Suppression

func NewSuppression added in v0.5.0

func NewSuppression(code, reason string, opts ...SuppressionOption) (Suppression, error)

func ParseInlineSuppression added in v0.5.0

func ParseInlineSuppression(comment string) (Suppression, bool, error)

type SuppressionOption added in v0.5.0

type SuppressionOption = query.SuppressionOption

func SuppressionExpiresAt added in v0.5.0

func SuppressionExpiresAt(t time.Time) SuppressionOption

func SuppressionOwner added in v0.5.0

func SuppressionOwner(owner string) SuppressionOption

type SuppressionScope added in v0.5.0

type SuppressionScope = query.SuppressionScope

type TablePolicy added in v0.5.0

type TablePolicy = query.TablePolicy

func RegisteredTablePolicies added in v0.5.0

func RegisteredTablePolicies() []TablePolicy

RegisteredTablePolicies returns all registered table policies in stable order.

type TableRef added in v0.5.0

type TableRef = query.TableRef

type TableSchema added in v0.5.0

type TableSchema = migration.TableSchema

type Tx

type Tx struct {
	*DB
	driver.Tx
}

Tx represents a transaction-scoped DB wrapper.

type Warning added in v0.5.0

type Warning = query.Warning

func ValidateOperationSpec added in v0.5.0

func ValidateOperationSpec(spec OperationSpec, opts OperationOptions) ([]Warning, error)

type WriteOpt added in v0.3.0

type WriteOpt func(*writeOptions)

WriteOpt configures write behavior.

func Columns added in v0.3.0

func Columns(cols ...string) WriteOpt

Columns limits write to specified columns.

func ConflictColumns added in v0.5.1

func ConflictColumns(cols ...string) WriteOpt

ConflictColumns sets the conflict target columns for Upsert.

func ConflictConstraint added in v0.5.1

func ConflictConstraint(name string) WriteOpt

ConflictConstraint sets a Postgres named constraint as the conflict target.

func ConflictDoNothing added in v0.5.2

func ConflictDoNothing() WriteOpt

ConflictDoNothing makes Upsert/UpsertReturning use a no-op conflict action.

func ConflictTargetRaw added in v0.5.3

func ConflictTargetRaw(target string) WriteOpt

ConflictTargetRaw sets a raw Postgres ON CONFLICT target.

Use this for expression indexes such as:

ConflictTargetRaw(`("tenant_id", COALESCE("target_node_id", '')) WHERE "active"`)

Prefer ConflictColumns, ConflictWhere, or ConflictConstraint when they can express the target.

func ConflictWhere added in v0.5.1

func ConflictWhere(predicate string) WriteOpt

ConflictWhere adds a Postgres partial-index predicate to the conflict target.

func ExpectAffected added in v0.6.0

func ExpectAffected(n int64) WriteOpt

ExpectAffected requires the write to affect exactly n rows.

func Increment added in v0.6.0

func Increment(column string, delta any) WriteOpt

Increment adds delta to column on Update or the conflict-update side of Upsert.

func NoRowsAs added in v0.6.0

func NoRowsAs(err error) WriteOpt

NoRowsAs maps a zero-row write result to err. Use ErrConflict for explicit optimistic-concurrency guards such as content_hash or version predicates.

func Omit added in v0.3.0

func Omit(cols ...string) WriteOpt

Omit excludes specified columns.

func PK added in v0.3.0

func PK(cols ...string) WriteOpt

PK specifies primary key columns for map writes.

func Returning added in v0.3.0

func Returning(cols ...string) WriteOpt

Returning specifies columns to return (Postgres only).

func SchemaName added in v0.6.0

func SchemaName(name string) WriteOpt

SchemaName sets the schema for the write table. It can be combined with Table("users") or an inferred struct table name.

func SetColumn added in v0.6.0

func SetColumn(column, sourceColumn string) WriteOpt

SetColumn assigns one column from another column.

func SetExpr added in v0.6.0

func SetExpr(column, expression string, args ...any) WriteOpt

SetExpr adds a database-side assignment with positional ? placeholders. Placeholders are rewritten for the active dialect.

func SetRaw added in v0.6.0

func SetRaw(column, expression string) WriteOpt

SetRaw adds a database-side assignment to Update or the conflict-update side of Upsert. The expression is a trusted SQL fragment and must not contain placeholders.

func Table added in v0.3.0

func Table(name string) WriteOpt

Table sets table name (required for map writes).

func TablePath added in v0.6.0

func TablePath(parts ...string) WriteOpt

TablePath sets a schema-qualified or otherwise path-qualified table name.

For example, TablePath("app", "users") renders "app"."users" on PostgreSQL and `app`.`users` on MySQL.

func UpdateColumns added in v0.5.2

func UpdateColumns(cols ...string) WriteOpt

UpdateColumns limits the conflict UPDATE side of Upsert/UpsertReturning. The insert side still uses Columns/Omit plus required conflict or primary-key columns.

func WherePK added in v0.3.0

func WherePK() WriteOpt

WherePK uses primary key columns in WHERE clause.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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