database

package
v0.0.0-...-41a30da Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package database provides the seeder infrastructure for populating the database with test or production seed data.

Index

Constants

This section is empty.

Variables

View Source
var AttachmentResolver func(disk, path string) (string, error)

AttachmentResolver allows the ORM to resolve attachment URLs without depending directly on the storage package.

View Source
var (
	// DefaultRunner is the global seeder runner used by the CLI.
	DefaultRunner = NewSeederRunner()
)

Functions

func FakeAddress

func FakeAddress() string

func FakeBool

func FakeBool() bool

func FakeCompany

func FakeCompany() string

func FakeEmail

func FakeEmail() string

func FakeInt

func FakeInt(min, max int) int

func FakeName

func FakeName() string

func FakePhone

func FakePhone() string

func FakeText

func FakeText(length int) string

func InitializeEncryption

func InitializeEncryption(appKey string) error

InitializeEncryption derives the 32-byte AES key from the application key. This should be called during application startup (e.g., by the ORM provider).

func ObservePool

func ObservePool(db *sql.DB, meter metric.Meter, driverName string) error

ObservePool registers OTel metrics for a database connection pool.

func Register

func Register(seeders ...Seeder)

Register adds one or more seeders to the default global runner.

func RegisterModel

func RegisterModel[T any](meta ModelMeta)

RegisterModel manually adds metadata for a type, typically called by generated code.

func ScanIter

func ScanIter[T any](db *DB, rows Rows, meta *ModelMeta) iter.Seq2[*T, error]

ScanIter creates an iterator that scans rows into *T.

func SetAttachmentResolver

func SetAttachmentResolver(fn func(disk, path string) (string, error))

SetAttachmentResolver sets the global attachment resolver.

func TenantIDFromContext

func TenantIDFromContext(ctx context.Context) (any, bool)

TenantIDFromContext retrieves the tenant ID from the context.

func WithContext

func WithContext(ctx context.Context, db *DB) context.Context

WithContext returns a new context with the transaction DB instance attached.

func WithTenantID

func WithTenantID(ctx context.Context, tenantID any) context.Context

WithTenantID returns a new context with the tenant ID attached.

Types

type AfterCreateHook

type AfterCreateHook interface {
	AfterCreate(ctx context.Context, db *DB) error
}

type AfterDeleteHook

type AfterDeleteHook interface {
	AfterDelete(ctx context.Context, db *DB) error
}

type AfterFindHook

type AfterFindHook interface {
	AfterFind(ctx context.Context, db *DB) error
}

type AfterUpdateHook

type AfterUpdateHook interface {
	AfterUpdate(ctx context.Context, db *DB) error
}

type AuditEntry

type AuditEntry struct {
	Action    string
	Table     string
	RecordID  string
	UserID    string
	Changes   map[string]any
	Timestamp int64
}

AuditEntry represents a single change record in the audit log.

type Auditable

type Auditable interface {
	AfterCreate(ctx context.Context, db *DB, model any) error
	AfterUpdate(ctx context.Context, db *DB, model any) error
}

Auditable is an interface for models that support auditing.

type Auditor

type Auditor interface {
	Audit(ctx context.Context, entry AuditEntry) error
}

Auditor defines the interface for custom audit loggers.

type BaseRepository

type BaseRepository[T any] struct {
	DB *DB
}

BaseRepository provides a generic implementation of the Repository interface.

func NewBaseRepository

func NewBaseRepository[T any](db *DB) *BaseRepository[T]

NewBaseRepository creates a new BaseRepository for the given model type.

func (*BaseRepository[T]) Count

func (r *BaseRepository[T]) Count(ctx context.Context) (int64, error)

Count returns the total number of records.

func (*BaseRepository[T]) Create

func (r *BaseRepository[T]) Create(ctx context.Context, model *T) (*T, error)

Create inserts a new record into the database.

func (*BaseRepository[T]) Delete

func (r *BaseRepository[T]) Delete(ctx context.Context, id any) error

Delete removes a record by its primary key.

func (*BaseRepository[T]) FindAll

func (r *BaseRepository[T]) FindAll(ctx context.Context, page, perPage int) ([]T, error)

FindAll returns a slice of records, optionally paginated.

func (*BaseRepository[T]) FindByID

func (r *BaseRepository[T]) FindByID(ctx context.Context, id any) (*T, error)

