database

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package database provides database connection and session management using GORM.

Index

Constants

This section is empty.

Variables

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

ErrNotFound indicates the requested entity was not found.

View Source
var ErrUnsupportedDriver = errors.New("unsupported database driver")

ErrUnsupportedDriver indicates the database URL uses an unsupported driver.

Functions

func ApplyConditions

func ApplyConditions(db *gorm.DB, options ...repository.Option) *gorm.DB

ApplyConditions applies only WHERE conditions (no limit/offset/order) for COUNT queries.

func ApplyOptions

func ApplyOptions(db *gorm.DB, options ...repository.Option) *gorm.DB

ApplyOptions builds a store.Query from the given options and applies it to a GORM session.

func ApplySearchFilters

func ApplySearchFilters(db *gorm.DB, filters search.Filters) *gorm.DB

ApplySearchFilters adds JOINs and WHERE clauses to a GORM query based on search filters. The calling table must have a snippet_id column that stores enrichment IDs as strings; the JOINs cast snippet_id to the appropriate integer type for the dialect.

func WithTransaction

func WithTransaction(ctx context.Context, db Database, fn func(tx *gorm.DB) error) error

WithTransaction executes fn within a transaction, committing on success or rolling back on error.

func WithTransactionResult

func WithTransactionResult[T any](ctx context.Context, db Database, fn func(tx *gorm.DB) (T, error)) (T, error)

WithTransactionResult executes fn within a transaction, returning the result on success.

Types

type Database

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

Database wraps a GORM connection with lifecycle management.

func NewDatabase

func NewDatabase(ctx context.Context, url string) (Database, error)

NewDatabase creates a new Database from a connection URL. Supported URL formats: - sqlite:///path/to/file.db - postgresql://user:pass@host:port/dbname - postgres://user:pass@host:port/dbname

func NewDatabaseWithConfig

func NewDatabaseWithConfig(ctx context.Context, url string, config *gorm.Config) (Database, error)

NewDatabaseWithConfig creates a Database with custom GORM configuration.

func (Database) Close

func (d Database) Close() error

Close closes the database connection.

func (Database) ConfigurePool

func (d Database) ConfigurePool(maxOpen, maxIdle int, maxLifetime time.Duration) error

ConfigurePool sets connection pool parameters.

func (Database) GORM

func (d Database) GORM() *gorm.DB

GORM returns the underlying GORM database instance. This is useful for repositories that need direct access to the *gorm.DB.

func (Database) IsPostgres

func (d Database) IsPostgres() bool

IsPostgres returns true if the underlying database is PostgreSQL.

func (Database) IsSQLite

func (d Database) IsSQLite() bool

IsSQLite returns true if the underlying database is SQLite.

func (Database) Session

func (d Database) Session(ctx context.Context) *gorm.DB

Session returns a GORM session with the given context.

type EntityMapper

type EntityMapper[D any, E any] interface {
	ToDomain(entity E) D
	ToModel(domain D) E
}

EntityMapper defines the interface for mapping between domain and database model types.

type Filter

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

Filter represents a single query filter condition.

func NewBetweenFilter

func NewBetweenFilter(field string, low, high any) Filter

NewBetweenFilter creates a new BETWEEN Filter.

func NewFilter

func NewFilter(field string, operator FilterOperator, value any) Filter

NewFilter creates a new Filter.

func (Filter) Field

func (f Filter) Field() string

Field returns the filter field name.

func (Filter) Operator

func (f Filter) Operator() FilterOperator

Operator returns the filter operator.

func (Filter) Value

func (f Filter) Value() any

Value returns the filter value.

type FilterOperator

type FilterOperator int

FilterOperator represents SQL comparison operators.

const (
	OpEqual FilterOperator = iota
	OpNotEqual
	OpGreaterThan
	OpGreaterThanOrEqual
	OpLessThan
	OpLessThanOrEqual
	OpLike
	OpILike
	OpIn
	OpNotIn
	OpIsNull
	OpIsNotNull
	OpBetween
)

