orm

package
v0.0.21 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound         = errors.New("record not found")
	ErrInvalidStruct    = errors.New("invalid struct type")
	ErrNoPrimaryKey     = errors.New("no primary key defined")
	ErrDuplicateKey     = errors.New("duplicate key violation")
	ErrForeignKey       = errors.New("foreign key violation")
	ErrCheckConstraint  = errors.New("check constraint violation")
	ErrNotNull          = errors.New("not null constraint violation")
	ErrConnectionFailed = errors.New("database connection failed")
	ErrTimeout          = errors.New("operation timeout")
	ErrCanceled         = errors.New("operation canceled")
)

Common errors

Functions

func GetColumnName

func GetColumnName(err error) string

func GetConstraintName

func GetConstraintName(err error) string

func IsConstraintError

func IsConstraintError(err error) bool

func IsRetryable

func IsRetryable(err error) bool

Types

type ArrayColumn

type ArrayColumn[T any] struct {
	Column[[]T]
}

ArrayColumn provides PostgreSQL array-specific operations

func (ArrayColumn[T]) ContainedBy

func (c ArrayColumn[T]) ContainedBy(values []T) Condition

func (ArrayColumn[T]) Contains

func (c ArrayColumn[T]) Contains(value T) Condition

func (ArrayColumn[T]) IsEmpty

func (c ArrayColumn[T]) IsEmpty() Condition

func (ArrayColumn[T]) IsNotEmpty

func (c ArrayColumn[T]) IsNotEmpty() Condition

func (ArrayColumn[T]) Length

func (c ArrayColumn[T]) Length() NumericColumn[int]

func (ArrayColumn[T]) Overlaps

func (c ArrayColumn[T]) Overlaps(values []T) Condition

type BelongsTo

type BelongsTo[TSource any, TTarget any, PK comparable] struct {
	// contains filtered or unexported fields
}

Relationship types with full type safety

type BoolColumn

type BoolColumn struct {
	Column[bool]
}

BoolColumn provides boolean-specific operations

func (BoolColumn) IsFalse

func (c BoolColumn) IsFalse() Condition

func (BoolColumn) IsTrue

func (c BoolColumn) IsTrue() Condition

type BulkUpdateOptions

type BulkUpdateOptions struct {
	UpdateColumns []string // Columns to update (if empty, updates all non-primary key columns)
	WhereColumns  []string // Columns to match on for WHERE clause (if empty, uses primary keys)
}

BulkUpdateOptions configures bulk update behavior

type Column

type Column[T any] struct {
	Name  string
	Table string
}

Column represents a type-safe database column reference

func (Column[T]) Asc

func (c Column[T]) Asc() string

func (Column[T]) Desc

func (c Column[T]) Desc() string

func (Column[T]) Eq

func (c Column[T]) Eq(value T) Condition

func (Column[T]) In

func (c Column[T]) In(values ...T) Condition

func (Column[T]) IsNotNull

func (c Column[T]) IsNotNull() Condition

func (Column[T]) IsNull

func (c Column[T]) IsNull() Condition

func (Column[T]) NotEq

func (c Column[T]) NotEq(value T) Condition

func (Column[T]) NotIn

func (c Column[T]) NotIn(values ...T) Condition

func (Column[T]) String

func (c Column[T]) String() string

type ColumnMetadata

type ColumnMetadata struct {
	FieldName       string              // Go struct field name
	DBName          string              // Database column name
	DBType          string              // Database type
	GoType          string              // Go type
	IsPrimaryKey    bool                // Is this a primary key?
	IsAutoGenerated bool                // Is this auto-generated (serial, default:now(), etc)?
	IsNullable      bool                // Can this be NULL?
	IsUnique        bool                // Has unique constraint?
	IsPointer       bool                // Is this a pointer field in Go struct?
	Default         string              // Default value
	Tags            map[string]string   // All dbdef tags
	Constraints     []string            // Check constraints
	ForeignKey      *ForeignKeyMetadata // Foreign key info if applicable

	// Generated accessor functions for zero-reflection field access
	GetValue func(model interface{}) interface{} // Extract field value (handles pointer dereferencing)
	IsNil    func(model interface{}) bool        // Check if pointer field is nil (only for pointer fields)
}

ColumnMetadata contains metadata for a single column

type Comparable

type Comparable interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64 |
		~string |
		time.Time
}

Comparable types that support comparison operators

