rain

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package rain provides the main entry point and typed SQL builders for Rain ORM.

Index

Constants

This section is empty.

Variables

View Source
var ErrNestedTxControlNotAllowed = errors.New("rain: nested RunInTx callbacks cannot call Commit or Rollback directly")

ErrNestedTxControlNotAllowed is returned when nested callbacks attempt to commit or roll back the outer transaction directly.

View Source
var ErrNestedTxNotSupported = errors.New("rain: nested transactions are not supported by this dialect")

ErrNestedTxNotSupported is returned when nested transactions are requested on a dialect without savepoint support.

View Source
var ErrNoConnection = errors.New("rain: no database connection configured")

ErrNoConnection is returned when execution is requested without a live database handle.

View Source
var ErrPrepareNotSupported = errors.New("rain: query runner does not support prepared statements")

ErrPrepareNotSupported is returned when the current query runner cannot prepare statements.

View Source
var ErrPreparedArgsRequired = errors.New("rain: query contains named placeholders; call Prepare and execute with PreparedArgs")

ErrPreparedArgsRequired is returned when a query with named placeholders is executed without prepared binding.

Functions

func BindModel

func BindModel[T any](table schema.TableReference) error

BindModel validates a model type against a table and caches the result. Deprecated: use BindTableModel for strict table-backed read/write models.

func BindTableModel

func BindTableModel[T any](table schema.TableReference) error

BindTableModel validates a full table-backed read/write model type against a table and caches the result.

func MustBindModel

func MustBindModel[T any](table schema.TableReference)

MustBindModel validates a model type against a table and panics on error. Deprecated: use MustBindTableModel for strict table-backed read/write models.

func MustBindTableModel

func MustBindTableModel[T any](table schema.TableReference)

MustBindTableModel validates a full table-backed read/write model type and panics on error.

Types

type DB

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

DB represents a database connection pool.

func Open

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

Open creates a database handle for the selected dialect.

func OpenDialect

func OpenDialect(driver string) (*DB, error)

OpenDialect creates a dialect-only handle that can compile SQL without a live database connection.

func WithReplicas

func WithReplicas(primary *DB, replicas []*DB, selector ReplicaSelector) (*DB, error)

WithReplicas returns a DB handle that routes SELECT queries to read replicas while keeping writes, raw SQL, and transactions on the primary handle.

func (*DB) AddConstraintSQL

func (db *DB) AddConstraintSQL(table schema.TableReference, constraintName string) (string, error)

AddConstraintSQL compiles one ALTER TABLE ... ADD ... statement for a named table constraint.

func (*DB) AddForeignKeySQL

func (db *DB) AddForeignKeySQL(table schema.TableReference, foreignKeyName string) (string, error)

AddForeignKeySQL compiles one ALTER TABLE ... ADD ... statement for a named foreign key.

func (*DB) Begin

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

Begin starts a new transaction.

func (*DB) Close

func (db *DB) Close() error

Close closes the database connection.

func (*DB) ColumnDefaultSQL

func (db *DB) ColumnDefaultSQL(table schema.TableReference, columnName string) (string, error)

ColumnDefaultSQL renders one column default expression for snapshotting and migration checks.

func (*DB) ColumnDefinitionSQL

func (db *DB) ColumnDefinitionSQL(table schema.TableReference, columnName string) (string, error)

ColumnDefinitionSQL compiles one column definition without the ALTER TABLE wrapper.

func (*DB) CreateIndexesSQL

func (db *DB) CreateIndexesSQL(table schema.TableReference) ([]string, error)

CreateIndexesSQL compiles schema index metadata into CREATE INDEX statements.

func (*DB) CreateTableSQL

func (db *DB) CreateTableSQL(table schema.TableReference) (string, error)

CreateTableSQL compiles a typed schema definition into a CREATE TABLE statement.

func (*DB) Delete

func (db *DB) Delete() *DeleteQuery

Delete starts a typed DELETE query builder.

func (*DB) Dialect

func (db *DB) Dialect() dialect.Dialect

Dialect returns the configured SQL dialect.

func (*DB) Exec

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

Exec executes raw SQL against the database.

func (*DB) Insert

func (db *DB) Insert() *InsertQuery

Insert starts a typed INSERT query builder.

func (*DB) InvalidateQueryCache

func (db *DB) InvalidateQueryCache(ctx context.Context, tags ...string) error

InvalidateQueryCache removes cached query entries associated with any provided tag.

func (*DB) Primary

func (db *DB) Primary() *DB

Primary returns a DB view that forces reads to use the primary handle.