FilterOperator values.

func (FilterOperator) String

func (o FilterOperator) String() string

String returns the SQL representation of the operator.

type OrderBy

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

OrderBy represents a sort specification.

func NewOrderBy

func NewOrderBy(field string, direction SortDirection) OrderBy

NewOrderBy creates a new OrderBy.

func (OrderBy) Direction

func (o OrderBy) Direction() SortDirection

Direction returns the sort direction.

func (OrderBy) Field

func (o OrderBy) Field() string

Field returns the field name.

type PgVector

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

PgVector wraps a float64 slice for use as a PostgreSQL VECTOR column value. It implements sql.Scanner and driver.Valuer to convert between Go and the PostgreSQL text format "[1.0,2.0,3.0]".

func NewPgVector

func NewPgVector(floats []float64) PgVector

NewPgVector creates a PgVector from a float64 slice. The input is defensively copied so later mutations of the source slice have no effect.

func (PgVector) Dimension

func (v PgVector) Dimension() int

Dimension returns the number of elements in the vector.

func (PgVector) Floats

func (v PgVector) Floats() []float64

Floats returns a defensive copy of the underlying float64 slice. Returns nil if the vector was never initialized (e.g. scanned from nil).

func (*PgVector) Scan

func (v *PgVector) Scan(value any) error

Scan implements sql.Scanner. It parses the PostgreSQL vector text format "[1.0,2.0,3.0]" from either a string or []byte value.

func (PgVector) String

func (v PgVector) String() string

String returns the PostgreSQL vector literal "[1.0,2.0,3.0]".

func (PgVector) Value

func (v PgVector) Value() (driver.Value, error)

Value implements driver.Valuer. It serializes the vector to the PostgreSQL text format "[1.0,2.0,3.0]".

type Query

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

Query represents a database query with filters, ordering, and pagination.

func NewQuery

func NewQuery() Query

NewQuery creates a new empty Query.

func (Query) Apply

func (q Query) Apply(db *gorm.DB) *gorm.DB

Apply applies the query to a GORM database session.

func (Query) Equal

func (q Query) Equal(field string, value any) Query

Equal adds an equality filter.

func (Query) Filters

func (q Query) Filters() []Filter

Filters returns all filter conditions.

func (Query) GreaterThan

func (q Query) GreaterThan(field string, value any) Query

GreaterThan adds a greater-than filter.

func (Query) GreaterThanOrEqual

func (q Query) GreaterThanOrEqual(field string, value any) Query

GreaterThanOrEqual adds a greater-than-or-equal filter.

func (Query) ILike

func (q Query) ILike(field string, pattern string) Query

ILike adds a case-insensitive LIKE filter.

func (Query) In

func (q Query) In(field string, values any) Query

In adds an IN filter.

func (Query) IsNotNull

func (q Query) IsNotNull(field string) Query

IsNotNull adds an IS NOT NULL filter.

func (Query) IsNull

func (q Query) IsNull(field string) Query

IsNull adds an IS NULL filter.

func (Query) LessThan

func (q Query) LessThan(field string, value any) Query

LessThan adds a less-than filter.

func (Query) LessThanOrEqual

func (q Query) LessThanOrEqual(field string, value any) Query

LessThanOrEqual adds a less-than-or-equal filter.

func (Query) Like

func (q Query) Like(field string, pattern string) Query

Like adds a LIKE filter.

func (Query) Limit

func (q Query) Limit(limit int) Query

Limit sets the result limit.

func (Query) LimitValue

func (q Query) LimitValue() int

LimitValue returns the limit value (0 means no limit).

func (Query) NotEqual

func (q Query) NotEqual(field string, value any) Query

NotEqual adds a not-equal filter.

func (Query) NotIn

func (q Query) NotIn(field string, values any) Query

NotIn adds a NOT IN filter.

func (Query) Offset

func (q Query) Offset(offset int) Query

Offset sets the result offset.

func (Query) OffsetValue