type ComparableColumn

type ComparableColumn[T Comparable] struct {
	Column[T]
}

ComparableColumn provides comparison operations for comparable types

func (ComparableColumn[T]) Between

func (c ComparableColumn[T]) Between(min, max T) Condition

func (ComparableColumn[T]) Gt

func (c ComparableColumn[T]) Gt(value T) Condition

func (ComparableColumn[T]) Gte

func (c ComparableColumn[T]) Gte(value T) Condition

func (ComparableColumn[T]) Lt

func (c ComparableColumn[T]) Lt(value T) Condition

func (ComparableColumn[T]) Lte

func (c ComparableColumn[T]) Lte(value T) Condition

type Condition

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

Condition wraps squirrel conditions for type safety

func (Condition) And

func (c Condition) And(other Condition) Condition

func (Condition) Not

func (c Condition) Not() Condition

func (Condition) Or

func (c Condition) Or(other Condition) Condition

func (Condition) ToSqlizer

func (c Condition) ToSqlizer() squirrel.Sqlizer

type DBExecutor

type DBExecutor interface {
	// Query execution methods
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
	QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error)
	QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row

	// Get and Select for struct scanning
	GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error
	SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error

	// Named query support
	NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error)

	// Prepared statements
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
	PreparexContext(ctx context.Context, query string) (*sqlx.Stmt, error)
	PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error)

	// Rebind for driver-specific placeholders
	Rebind(query string) string

	// DriverName returns the driverName passed to the Open function for this DB.
	DriverName() string
}

DBExecutor represents an interface that can execute database operations. It can be satisfied by both *sqlx.DB and *sqlx.Tx, allowing repositories to work with either regular connections or transactions.

type DBWrapper

type DBWrapper interface {
	DBExecutor
	BeginTxx(ctx context.Context, opts *sql.TxOptions) (*sqlx.Tx, error)
	Close() error
	Ping() error
	PingContext(ctx context.Context) error
	Stats() sql.DBStats
}

DBWrapper provides additional database-specific operations that are only available on *sqlx.DB (not on transactions)

type Error

type Error struct {
	Op         string        // Operation that failed
	Table      string        // Table involved
	Err        error         // Underlying error
	Query      string        // SQL query (if applicable)
	Args       []interface{} // Query arguments (if applicable)
	Constraint string        // Constraint name (if applicable)
	Column     string        // Column name (if applicable)
	Retryable  bool          // Whether the operation can be retried
}

Error provides detailed error information

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ForeignKeyMetadata

type ForeignKeyMetadata struct {
	ReferencedTable  string
	ReferencedColumn string
	OnDelete         string
	OnUpdate         string
}

ForeignKeyMetadata contains foreign key information

type HasMany

type HasMany[TSource any, TTarget any, PK comparable] struct {
	// contains filtered or unexported fields
}

type HasManyThrough

type HasManyThrough[TSource any, TTarget any, TJoin any, PK comparable] struct {
	// contains filtered or unexported fields
}

type HasOne

type HasOne[TSource any, TTarget any, PK comparable] struct {
	// contains filtered or unexported fields
}

type JSONBColumn

type JSONBColumn struct {
	Column[interface{}]
}

JSONBColumn provides PostgreSQL JSONB-specific operations

func (JSONBColumn) ContainedBy

func (c JSONBColumn) ContainedBy(value interface{}) Condition

func (JSONBColumn) Contains

func (c JSONBColumn) Contains(value interface{}) Condition

func (JSONBColumn) HasAllKeys

func (c JSONBColumn) HasAllKeys(keys []string) Condition

func (JSONBColumn) HasAnyKey

func (c JSONBColumn) HasAnyKey(keys []string) Condition

func (JSONBColumn) HasKey

func (c JSONBColumn) HasKey(key string) Condition

func (JSONBColumn) Path

func (c JSONBColumn) Path(path string) JSONBColumn

func (JSONBColumn) PathText

func (c JSONBColumn) PathText(path string) StringColumn

type JSONData

type JSONData struct {
	json.RawMessage
}

func (*JSONData) Marshal

func (j *JSONData) Marshal(v interface{}) error

func (*JSONData) Scan

func (j *JSONData) Scan(value interface{}) error

func (*JSONData) String

func (j *JSONData) String() string

func (*JSONData) Unmarshal

func (j *JSONData) Unmarshal(v interface{}) error