FindByID returns a single record by its primary key.

func (*BaseRepository[T]) Update

func (r *BaseRepository[T]) Update(ctx context.Context, model *T) error

Update saves changes to an existing record.

type BeforeCreateHook

type BeforeCreateHook interface {
	BeforeCreate(ctx context.Context, db *DB) error
}

Lifecycle hook interfaces

type BeforeDeleteHook

type BeforeDeleteHook interface {
	BeforeDelete(ctx context.Context, db *DB) error
}

type BeforeUpdateHook

type BeforeUpdateHook interface {
	BeforeUpdate(ctx context.Context, db *DB) error
}

type BelongsTo

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

BelongsTo represents the inverse of a HasOne/HasMany.

func (*BelongsTo[T]) Get

func (r *BelongsTo[T]) Get() *T

type ColumnMeta

type ColumnMeta struct {
	FieldName  string
	ColumnName string
	FieldIndex []int // replaces uintptr Offset — safe, GC-correct
	IsPK       bool
	IsAuto     bool
	IsSoftDel  bool
	IsGuarded  bool // Mass assignment protection
	IsNullZero bool
	Type       reflect.Type
}

ColumnMeta holds metadata for a single column/field. FieldIndex is a multi-level index compatible with reflect.Value.FieldByIndex, which correctly handles embedded structs without any unsafe pointer arithmetic.

type Config

type Config struct {
	Driver             string
	DSN                string
	MaxOpen            int
	MaxIdle            int
	Lifetime           time.Duration
	SlowQueryThreshold time.Duration
	Auditor            Auditor
	// Optional OpenTelemetry tracer. When set, all queries emit spans.
	Tracer trace.Tracer
	// LogQueries enables query logging to slog (development only).
	LogQueries bool
	// QueryHook, when set, is called after every SQL statement with the query text,
	// bound arguments, and execution duration. Use this to feed the Astra Cockpit
	// SQL Timeline without importing the core package.
	QueryHook QueryHook
}

Config holds the database connection configuration.

type Connection

type Connection interface {
	Exec(ctx context.Context, sql string, args ...any) (sql.Result, error)
	Query(ctx context.Context, sql string, args ...any) (Rows, error)
	QueryRow(ctx context.Context, sql string, args ...any) Row
	Begin(ctx context.Context) (Transaction, error)
	Close() error
}

type CursorPaginated

type CursorPaginated[T any] struct {
	Data       []T    `json:"data"`
	NextCursor string `json:"next_cursor"`
	HasMore    bool   `json:"has_more"`
}

CursorPaginated represents a cursor-based paginated result set

type CustomScanner

type CustomScanner interface {
	ScanValue(src any) error
}

CustomScanner allows types to control how they are scanned from the database.

type DB

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

DB wraps a database connection

func FromContext

func FromContext(ctx context.Context) (*DB, bool)

FromContext retrieves the transaction DB instance from the context if it exists.

func MustOpen

func MustOpen(cfg Config) *DB

MustOpen calls Open and panics on error. Suitable for application startup where a database connection failure should be fatal.

func New

func New(conn Connection, dialect Dialect) *DB

func NewStandalone

func NewStandalone(cfg Config) (*DB, error)

NewStandalone establishes a database connection and returns an *DB. It is identical to Open() but explicitly documented as requiring no dependency on the engine.App framework struct. Suitable for:

  • Standard net/http projects
  • CLI tools that need ORM access
  • Microservices that want only the ORM package

func Open

func Open(cfg Config) (*DB, error)

Open establishes a database connection and returns an ORM instance

func (*DB) Begin

func (db *DB) Begin(ctx context.Context) (Transaction, error)

Begin starts a new database transaction.

func (*DB) Close

func (db *DB) Close() error

Close closes the underlying database pool.

func (*DB) Dialect

func (db *DB) Dialect() Dialect

Dialect returns the database dialect.

func (*DB) DropAllTables

func (db *DB) DropAllTables(ctx context.Context) error

DropAllTables drops all tables in the current database. It handles foreign key constraints across different dialects.

func (*DB) Exec

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

Exec executes a query without returning any rows. It automatically detects if a transaction is present in the context and uses it.

func (*DB) Pool

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

Pool returns the underlying *sql.DB connection pool.

func (*DB) Query

