orm

package
v0.0.21 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

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

ErrNotFound is returned when a query expects exactly one row but finds none.

Functions

func GroupBySource

func GroupBySource[S, T comparable](pairs []JoinPair[S, T]) map[S][]T

GroupBySource groups JoinPair values by source key into a map[S][]T.

func ResolveTableName added in v0.0.7

func ResolveTableName[T any](fallback string) string

ResolveTableName returns the table name for type T. If T implements TableNamer (value or pointer receiver), that name is used; otherwise fallback is returned.

func UniqueTargets

func UniqueTargets[S, T comparable](pairs []JoinPair[S, T]) []T

UniqueTargets extracts deduplicated target values from a slice of JoinPair.

func WithClock added in v0.0.10

func WithClock(ctx context.Context, c Clock) context.Context

WithClock returns a child context carrying the given Clock. Query methods (Create, Update, Upsert) will use this Clock instead of time.Now() when auto-setting timestamp fields.

Types

type Clock added in v0.0.10

type Clock interface {
	Now() time.Time
}

Clock provides the current time. Implementations can return fixed times for deterministic testing.

type ColumnValueFunc

type ColumnValueFunc[T any] func(t *T, includesPK bool) (columns []string, values []any)

ColumnValueFunc extracts column names and their values from a *T. When includesPK is false the primary key column is excluded (for INSERT with auto-increment).

type DB

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

DB wraps *sql.DB with a Dialect and satisfies Querier.

func New

func New(db *sql.DB, d Dialect) *DB

New wraps a *sql.DB with the given Dialect.

func (*DB) Begin

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

Begin starts a transaction.

func (*DB) Close added in v0.0.3

func (db *DB) Close() error

Close closes the underlying *sql.DB.

func (*DB) Debug added in v0.0.5

func (db *DB) Debug(l Logger) *DB

Debug returns a new *DB that logs every query using the given Logger. The original DB is not modified.

func (*DB) ExecContext

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

func (*DB) QueryContext

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

func (*DB) Transaction

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

Transaction executes fn within a transaction. If fn returns nil the transaction is committed. If fn returns an error or panics the transaction is rolled back.

type Dialect

type Dialect interface {
	// Placeholder returns the bind parameter placeholder for the given
	// 1-based index. MySQL returns "?" regardless of index; PostgreSQL
	// returns "$1", "$2", etc.
	Placeholder(index int) string

	// QuoteIdent quotes an identifier (table name, column name) to safely
	// handle SQL reserved words. MySQL uses backticks; PostgreSQL uses
	// double quotes.
	QuoteIdent(name string) string

	// UseReturning reports whether INSERT should use a RETURNING clause
	// to retrieve the auto-generated primary key (PostgreSQL) rather
	// than relying on LastInsertId (MySQL).
	UseReturning() bool

	// ReturningClause returns the RETURNING clause appended to INSERT
	// statements. Returns an empty string for dialects that do not
	// support RETURNING (MySQL).
	ReturningClause(pk string) string
}

Dialect abstracts SQL differences between database engines.

var MySQL Dialect = mysqlDialect{}

MySQL is the Dialect for MySQL / MariaDB.

var PostgreSQL Dialect = postgresDialect{}

PostgreSQL is the Dialect for PostgreSQL.

type JoinConfig

type JoinConfig struct {
	TargetTable   string
	TargetColumn  string
	SourceTable   string
	SourceColumn  string
	SelectColumns []string // target table columns to SELECT with aliases (nil = no extra SELECT)
}

JoinConfig holds the metadata needed to build a JOIN clause at runtime.

type JoinPair

type JoinPair[S, T comparable] struct {
	Source S
	Target T
}

JoinPair holds a source–target pair read from a join table.

func QueryJoinTable

func QueryJoinTable[S, T comparable](
	ctx context.Context, db Querier, table, sourceCol, targetCol string, sourceIDs []S,
) ([]JoinPair[S, T], error)

QueryJoinTable reads (sourceCol, targetCol) rows from the given join table where sourceCol IN (sourceIDs). It returns a slice of JoinPair.

type Logger added in v0.0.6

type Logger interface {
	Log(ctx context.Context, query string, args ...any)
}

Logger is the interface for query logging.

type PreloaderFunc

type PreloaderFunc[T any] func(ctx context.Context, db Querier, results []T) error

PreloaderFunc executes a preload query and assigns results to the parent slice. Generated per-relation by ormgen.

type Querier

type Querier interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	// contains filtered or unexported methods
}

Querier is the common interface for DB and Tx. Generated factory functions accept this so that queries work with both.

type Query

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

Query represents a pending query against a single table. All builder methods return a new Query; the receiver is never modified.

func NewQuery

func NewQuery[T any](
	db Querier,
	table string,
	columns []string,
	pk string,
	scan ScanFunc[T],
	colValPairs ColumnValueFunc[T],
	setPK SetPKFunc[T],
) *Query[T]

NewQuery is called by generated factory functions.

func (*Query[T]) All

func (q *Query[T]) All(ctx context.Context) ([]T, error)

All executes a SELECT and returns all matching rows.

func (*Query[T]) ApplyJoin added in v0.0.15

func (q *Query[T]) ApplyJoin(name string)

func (*Query[T]) ApplyLeftJoin added in v0.0.15

func (q *Query[T]) ApplyLeftJoin(name string)