func (*JSONData) Value

func (j *JSONData) Value() (driver.Value, error)

type JoinType

type JoinType string

JoinType represents different types of SQL joins

const (
	InnerJoin JoinType = "INNER JOIN"
	LeftJoin  JoinType = "LEFT JOIN"
	RightJoin JoinType = "RIGHT JOIN"
	FullJoin  JoinType = "FULL OUTER JOIN"
)

type MiddlewareContext

type MiddlewareContext struct {
	Operation    OperationType
	TableName    string
	Record       interface{}
	Records      interface{}
	QueryBuilder interface{} // squirrel.SelectBuilder, squirrel.InsertBuilder, etc.
	Query        string
	Args         []interface{}
	Error        error
	StartTime    time.Time
	Duration     time.Duration
	Context      context.Context
	Metadata     map[string]interface{}
}

MiddlewareContext contains information passed to middleware

type ModelMetadata

type ModelMetadata struct {
	// Basic table information
	TableName  string
	StructName string

	// Column mappings
	Columns    map[string]*ColumnMetadata // key is Go field name
	ColumnMap  map[string]string          // Go field -> DB column
	ReverseMap map[string]string          // DB column -> Go field

	// Primary keys only - other column lists are determined dynamically
	PrimaryKeys []string // DB column names

	// Relationships
	Relationships map[string]*RelationshipMetadata
}

ModelMetadata contains all the metadata needed for ORM operations This will be generated at compile time instead of parsed at runtime

type Numeric

type Numeric interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64
}

Numeric types for mathematical operations

type NumericColumn

type NumericColumn[T Numeric] struct {
	ComparableColumn[T]
}

NumericColumn provides numeric-specific operations

type OperationType

type OperationType string

OperationType represents different types of database operations

const (
	OpCreate     OperationType = "create"
	OpCreateMany OperationType = "create_many"
	OpUpdate     OperationType = "update"
	OpUpdateMany OperationType = "update_many"
	OpDelete     OperationType = "delete"
	OpUpsert     OperationType = "upsert"
	OpUpsertMany OperationType = "upsert_many"
	OpBulkUpdate OperationType = "bulk_update"
	OpFind       OperationType = "find"
	OpQuery      OperationType = "query"
)

type Query

type Query[T any] struct {
	// contains filtered or unexported fields
}

Query provides a fluent interface for building database queries with all features integrated

func (*Query[T]) Count

func (q *Query[T]) Count() (int64, error)

func (*Query[T]) Delete

func (q *Query[T]) Delete() (int64, error)

func (*Query[T]) ExecuteRaw

func (q *Query[T]) ExecuteRaw(query string, args ...interface{}) ([]T, error)

func (*Query[T]) Exists

func (q *Query[T]) Exists() (bool, error)

func (*Query[T]) Find

func (q *Query[T]) Find() ([]T, error)

func (*Query[T]) First

func (q *Query[T]) First() (*T, error)

func (*Query[T]) FullJoin

func (q *Query[T]) FullJoin(table, condition string) *Query[T]

func (*Query[T]) Include

func (q *Query[T]) Include(relationships ...string) *Query[T]

func (*Query[T]) IncludeWhere

func (q *Query[T]) IncludeWhere(relationship string, conditions ...Condition) *Query[T]

func (*Query[T]) InnerJoin

func (q *Query[T]) InnerJoin(table, condition string) *Query[T]

func (*Query[T]) Join

func (q *Query[T]) Join(joinType JoinType, table, condition string) *Query[T]

func (*Query[T]) JoinRelationship

func (q *Query[T]) JoinRelationship(relationshipName string, joinType JoinType) *Query[T]

func (*Query[T]) LeftJoin

func (q *Query[T]) LeftJoin(table, condition string) *Query[T]

func (*Query[T]) Limit

func (q *Query[T]) Limit(limit uint64) *Query[T]

func (*Query[T]) Offset

func (q *Query[T]) Offset(offset uint64) *Query[T]

func (*Query[T]) OrderBy

func (q *Query[T]) OrderBy(expressions ...string) *Query[T]

func (*Query[T]) RawJoin

func (q *Query[T]) RawJoin(joinClause string, args ...interface{}) *Query[T]

func (*Query[T]) RightJoin

func (q *Query[T]) RightJoin(table, condition string) *Query[T]

func (*Query[T]) Update added in v0.0.19