func (db *DB) Query(ctx context.Context, sqlStr string, args ...any) (Rows, error)

Query executes a query that returns rows. It automatically detects if a transaction is present in the context and uses it.

func (*DB) QueryRow

func (db *DB) QueryRow(ctx context.Context, sqlStr string, args ...any) Row

QueryRow executes a query that is expected to return at most one row. It automatically detects if a transaction is present in the context and uses it.

func (*DB) Schema

func (db *DB) Schema() *schema.Builder

Schema returns a schema builder

func (*DB) SetQueryHook

func (db *DB) SetQueryHook(hook QueryHook)

SetQueryHook sets a hook that is called after every query.

func (*DB) Transaction

func (db *DB) Transaction(ctx context.Context, fn func(txCtx context.Context) error) error

Transaction executes a function within a transaction. It automatically rolls back on error or panic, and commits on success. Supports nested transactions using SAVEPOINTs. The transaction-aware DB instance is injected into the context passed to fn.

func (*DB) WithTx

func (db *DB) WithTx(tx Transaction) *DB

WithTx returns a new DB that runs queries inside the provided transaction. Use with a deferred rollback pattern to ensure cleanup:

tx, err := db.Begin(ctx)
if err != nil { ... }
defer tx.Rollback()
txDB := db.WithTx(tx)
// ... use txDB ...
tx.Commit()

type Dialect

type Dialect interface {
	Name() string
	Placeholder(n int) string           // $1 (postgres) vs ? (mysql/sqlite)
	QuoteIdentifier(name string) string // "name" vs `name`
	SupportsReturning() bool
	AutoIncrementDDL() string
	LimitOffsetSQL(limit, offset int) string
	UpsertSQL(table string, columns []string, conflict string) string
	AdvisoryLock(id int64) string
	AdvisoryUnlock(id int64) string
	ConfigurePool(db *sql.DB)
}

Dialect provides database-specific SQL generation

func ResolveDialect

func ResolveDialect(driver string) (Dialect, string)

ResolveDialect returns the appropriate dialect and driver name for a given connection string.

type Encrypted

type Encrypted[T any] struct {
	Val T
}

Encrypted wraps a value with transparent crypto. Use this for sensitive PII like email, phone, or credentials.

func (*Encrypted[T]) Scan

func (e *Encrypted[T]) Scan(src any) error

Scan implements sql.Scanner interface for the ORM

func (Encrypted[T]) Value

func (e Encrypted[T]) Value() (any, error)

Value implements driver.Valuer interface (conceptually)

type FactoryBuilder

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

FactoryBuilder builds factory instances

func Factory

func Factory[T any](fn func(*FactoryDef[T])) *FactoryBuilder[T]

Factory creates a new factory for type T

func (*FactoryBuilder[T]) Create

func (fb *FactoryBuilder[T]) Create(ctx context.Context, db ...*DB) (*T, error)

Create creates and persists an instance

func (*FactoryBuilder[T]) CreateMany

func (fb *FactoryBuilder[T]) CreateMany(ctx context.Context, count int, db ...*DB) ([]*T, error)

CreateMany creates and persists multiple instances

func (*FactoryBuilder[T]) Make

func (fb *FactoryBuilder[T]) Make() T

Make creates an instance without persisting

func (*FactoryBuilder[T]) State

func (fb *FactoryBuilder[T]) State(name string) *FactoryBuilder[T]

State applies a named state to a builder

func (*FactoryBuilder[T]) WithDB

func (fb *FactoryBuilder[T]) WithDB(db *DB) *FactoryBuilder[T]

WithDB associates the factory with a database for persisting

type FactoryDef

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

FactoryDef defines how to build a model

func (*FactoryDef[T]) Set

func (f *FactoryDef[T]) Set(field string, value any)

Set sets a field value in the factory definition

func (*FactoryDef[T]) State

func (f *FactoryDef[T]) State(name string, attrs map[string]any)

State defines a named state with overrides

type HasMany

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

HasMany represents a 1-to-N relationship.

func (*HasMany[T]) All

func (r *HasMany[T]) All() []T

type HasOne

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

HasOne represents a 1-to-1 relationship.

func (*HasOne[T]) Get

func (r *HasOne[T]) Get() *T

type ManyToMany

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

ManyToMany represents a N-to-N relationship via a pivot table.

func (*ManyToMany[T]) All