func (*Query[T]) ApplyLimit

func (q *Query[T]) ApplyLimit(n int)

func (*Query[T]) ApplyOffset

func (q *Query[T]) ApplyOffset(n int)

func (*Query[T]) ApplyOrderBy

func (q *Query[T]) ApplyOrderBy(clause string)

func (*Query[T]) ApplyPreload added in v0.0.15

func (q *Query[T]) ApplyPreload(name string)

func (*Query[T]) ApplySelect

func (q *Query[T]) ApplySelect(columns string)

func (*Query[T]) ApplyWhere

func (q *Query[T]) ApplyWhere(clause string, args []any)

func (*Query[T]) Count

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

Count returns the number of rows matching the current query conditions.

func (*Query[T]) Create

func (q *Query[T]) Create(ctx context.Context, t *T) error

Create inserts a new row. If setPK is set, the primary key is populated via RETURNING (PostgreSQL) or LastInsertId (MySQL).

func (*Query[T]) CreateAll

func (q *Query[T]) CreateAll(ctx context.Context, items []*T) error

CreateAll inserts multiple rows in a single INSERT statement. If setPK is set, primary keys are populated for each row.

func (*Query[T]) Delete

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

Delete deletes rows matching the accumulated WHERE clauses. Returns an error if no WHERE clauses are set (safety guard).

func (*Query[T]) Exists

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

Exists returns true if at least one row matches the current query conditions.

func (*Query[T]) First

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

First executes a SELECT with LIMIT 1 and returns the first row. Returns ErrNotFound if no rows match.

func (*Query[T]) Join

func (q *Query[T]) Join(name string) *Query[T]

Join adds an INNER JOIN for the named relation.

func (*Query[T]) LeftJoin

func (q *Query[T]) LeftJoin(name string) *Query[T]

LeftJoin adds a LEFT JOIN for the named relation.

func (*Query[T]) Limit

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

func (*Query[T]) Offset

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

func (*Query[T]) OrderBy

func (q *Query[T]) OrderBy(clause string) *Query[T]

func (*Query[T]) Preload

func (q *Query[T]) Preload(name string) *Query[T]

Preload registers a relation to be eagerly loaded after the main query.

func (*Query[T]) RegisterJoin

func (q *Query[T]) RegisterJoin(name string, cfg JoinConfig)

RegisterJoin registers a named join definition for use with Join/LeftJoin.

func (*Query[T]) RegisterPreloader

func (q *Query[T]) RegisterPreloader(name string, fn PreloaderFunc[T])

RegisterPreloader registers a named preloader for use with Preload.

func (*Query[T]) RegisterTimestamps added in v0.0.10

func (q *Query[T]) RegisterTimestamps(
	createdAtCols []string, setCreatedAt SetCreatedAtFunc[T],
	updatedAtCols []string, setUpdatedAt SetUpdatedAtFunc[T],
)

RegisterTimestamps configures automatic timestamp management.

func (*Query[T]) Scopes

func (q *Query[T]) Scopes(scopes ...scope.Scope) *Query[T]

Scopes applies the given scope.Scope values to the query.

func (*Query[T]) Select

func (q *Query[T]) Select(columns string) *Query[T]

func (*Query[T]) Update

func (q *Query[T]) Update(ctx context.Context, t *T) error

Update updates the row identified by the primary key of t. All non-PK columns are SET.

func (*Query[T]) Updates added in v0.0.21

func (q *Query[T]) Updates(ctx context.Context, values map[string]any) error

Updates updates specific columns by map for rows matching the accumulated WHERE clauses. Returns an error if no WHERE clauses are set (safety guard). If updatedAt columns are registered and not present in values, they are automatically added with the current time.

func (*Query[T]) Upsert

func (q *Query[T]) Upsert(ctx context.Context, t *T) error

Upsert inserts a row or updates it on primary key conflict. All non-PK columns (except createdAt) are updated on conflict. The primary key must be set on t before calling Upsert.

func (*Query[T]) Where

func (q *Query[T]) Where(clause string, args ...any) *Query[T]

type ScanFunc

type ScanFunc[T any] func(rows *sql.Rows) (T, error)

ScanFunc scans a single row into T. Generated per-type by ormgen.

type SetCreatedAtFunc added in v0.0.10

type SetCreatedAtFunc[T any] func(t *T, now time.Time)

SetCreatedAtFunc sets the createdAt timestamp on *T. The implementation should only set the field if its current value is zero. Generated per-type by ormgen; nil when no createdAt field exists.

type SetPKFunc

type SetPKFunc[T any] func(t *T, id int64)

SetPKFunc sets the auto-generated primary key on *T after INSERT. May be nil when the primary key is not auto-generated.

type SetUpdatedAtFunc added in v0.0.10

type SetUpdatedAtFunc[T any] func(t *T, now time.Time)

SetUpdatedAtFunc sets the updatedAt timestamp on *T. Generated per-type by ormgen; nil when no updatedAt field exists.

type TableNamer added in v0.0.7

type TableNamer interface {
	TableName() string
}

TableNamer can be implemented by model structs to override the auto-derived table name.

type Tx

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

Tx wraps *sql.Tx with a Dialect and satisfies Querier.

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit commits the transaction.

func (*Tx) ExecContext

func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

func (*Tx) QueryContext

func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback rolls back the transaction.

Jump to

Keyboard shortcuts

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