func (q *Query[T]) Update(record *T) error

func (*Query[T]) UpdateMany added in v0.0.19

func (q *Query[T]) UpdateMany(updates map[string]interface{}) (int64, error)

func (*Query[T]) Where

func (q *Query[T]) Where(condition Condition) *Query[T]

func (*Query[T]) WithTx

func (q *Query[T]) WithTx(tx *sqlx.Tx) *Query[T]

type QueryMiddleware

type QueryMiddleware func(next QueryMiddlewareFunc) QueryMiddlewareFunc

QueryMiddleware represents middleware that can see and modify query builders

type QueryMiddlewareFunc

type QueryMiddlewareFunc func(ctx *MiddlewareContext) error

QueryMiddlewareFunc represents middleware that can modify queries

type RelationshipMetadata

type RelationshipMetadata struct {
	Name       string
	Type       string // belongs_to, has_one, has_many, has_many_through
	Target     string // Target model name
	ForeignKey string // Foreign key field
	TargetKey  string // Target key field (for belongs_to)
	SourceKey  string // Source key field (for has_one/has_many)
	Through    string // Through model (for has_many_through)
	ThroughFK  string // Through foreign key
	ThroughTK  string // Through target key

	// Generated accessor functions for relationships
	SetValue func(model interface{}, value interface{}) // Set relationship value
	IsSlice  bool                                       // Whether this is a slice relationship
}

RelationshipMetadata contains relationship information

type Repository

type Repository[T any] struct {
	// contains filtered or unexported fields
}

Repository provides type-safe database operations for a specific model type

func NewRepository

func NewRepository[T any](db *sqlx.DB, metadata *ModelMetadata) (*Repository[T], error)

func NewRepositoryWithExecutor

func NewRepositoryWithExecutor[T any](executor DBExecutor, metadata *ModelMetadata) (*Repository[T], error)

func NewRepositoryWithTx

func NewRepositoryWithTx[T any](tx *sqlx.Tx, metadata *ModelMetadata) (*Repository[T], error)

func (*Repository[T]) AddMiddleware

func (r *Repository[T]) AddMiddleware(middleware QueryMiddleware)

func (*Repository[T]) BulkUpdate

func (r *Repository[T]) BulkUpdate(ctx context.Context, records []T, opts BulkUpdateOptions) (int64, error)

func (*Repository[T]) Columns

func (r *Repository[T]) Columns() []string

func (*Repository[T]) Create

func (r *Repository[T]) Create(ctx context.Context, record *T) error

func (*Repository[T]) CreateMany

func (r *Repository[T]) CreateMany(ctx context.Context, records []*T) error

func (*Repository[T]) Delete

func (r *Repository[T]) Delete(ctx context.Context, id interface{}) error

func (*Repository[T]) DeleteRecord

func (r *Repository[T]) DeleteRecord(ctx context.Context, record *T) error

func (*Repository[T]) FindByID

func (r *Repository[T]) FindByID(ctx context.Context, id interface{}) (*T, error)

func (*Repository[T]) GetTransactionManager

func (r *Repository[T]) GetTransactionManager() (*TransactionManager, error)

func (*Repository[T]) IsTransaction

func (r *Repository[T]) IsTransaction() bool

func (*Repository[T]) PrimaryKeys

func (r *Repository[T]) PrimaryKeys() []string

func (*Repository[T]) Query

func (r *Repository[T]) Query(ctx context.Context) *Query[T]

func (*Repository[T]) TableName

func (r *Repository[T]) TableName() string

func (*Repository[T]) Update

func (r *Repository[T]) Update(ctx context.Context, record *T) error

func (*Repository[T]) Upsert

func (r *Repository[T]) Upsert(ctx context.Context, record *T, opts UpsertOptions) error

func (*Repository[T]) UpsertMany

func (r *Repository[T]) UpsertMany(ctx context.Context, records []T, opts UpsertOptions) error

func (*Repository[T]) WithRelationships

func (r *Repository[T]) WithRelationships(ctx context.Context) *Query[T]

func (*Repository[T]) WithinTransaction

func (r *Repository[T]) WithinTransaction(ctx context.Context, fn func(*sqlx.Tx) error) error

type Storm

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

Storm is the main entry point for all ORM operations It holds all repositories and manages database connections

func NewStorm

func NewStorm(db *sqlx.DB) *Storm

func (*Storm) And

func (s *Storm) And(conditions ...Condition) Condition