func (r *ManyToMany[T]) All() []T

type Model

type Model struct {
	ID        uint       `orm:"primary_key;auto_increment" json:"id" db:"id"`
	CreatedAt time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt time.Time  `json:"updated_at" db:"updated_at"`
	DeletedAt *time.Time `orm:"soft_delete" json:"deleted_at,omitempty" db:"deleted_at"`
}

Model is a base struct for all Astra models, providing ID and Timestamps.

type ModelMeta

type ModelMeta struct {
	Type        reflect.Type
	TableName   string
	Columns     []ColumnMeta
	ColumnByCol map[string]ColumnMeta
	PK          ColumnMeta
	HasSoftDel  bool
	Relations   []RelationMeta
}

ModelMeta holds pre-computed metadata for a model.

func GetMeta

func GetMeta(t reflect.Type) *ModelMeta

GetMeta retrieves or builds metadata for a type.

type MorphMany

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

MorphMany represents a polymorphic one-to-many relation.

type MorphTo

type MorphTo struct {
	Relation[any]
	// contains filtered or unexported fields
}

MorphTo represents a polymorphic relation.

type MySQLDialect

type MySQLDialect struct{}

MySQLDialect implementation for MySQL

func (MySQLDialect) AdvisoryLock

func (d MySQLDialect) AdvisoryLock(id int64) string

func (MySQLDialect) AdvisoryUnlock

func (d MySQLDialect) AdvisoryUnlock(id int64) string

func (MySQLDialect) AutoIncrementDDL

func (d MySQLDialect) AutoIncrementDDL() string

func (MySQLDialect) ConfigurePool

func (d MySQLDialect) ConfigurePool(db *sql.DB)

func (MySQLDialect) LimitOffsetSQL

func (d MySQLDialect) LimitOffsetSQL(limit, offset int) string

func (MySQLDialect) Name

func (d MySQLDialect) Name() string

func (MySQLDialect) Placeholder

func (d MySQLDialect) Placeholder(n int) string

func (MySQLDialect) QuoteIdentifier

func (d MySQLDialect) QuoteIdentifier(name string) string

func (MySQLDialect) SupportsReturning

func (d MySQLDialect) SupportsReturning() bool

func (MySQLDialect) UpsertSQL

func (d MySQLDialect) UpsertSQL(table string, columns []string, conflict string) string

type NeonDialect

type NeonDialect struct {
	PostgresDialect
}

NeonDialect extends PostgresDialect with serverless-specific optimizations. It handles Neon's "cold start" behavior by implementing automatic retries for common network errors that occur when compute units spin up.

func (NeonDialect) ConfigurePool

func (d NeonDialect) ConfigurePool(db *sql.DB)

ConfigurePool applies Neon-specific connection pool settings. It optimizes for serverless environments by limiting total connections and reducing idle time to facilitate scale-to-zero.

func (NeonDialect) Name

func (d NeonDialect) Name() string

Name returns the name of the dialect.

type Paginated

type Paginated[T any] struct {
	Data     []T `json:"data"`
	Total    int `json:"total"`
	Page     int `json:"page"`
	PerPage  int `json:"per_page"`
	LastPage int `json:"last_page"`
}

Paginated represents a paginated result set (Legacy compatibility naming)

type PaginationResult

type PaginationResult[T any] struct {
	Data        []T               `json:"data"`
	Total       int64             `json:"total"`
	PerPage     int               `json:"per_page"`
	CurrentPage int               `json:"current_page"`
	LastPage    int               `json:"last_page"`
	From        int               `json:"from"`
	To          int               `json:"to"`
	Links       map[string]string `json:"links,omitempty"`
}

PaginationResult holds the results of a paginated query

type PostgresDialect

type PostgresDialect struct{}

PostgresDialect implementation for PostgreSQL

func (PostgresDialect) AdvisoryLock

func (d PostgresDialect) AdvisoryLock(id int64) string

func (PostgresDialect) AdvisoryUnlock

func (d PostgresDialect) AdvisoryUnlock(id int64) string

func (PostgresDialect) AutoIncrementDDL

func (d PostgresDialect) AutoIncrementDDL() string

func (PostgresDialect) ConfigurePool

func (d PostgresDialect) ConfigurePool(db *sql.DB)

func (PostgresDialect) LimitOffsetSQL