func (q Query) OffsetValue() int

OffsetValue returns the offset value.

func (Query) Order

func (q Query) Order(field string, direction SortDirection) Query

Order adds an ordering specification.

func (Query) OrderAsc

func (q Query) OrderAsc(field string) Query

OrderAsc adds ascending ordering.

func (Query) OrderDesc

func (q Query) OrderDesc(field string) Query

OrderDesc adds descending ordering.

func (Query) Orders

func (q Query) Orders() []OrderBy

Orders returns all ordering specifications.

func (Query) Paginate

func (q Query) Paginate(page, pageSize int) Query

Paginate sets both limit and offset for pagination.

func (Query) Where

func (q Query) Where(field string, operator FilterOperator, value any) Query

Where adds a filter condition.

func (Query) WhereBetween

func (q Query) WhereBetween(field string, low, high any) Query

WhereBetween adds a BETWEEN filter.

type Repository

type Repository[D any, E any] struct {
	// contains filtered or unexported fields
}

Repository provides generic persistence operations for database entities using repository.Option-based queries.

func NewRepository

func NewRepository[D any, E any](db Database, mapper EntityMapper[D, E], label string) Repository[D, E]

NewRepository creates a new Repository.

func NewRepositoryForTable

func NewRepositoryForTable[D any, E any](db Database, mapper EntityMapper[D, E], label string, tableName string) Repository[D, E]

NewRepositoryForTable creates a Repository that targets a specific table name. GORM caches schemas by type, so dynamic TableName() methods on entities do not work when the same struct maps to multiple tables. This constructor sets a tableName that is applied via .Table() after .Model() in every operation, which GORM respects because TableExpr prevents Parse() from overriding Statement.Table.

func (Repository[D, E]) Count

func (r Repository[D, E]) Count(ctx context.Context, options ...repository.Option) (int64, error)

Count returns the number of entities matching the given options.

func (Repository[D, E]) DB

func (r Repository[D, E]) DB(ctx context.Context) *gorm.DB

DB returns a GORM session scoped to the optional dynamic table.

func (Repository[D, E]) DeleteBy

func (r Repository[D, E]) DeleteBy(ctx context.Context, options ...repository.Option) error

DeleteBy removes entities matching the given options.

func (Repository[D, E]) Exists

func (r Repository[D, E]) Exists(ctx context.Context, options ...repository.Option) (bool, error)

Exists checks if any entity matches the given options.

func (Repository[D, E]) Find

func (r Repository[D, E]) Find(ctx context.Context, options ...repository.Option) ([]D, error)

Find retrieves entities matching the given options. When no ordering is specified, results are sorted by primary key ASC to ensure deterministic output across database engines (Postgres does not guarantee row order without an explicit ORDER BY).

func (Repository[D, E]) FindOne

func (r Repository[D, E]) FindOne(ctx context.Context, options ...repository.Option) (D, error)

FindOne retrieves a single entity matching the given options.

func (Repository[D, E]) Mapper

func (r Repository[D, E]) Mapper() EntityMapper[D, E]

Mapper returns the entity mapper for external use.

func (Repository[D, E]) Table

func (r Repository[D, E]) Table() string

Table returns the dynamic table name, or empty if not set.

type SortDirection

type SortDirection int

SortDirection represents sort direction.

const (
	SortAsc SortDirection = iota
	SortDesc
)

SortDirection values.

func (SortDirection) String

func (s SortDirection) String() string

String returns the SQL representation.

type Transaction

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

Transaction wraps a GORM transaction with commit/rollback semantics.

func NewTransaction

func NewTransaction(ctx context.Context, db Database) (Transaction, error)

NewTransaction starts a new database transaction.

func (*Transaction) Commit

func (t *Transaction) Commit() error

Commit commits the transaction.

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

Rollback rolls back the transaction if not already finished.

func (Transaction) Session

func (t Transaction) Session() *gorm.DB

Session returns the transaction session for executing queries.

Jump to

Keyboard shortcuts

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