func (*DB) Query

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

Query executes a SQL query and returns rows.

func (*DB) QueryRow

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

QueryRow executes a query that returns a single row.

func (*DB) RunInTx

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

RunInTx executes fn in a transaction, rolling back on error and committing on success.

func (*DB) Select

func (db *DB) Select() *SelectQuery

Select starts a typed SELECT query builder.

func (*DB) Update

func (db *DB) Update() *UpdateQuery

Update starts a typed UPDATE query builder.

func (*DB) WithQueryCache

func (db *DB) WithQueryCache(cache QueryCache) *DB

WithQueryCache sets the shared SELECT query cache backend on DB.

type DeleteQuery

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

DeleteQuery builds typed DELETE statements.

func (*DeleteQuery) Exec

func (q *DeleteQuery) Exec(ctx context.Context) (sql.Result, error)

Exec executes the DELETE query.

func (*DeleteQuery) Returning

func (q *DeleteQuery) Returning(exprs ...schema.Expression) *DeleteQuery

Returning adds RETURNING expressions when supported by the dialect.

func (*DeleteQuery) Scan

func (q *DeleteQuery) Scan(ctx context.Context, dest any) error

Scan executes a DELETE ... RETURNING query and scans results into dest.

func (*DeleteQuery) Table

func (q *DeleteQuery) Table(table schema.TableReference) *DeleteQuery

Table sets the DELETE target table.

func (*DeleteQuery) ToSQL

func (q *DeleteQuery) ToSQL() (string, []any, error)

ToSQL compiles the delete into SQL and args.

func (*DeleteQuery) Unbounded

func (q *DeleteQuery) Unbounded() *DeleteQuery

Unbounded allows DELETE without a WHERE clause.

func (*DeleteQuery) Where

func (q *DeleteQuery) Where(predicate schema.Predicate) *DeleteQuery

Where appends a WHERE predicate joined with AND.

type InsertConflictBuilder

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

InsertConflictBuilder configures conflict behavior for INSERT statements.

func (*InsertConflictBuilder) DoNothing

func (b *InsertConflictBuilder) DoNothing() *InsertQuery

DoNothing configures ON CONFLICT ... DO NOTHING.

func (*InsertConflictBuilder) DoUpdateSet

func (b *InsertConflictBuilder) DoUpdateSet(columns ...schema.ColumnReference) *InsertQuery

DoUpdateSet configures ON CONFLICT ... DO UPDATE SET using EXCLUDED values.

type InsertQuery

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

InsertQuery builds typed INSERT statements.

func (*InsertQuery) Exec

func (q *InsertQuery) Exec(ctx context.Context) (sql.Result, error)

Exec executes the INSERT query.

func (*InsertQuery) Model

func (q *InsertQuery) Model(model any) *InsertQuery

Model sets a struct payload for the insert. Plain fields are treated as explicit values, including zero values. Nil pointers are omitted, and rain.Set[T]{Valid:false} omits a value so schema defaults can apply.

func (*InsertQuery) Models

func (q *InsertQuery) Models(models any) *InsertQuery

Models sets multiple struct payloads for a bulk insert.

func (*InsertQuery) OnConflict

func (q *InsertQuery) OnConflict(columns ...schema.ColumnReference) *InsertConflictBuilder

OnConflict starts an upsert clause for PostgreSQL and SQLite dialects.

func (*InsertQuery) Returning

func (q *InsertQuery) Returning(exprs ...schema.Expression) *InsertQuery

Returning adds RETURNING expressions when supported by the dialect.

func (*InsertQuery) Scan

func (q *InsertQuery) Scan(ctx context.Context, dest any) error

Scan executes an INSERT ... RETURNING query and scans one row into dest.

func (*InsertQuery) Set

func (q *InsertQuery) Set(column schema.ColumnReference, value any) *InsertQuery

Set adds an explicit column assignment.

func (*InsertQuery) Table

func (q *InsertQuery) Table(table schema.TableReference) *InsertQuery

Table sets the INSERT target table.

func (*InsertQuery) ToSQL

func (q *InsertQuery) ToSQL() (string, []any, error)

ToSQL compiles the insert into SQL and args.

func (*InsertQuery) Values

func (q *InsertQuery) Values(rows ...map[schema.ColumnReference]any) *InsertQuery

Values appends explicit row value sets for a bulk insert.

type JSON

type JSON[T any] struct {
	V T
}

JSON wraps a typed Go value for JSON/JSONB columns.

func (*JSON[T]) Scan

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

Scan implements sql.Scanner.