func (d PostgresDialect) LimitOffsetSQL(limit, offset int) string

func (PostgresDialect) Name

func (d PostgresDialect) Name() string

func (PostgresDialect) Placeholder

func (d PostgresDialect) Placeholder(n int) string

func (PostgresDialect) QuoteIdentifier

func (d PostgresDialect) QuoteIdentifier(name string) string

func (PostgresDialect) SupportsReturning

func (d PostgresDialect) SupportsReturning() bool

func (PostgresDialect) UpsertSQL

func (d PostgresDialect) UpsertSQL(table string, columns []string, conflict string) string

type QueryBuilder

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

QueryBuilder is a generic fluent query builder.

func NewQueryBuilder

func NewQueryBuilder[T any](db *DB) *QueryBuilder[T]

NewQueryBuilder creates a new instance for a model type.

func Query

func Query[T any](db *DB, ctx ...context.Context) *QueryBuilder[T]

Query is the public entry point for the ORM. It automatically detects if a transaction is present in the context and uses it.

func (*QueryBuilder[T]) All

func (q *QueryBuilder[T]) All(ctx ...context.Context) iter.Seq2[*T, error]

All returns an iterator over the query results. Go 1.23+ iter.Seq2 style.

func (*QueryBuilder[T]) AllSlice

func (q *QueryBuilder[T]) AllSlice(ctx ...context.Context) ([]T, error)

func (*QueryBuilder[T]) ApplyScopes

func (q *QueryBuilder[T]) ApplyScopes() *QueryBuilder[T]

ApplyScopes runs all registered scopes before SQL generation.

func (*QueryBuilder[T]) Attach

func (q *QueryBuilder[T]) Attach(relation string, ownerID uint, relatedIDs []uint, ctx ...context.Context) error

func (*QueryBuilder[T]) Chunk

func (q *QueryBuilder[T]) Chunk(size int, fn func([]T) error, ctx ...context.Context) error

Chunk processes results in batches of the given size.

func (*QueryBuilder[T]) Count

func (q *QueryBuilder[T]) Count(ctx ...context.Context) (int64, error)

func (*QueryBuilder[T]) Create

func (q *QueryBuilder[T]) Create(model *T, ctx ...context.Context) (*T, error)

func (*QueryBuilder[T]) CursorPaginate

func (q *QueryBuilder[T]) CursorPaginate(ctx context.Context, column, cursor string, perPage int) (*CursorPaginated[T], error)

CursorPaginate performs cursor-based pagination.

func (*QueryBuilder[T]) Delete

func (q *QueryBuilder[T]) Delete(ctx ...context.Context) error

func (*QueryBuilder[T]) Detach

func (q *QueryBuilder[T]) Detach(relation string, ownerID uint, relatedIDs []uint, ctx ...context.Context) error

func (*QueryBuilder[T]) Each

func (q *QueryBuilder[T]) Each(fn func(*T) error, ctx ...context.Context) error

Each iterates over each result using a callback.

func (*QueryBuilder[T]) Exists

func (q *QueryBuilder[T]) Exists(ctx ...context.Context) (bool, error)

func (*QueryBuilder[T]) FindBy

func (q *QueryBuilder[T]) FindBy(column string, value any, ctx ...context.Context) (*T, error)

func (*QueryBuilder[T]) FindByID

func (q *QueryBuilder[T]) FindByID(id any, ctx ...context.Context) (*T, error)

func (*QueryBuilder[T]) First

func (q *QueryBuilder[T]) First(ctx ...context.Context) (*T, error)

func (*QueryBuilder[T]) FirstOrCreate

func (q *QueryBuilder[T]) FirstOrCreate(attributes *T, ctx ...context.Context) (*T, bool, error)

func (*QueryBuilder[T]) ForceDelete

func (q *QueryBuilder[T]) ForceDelete(ctx ...context.Context) error

func (*QueryBuilder[T]) Get

func (q *QueryBuilder[T]) Get(ctx ...context.Context) ([]T, error)

func (*QueryBuilder[T]) GlobalScope

func (q *QueryBuilder[T]) GlobalScope(fn func(*QueryBuilder[T]) *QueryBuilder[T]) *QueryBuilder[T]

GlobalScope adds a scope that is applied to all terminal operations.

func (*QueryBuilder[T]) Last