func (*Storm) GetDB

func (s *Storm) GetDB() *sqlx.DB

func (*Storm) GetExecutor

func (s *Storm) GetExecutor() DBExecutor

func (*Storm) Not

func (s *Storm) Not(condition Condition) Condition

func (*Storm) Or

func (s *Storm) Or(conditions ...Condition) Condition

func (*Storm) WithTransaction

func (s *Storm) WithTransaction(ctx context.Context, fn func(*Storm) error) error

func (*Storm) WithTransactionOptions

func (s *Storm) WithTransactionOptions(ctx context.Context, opts *TransactionOptions, fn func(*Storm) error) error

type StringColumn

type StringColumn struct {
	Column[string]
}

StringColumn provides string-specific operations

func (StringColumn) Contains

func (c StringColumn) Contains(substring string) Condition

func (StringColumn) EndsWith

func (c StringColumn) EndsWith(suffix string) Condition

func (StringColumn) FullTextSearch added in v0.0.19

func (c StringColumn) FullTextSearch(query string) Condition

func (StringColumn) FullTextSearchLang added in v0.0.19

func (c StringColumn) FullTextSearchLang(language, query string) Condition

func (StringColumn) ILike

func (c StringColumn) ILike(pattern string) Condition

func (StringColumn) Like

func (c StringColumn) Like(pattern string) Condition

func (StringColumn) Regexp

func (c StringColumn) Regexp(pattern string) Condition

func (StringColumn) StartsWith

func (c StringColumn) StartsWith(prefix string) Condition

type Table

type Table struct {
	Name        string   `json:"name"`
	PrimaryKeys []string `json:"primary_keys"`
	Schema      string   `json:"schema,omitempty"`
}

Table provides table-level operations and metadata

func (Table) FullName

func (t Table) FullName() string

func (Table) GetPrimaryKeyColumns

func (t Table) GetPrimaryKeyColumns() []string

func (Table) HasPrimaryKey

func (t Table) HasPrimaryKey(column string) bool

func (Table) IsCompositePrimaryKey

func (t Table) IsCompositePrimaryKey() bool

type TimeColumn

type TimeColumn struct {
	ComparableColumn[time.Time]
}

TimeColumn provides time-specific operations

func (TimeColumn) After

func (c TimeColumn) After(t time.Time) Condition

func (TimeColumn) Before

func (c TimeColumn) Before(t time.Time) Condition

func (TimeColumn) LastNDays

func (c TimeColumn) LastNDays(days int) Condition

func (TimeColumn) Since

func (c TimeColumn) Since(t time.Time) Condition

func (TimeColumn) ThisMonth

func (c TimeColumn) ThisMonth() Condition

func (TimeColumn) ThisWeek

func (c TimeColumn) ThisWeek() Condition

func (TimeColumn) Today

func (c TimeColumn) Today() Condition

func (TimeColumn) Until

func (c TimeColumn) Until(t time.Time) Condition

type TransactionManager

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

TransactionManager provides utilities for managing transactions across repositories

func NewTransactionManager

func NewTransactionManager(db *sqlx.DB) *TransactionManager

func (*TransactionManager) WithTransaction

func (tm *TransactionManager) WithTransaction(ctx context.Context, fn func(*sqlx.Tx) error) error

func (*TransactionManager) WithTransactionOptions

func (tm *TransactionManager) WithTransactionOptions(ctx context.Context, opts *TransactionOptions, fn func(*sqlx.Tx) error) error

type TransactionOptions

type TransactionOptions struct {
	Isolation sql.IsolationLevel
	ReadOnly  bool
}

TransactionOptions configures transaction behavior

func DefaultTransactionOptions

func DefaultTransactionOptions() *TransactionOptions

func (*TransactionOptions) ToTxOptions

func (o *TransactionOptions) ToTxOptions() *sql.TxOptions

type UpsertOptions

type UpsertOptions struct {
	ConflictColumns []string          // Columns that define conflicts (ON CONFLICT)
	UpdateColumns   []string          // Columns to update on conflict (if empty, updates all non-conflict columns)
	UpdateExpr      map[string]string // Custom update expressions (column -> expression)
}

UpsertOptions configures upsert behavior

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents validation errors

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors represents multiple validation errors

func (ValidationErrors) Error

func (e ValidationErrors) Error() string

Jump to

Keyboard shortcuts

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