func (JSON[T]) Value

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

Value implements driver.Valuer.

type MemoryQueryCache

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

MemoryQueryCache is an in-memory QueryCache backend for local use and tests.

func NewMemoryQueryCache

func NewMemoryQueryCache() *MemoryQueryCache

NewMemoryQueryCache creates a new in-memory query cache.

func (*MemoryQueryCache) Get

func (c *MemoryQueryCache) Get(_ context.Context, key string) ([]byte, bool, error)

func (*MemoryQueryCache) InvalidateTags

func (c *MemoryQueryCache) InvalidateTags(_ context.Context, tags ...string) error

func (*MemoryQueryCache) Set

func (c *MemoryQueryCache) Set(_ context.Context, key string, value []byte, ttl time.Duration, tags []string) error

type PreparedArgs

type PreparedArgs map[string]any

PreparedArgs provides runtime values for a prepared query's named placeholders.

type PreparedSelectQuery

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

PreparedSelectQuery is a prepared SELECT query with reusable named argument binding.

func (*PreparedSelectQuery) Close

func (p *PreparedSelectQuery) Close() error

Close closes all prepared statements.

func (*PreparedSelectQuery) Count

func (p *PreparedSelectQuery) Count(ctx context.Context, args PreparedArgs) (int64, error)

Count executes the prepared COUNT(*) query.

func (*PreparedSelectQuery) Exists

func (p *PreparedSelectQuery) Exists(ctx context.Context, args PreparedArgs) (bool, error)

Exists executes the prepared SELECT EXISTS query.

func (*PreparedSelectQuery) Scan

func (p *PreparedSelectQuery) Scan(ctx context.Context, args PreparedArgs, dest any) error

Scan executes the prepared SELECT query and scans results into dest.

type QueryCache

type QueryCache interface {
	Get(ctx context.Context, key string) ([]byte, bool, error)
	Set(ctx context.Context, key string, value []byte, ttl time.Duration, tags []string) error
	InvalidateTags(ctx context.Context, tags ...string) error
}

QueryCache is the pluggable backend interface for opt-in SELECT query caching.

type QueryCacheOptions

type QueryCacheOptions struct {
	TTL       time.Duration
	Tags      []string
	Namespace string
	Key       string
	Bypass    bool
}

QueryCacheOptions configures per-query cache behavior for SELECT helpers.

type ReplicaSelector

type ReplicaSelector func(replicas []*DB) *DB

ReplicaSelector chooses which read replica should serve a SELECT query.

type SelectQuery

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

SelectQuery builds typed SELECT statements.

func (*SelectQuery) Cache

func (q *SelectQuery) Cache(options QueryCacheOptions) *SelectQuery

Cache enables opt-in query caching for this SELECT with TTL and optional metadata. Queries that use WithRelations do not read from or write to the query cache.

func (*SelectQuery) Column

func (q *SelectQuery) Column(cols ...schema.Expression) *SelectQuery

Column sets the selected expressions.

func (*SelectQuery) Count

func (q *SelectQuery) Count(ctx context.Context) (int64, error)

Count executes SELECT COUNT(*).

func (*SelectQuery) Distinct

func (q *SelectQuery) Distinct() *SelectQuery

Distinct marks the SELECT query as DISTINCT.

func (*SelectQuery) Exists

func (q *SelectQuery) Exists(ctx context.Context) (bool, error)

Exists executes a SELECT EXISTS query.

func (*SelectQuery) GroupBy

func (q *SelectQuery) GroupBy(exprs ...schema.Expression) *SelectQuery

GroupBy appends GROUP BY expressions.

func (*SelectQuery) Having

func (q *SelectQuery) Having(predicate schema.Predicate) *SelectQuery

Having appends a HAVING predicate joined with AND.

func (*SelectQuery) Join

Join appends an INNER JOIN clause.

func (*SelectQuery) JoinSubquery

func (q *SelectQuery) JoinSubquery(query *SelectQuery, alias string, on schema.Predicate) *SelectQuery

JoinSubquery appends an INNER JOIN against a subquery source.

func (*SelectQuery) LeftJoin

func (q *SelectQuery) LeftJoin(table schema.TableReference, on schema.Predicate) *SelectQuery

LeftJoin appends a LEFT JOIN clause.

func (*SelectQuery) LeftJoinSubquery

func (q *SelectQuery) LeftJoinSubquery(query *SelectQuery, alias string, on schema.Predicate) *SelectQuery

LeftJoinSubquery appends a LEFT JOIN against a subquery source.

func (*SelectQuery) Limit