func (q *QueryBuilder[T]) Last(ctx ...context.Context) (*T, error)

func (*QueryBuilder[T]) Limit

func (q *QueryBuilder[T]) Limit(n int) *QueryBuilder[T]

func (*QueryBuilder[T]) LockForUpdate

func (q *QueryBuilder[T]) LockForUpdate() *QueryBuilder[T]

func (*QueryBuilder[T]) Offset

func (q *QueryBuilder[T]) Offset(n int) *QueryBuilder[T]

func (*QueryBuilder[T]) OrWhere

func (q *QueryBuilder[T]) OrWhere(column, operator string, value any) *QueryBuilder[T]

func (*QueryBuilder[T]) OrderBy

func (q *QueryBuilder[T]) OrderBy(column, direction string) *QueryBuilder[T]

func (*QueryBuilder[T]) Paginate

func (q *QueryBuilder[T]) Paginate(page, perPage int, ctx ...context.Context) (*PaginationResult[T], error)

func (*QueryBuilder[T]) Pluck

func (q *QueryBuilder[T]) Pluck(column string, ctx ...context.Context) ([]any, error)

func (*QueryBuilder[T]) Restore

func (q *QueryBuilder[T]) Restore(ctx ...context.Context) error

func (*QueryBuilder[T]) Save

func (q *QueryBuilder[T]) Save(model *T, ctx ...context.Context) error

func (*QueryBuilder[T]) Scope

func (q *QueryBuilder[T]) Scope(fn func(*QueryBuilder[T]) *QueryBuilder[T]) *QueryBuilder[T]

func (*QueryBuilder[T]) Sync

func (q *QueryBuilder[T]) Sync(relation string, ownerID uint, relatedIDs []uint, ctx ...context.Context) error

func (*QueryBuilder[T]) Table

func (q *QueryBuilder[T]) Table(name string) *QueryBuilder[T]

func (*QueryBuilder[T]) ToSQL

func (q *QueryBuilder[T]) ToSQL() (string, []any)

ToSQL returns the SELECT query string and bound arguments.

func (*QueryBuilder[T]) Update

func (q *QueryBuilder[T]) Update(data map[string]any, ctx ...context.Context) error

func (*QueryBuilder[T]) Where

func (q *QueryBuilder[T]) Where(column, operator string, value any) *QueryBuilder[T]

func (*QueryBuilder[T]) WhereIn

func (q *QueryBuilder[T]) WhereIn(column string, values []any) *QueryBuilder[T]

func (*QueryBuilder[T]) WhereNotNull

func (q *QueryBuilder[T]) WhereNotNull(column string) *QueryBuilder[T]

func (*QueryBuilder[T]) WhereNull

func (q *QueryBuilder[T]) WhereNull(column string) *QueryBuilder[T]

func (*QueryBuilder[T]) WhereRaw

func (q *QueryBuilder[T]) WhereRaw(raw string, args ...any) *QueryBuilder[T]

func (*QueryBuilder[T]) With

func (q *QueryBuilder[T]) With(relations ...string) *QueryBuilder[T]

func (*QueryBuilder[T]) WithBaseURL

func (q *QueryBuilder[T]) WithBaseURL(url string) *QueryBuilder[T]

WithBaseURL sets the base URL for generating pagination links.

func (*QueryBuilder[T]) WithTrashed

func (q *QueryBuilder[T]) WithTrashed() *QueryBuilder[T]

type QueryHook

type QueryHook func(sql string, args []any, duration time.Duration)

QueryHook is called after every SQL statement with the query, bound arguments, and how long the statement took to execute. It is safe to call from multiple goroutines concurrently.

Use this hook to feed the Astra Cockpit SQL Timeline panel without importing the core package from within the ORM:

cfg.QueryHook = func(sql string, args []any, d time.Duration) {
    dashboard.TrackQuery(sql, args, d)
}

type RawQuery

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

func Raw

func Raw[T any](db *DB, sqlStr string, args ...any) *RawQuery[T]

Raw creates a raw SQL query that can be scanned into T.

func (*RawQuery[T]) All

func (r *RawQuery[T]) All(ctx ...context.Context) iter.Seq2[*T, error]

All returns an iterator over the raw query results, scanning into T.

func (*RawQuery[T]) Rows

func (r *RawQuery[T]) Rows(ctx ...context.Context) (Rows, error)