func (q *SelectQuery) Limit(limit int) *SelectQuery

Limit sets the LIMIT clause.

func (*SelectQuery) Offset

func (q *SelectQuery) Offset(offset int) *SelectQuery

Offset sets the OFFSET clause.

func (*SelectQuery) OrderBy

func (q *SelectQuery) OrderBy(order ...schema.OrderExpr) *SelectQuery

OrderBy appends ORDER BY expressions.

func (*SelectQuery) Prepare

func (q *SelectQuery) Prepare(ctx context.Context) (*PreparedSelectQuery, error)

Prepare compiles and prepares the SELECT query and derived aggregate statements.

func (*SelectQuery) Scan

func (q *SelectQuery) Scan(ctx context.Context, dest any) error

Scan executes the SELECT query and scans results into dest.

func (*SelectQuery) Table

func (q *SelectQuery) Table(table schema.TableReference) *SelectQuery

Table sets the table source for the query.

func (*SelectQuery) TableSubquery

func (q *SelectQuery) TableSubquery(query *SelectQuery, alias string) *SelectQuery

TableSubquery sets a subquery source for the query's FROM clause.

func (*SelectQuery) ToSQL

func (q *SelectQuery) ToSQL() (string, []any, error)

ToSQL compiles the query into SQL and args.

func (*SelectQuery) Where

func (q *SelectQuery) Where(predicate schema.Predicate) *SelectQuery

Where appends a WHERE predicate joined with AND.

func (*SelectQuery) With

func (q *SelectQuery) With(name string, query *SelectQuery) *SelectQuery

With appends a common table expression definition.

func (*SelectQuery) WithRelations

func (q *SelectQuery) WithRelations(names ...string) *SelectQuery

WithRelations requests one or more named relations to be loaded after scanning base rows.

type Set

type Set[T any] struct {
	Value T
	Valid bool
}

Set allows value types to opt into omission semantics during writes.

type Tx

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

Tx represents a database transaction.

func (*Tx) Commit

func (tx *Tx) Commit() error

Commit commits the transaction.

func (*Tx) Delete

func (tx *Tx) Delete() *DeleteQuery

Delete starts a typed DELETE query builder in the transaction.

func (*Tx) Insert

func (tx *Tx) Insert() *InsertQuery

Insert starts a typed INSERT query builder in the transaction.

func (*Tx) InvalidateQueryCache

func (tx *Tx) InvalidateQueryCache(ctx context.Context, tags ...string) error

InvalidateQueryCache removes cached query entries associated with any provided tag.

func (*Tx) Rollback

func (tx *Tx) Rollback() error

Rollback rolls the transaction back.

func (*Tx) RunInTx

func (tx *Tx) RunInTx(ctx context.Context, fn func(*Tx) error) error

RunInTx executes fn in a nested transaction using a savepoint.

func (*Tx) Select

func (tx *Tx) Select() *SelectQuery

Select starts a typed SELECT query builder in the transaction.

func (*Tx) Update

func (tx *Tx) Update() *UpdateQuery

Update starts a typed UPDATE query builder in the transaction.

type UpdateQuery

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

UpdateQuery builds typed UPDATE statements.

func (*UpdateQuery) Exec

func (q *UpdateQuery) Exec(ctx context.Context) (sql.Result, error)

Exec executes the UPDATE query.

func (*UpdateQuery) Returning

func (q *UpdateQuery) Returning(exprs ...schema.Expression) *UpdateQuery

Returning adds RETURNING expressions when supported by the dialect.

func (*UpdateQuery) Scan

func (q *UpdateQuery) Scan(ctx context.Context, dest any) error

Scan executes an UPDATE ... RETURNING query and scans results into dest.

func (*UpdateQuery) Set

func (q *UpdateQuery) Set(column schema.ColumnReference, value any) *UpdateQuery

Set adds an explicit typed assignment.

func (*UpdateQuery) Table

func (q *UpdateQuery) Table(table schema.TableReference) *UpdateQuery

Table sets the UPDATE target table.

func (*UpdateQuery) ToSQL

func (q *UpdateQuery) ToSQL() (string, []any, error)

ToSQL compiles the update into SQL and args.

func (*UpdateQuery) Unbounded

func (q *UpdateQuery) Unbounded() *UpdateQuery

Unbounded allows UPDATE without a WHERE clause.

func (*UpdateQuery) Where

func (q *UpdateQuery) Where(predicate schema.Predicate) *UpdateQuery

Where appends a WHERE predicate joined with AND.

Jump to

Keyboard shortcuts

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