func (*RawQuery[T]) Scan

func (r *RawQuery[T]) Scan(dest any, ctx ...context.Context) error

Scan scans raw SQL rows into dest. dest must be a *[]T where T is a struct, or a *T for a single row.

func (*RawQuery[T]) ScanOne

func (r *RawQuery[T]) ScanOne(dest any, ctx ...context.Context) error

ScanOne scans the first row of a raw SQL result into a *T.

func (*RawQuery[T]) ScanSlice

func (r *RawQuery[T]) ScanSlice(dest any, ctx ...context.Context) error

ScanSlice scans raw SQL rows into a *[]T.

type Relation

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

Relation is the base for all relationship wrappers.

type RelationMeta

type RelationMeta struct {
	FieldName  string
	Type       string // "has_one", "has_many", "belongs_to", "many_to_many"
	Related    reflect.Type
	FK         string
	RelatedKey string // FK on the related side for many_to_many
	Pivot      string // pivot table name
	MorphType  string // for polymorphic relations
	MorphID    string // for polymorphic relations
}

RelationMeta holds metadata for a model relation.

type Repository

type Repository[T any] interface {
	FindByID(ctx context.Context, id any) (*T, error)
	FindAll(ctx context.Context, page, perPage int) ([]T, error)
	Create(ctx context.Context, model *T) (*T, error)
	Update(ctx context.Context, model *T) error
	Delete(ctx context.Context, id any) error
	Count(ctx context.Context) (int64, error)
}

Repository defines the standard interface for Astra repositories.

type Row

type Row interface {
	Scan(dest ...any) error
}

type Rows

type Rows interface {
	Next() bool
	Scan(dest ...any) error
	Close() error
	Err() error
	Columns() ([]string, error)
}

type SQLiteDialect

type SQLiteDialect struct{}

SQLiteDialect implementation for SQLite

func (SQLiteDialect) AdvisoryLock

func (d SQLiteDialect) AdvisoryLock(id int64) string

func (SQLiteDialect) AdvisoryUnlock

func (d SQLiteDialect) AdvisoryUnlock(id int64) string

func (SQLiteDialect) AutoIncrementDDL

func (d SQLiteDialect) AutoIncrementDDL() string

func (SQLiteDialect) ConfigurePool

func (d SQLiteDialect) ConfigurePool(db *sql.DB)

func (SQLiteDialect) LimitOffsetSQL

func (d SQLiteDialect) LimitOffsetSQL(limit, offset int) string

func (SQLiteDialect) Name

func (d SQLiteDialect) Name() string

func (SQLiteDialect) Placeholder

func (d SQLiteDialect) Placeholder(n int) string

func (SQLiteDialect) QuoteIdentifier

func (d SQLiteDialect) QuoteIdentifier(name string) string

func (SQLiteDialect) SupportsReturning

func (d SQLiteDialect) SupportsReturning() bool

func (SQLiteDialect) UpsertSQL

func (d SQLiteDialect) UpsertSQL(table string, columns []string, conflict string) string

type Seeder

type Seeder interface {
	// Name returns the unique name of this seeder (e.g. "01_users").
	Name() string
	// Run executes the seeder, inserting or upserting seed data.
	Run(ctx context.Context, db *DB) error
}

Seeder defines the interface that all seeders must implement.

type SeederRunner

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

SeederRunner manages and executes registered seeders.

func NewSeederRunner

func NewSeederRunner() *SeederRunner

NewSeederRunner creates a new SeederRunner.

func (*SeederRunner) Names

func (r *SeederRunner) Names() []string

Names returns all registered seeder names, sorted alphabetically.

func (*SeederRunner) Register

func (r *SeederRunner) Register(seeders ...Seeder)

Register adds one or more seeders to the runner in order.

func (*SeederRunner) Run

func (r *SeederRunner) Run(ctx context.Context, db *DB) error

Run executes all registered seeders in the order they were registered.

func (*SeederRunner) RunByName

func (r *SeederRunner) RunByName(ctx context.Context, db *DB, name string) error

RunByName runs a specific seeder by its registered name.

type TableNamer

type TableNamer interface {
	TableName() string
}

TableNamer allows models to specify a custom table name.

type Transaction

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

Directories

Path Synopsis
Package migrations is deprecated.
Package migrations is deprecated.

Jump to

Keyboard shortcuts

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