schema

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: 4 Imported by: 0

Documentation

Overview

Package schema provides typed schema definitions and reusable SQL expressions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Alias

func Alias[T any](src *T, alias string) *T

Alias clones a typed table handle with a SQL alias.

func Define

func Define[T any](name string, fn func(*T)) *T

Define creates a typed table handle backed by schema metadata.

Types

type AggregateExpr

type AggregateExpr struct {
	Function string
	Expr     Expression
	Star     bool
	Distinct bool
}

AggregateExpr renders SQL aggregate functions.

Function must be non-empty. Distinct must not be combined with Star.

func Avg

func Avg(expr Expression) AggregateExpr

Avg renders AVG(expr).

func Count

func Count(exprs ...Expression) AggregateExpr

Count renders COUNT(*) when no expression is provided, or COUNT(expr) when one expression is provided.

func Max

func Max(expr Expression) AggregateExpr

Max renders MAX(expr).

func Min

func Min(expr Expression) AggregateExpr

Min renders MIN(expr).

func Sum

func Sum(expr Expression) AggregateExpr

Sum renders SUM(expr).

func (AggregateExpr) As

func (a AggregateExpr) As(alias string) AliasExpr

As aliases this computed expression in a SELECT list.

type AliasExpr

type AliasExpr struct {
	Expr  Expression
	Alias string
}

AliasExpr renames a computed expression in a select list.

func As

func As(expr Expression, alias string) AliasExpr

As aliases an expression in a SELECT list.

type AnyColumn

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

AnyColumn is an untyped column reference.

func Ref

func Ref(def *ColumnDef) *AnyColumn

Ref creates an untyped column reference from metadata.

func (*AnyColumn) As

func (c *AnyColumn) As(alias string) AliasExpr

As aliases this column in a SELECT list.

func (*AnyColumn) Asc

func (c *AnyColumn) Asc() OrderExpr

Asc returns an ascending sort expression.

func (*AnyColumn) ColumnDef

func (c *AnyColumn) ColumnDef() *ColumnDef

ColumnDef returns metadata for this column.

func (*AnyColumn) Desc

func (c *AnyColumn) Desc() OrderExpr

Desc returns a descending sort expression.

func (*AnyColumn) In

func (c *AnyColumn) In(values ...any) InExpr

In compares this column to a set of Go values using SQL IN.

type CoalesceExpr

type CoalesceExpr struct {
	Exprs []Expression
}

CoalesceExpr renders COALESCE(expr1, expr2, ...).

func Coalesce

func Coalesce(exprs ...Expression) CoalesceExpr

Coalesce renders COALESCE(expr1, expr2, ...).

func (CoalesceExpr) As

func (c CoalesceExpr) As(alias string) AliasExpr

As aliases this computed expression in a SELECT list.

type Column

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

Column represents a typed column handle.

func (*Column[T]) As

func (c *Column[T]) As(alias string) AliasExpr

As aliases this column in a SELECT list.

func (*Column[T]) Asc

func (c *Column[T]) Asc() OrderExpr

Asc returns an ascending sort expression.

func (*Column[T]) ColumnDef

func (c *Column[T]) ColumnDef() *ColumnDef

ColumnDef returns metadata for this column.

func (*Column[T]) Default

func (c *Column[T]) Default(value T) *Column[T]

Default sets a Go value default.

func (*Column[T]) DefaultNow

func (c *Column[T]) DefaultNow() *Column[T]

DefaultNow sets CURRENT_TIMESTAMP as the default value.

func (*Column[T]) Desc

func (c *Column[T]) Desc() OrderExpr

Desc returns a descending sort expression.

func (*Column[T]) Eq

func (c *Column[T]) Eq(value T) ComparisonExpr

Eq compares this column to a Go value.

func (*Column[T]) EqCol

func (c *Column[T]) EqCol(other ColumnReference) ComparisonExpr

EqCol compares this column to another column.

func (*Column[T]) EqExpr

func (c *Column[T]) EqExpr(expr Expression) ComparisonExpr

EqExpr compares this column to another SQL expression.

func (*Column[T]) Gt

func (c *Column[T]) Gt(value T) ComparisonExpr

Gt compares this column to a Go value.

func (*Column[T]) GtExpr

func (c *Column[T]) GtExpr(expr Expression) ComparisonExpr

GtExpr compares this column to another SQL expression.

func (*Column[T]) Gte

func (c *Column[T]) Gte(value T) ComparisonExpr

Gte compares this column to a Go value.

func (*Column[T]) GteExpr

func (c *Column[T]) GteExpr(expr Expression) ComparisonExpr

GteExpr compares this column to another SQL expression.

func (*Column[T]) In

func (c *Column[T]) In(values ...T) InExpr

In compares this column to a set of Go values using SQL IN.

func (*Column[T]) IsNotNull

func (c *Column[T]) IsNotNull() NullCheckExpr

IsNotNull creates an IS NOT NULL predicate.

func (*Column[T]) IsNull

func (c *Column[T]) IsNull() NullCheckExpr

IsNull creates an IS NULL predicate.

func (*Column[T]) Lt

func (c *Column[T]) Lt(value T) ComparisonExpr

Lt compares this column to a Go value.

func (*Column[T]) LtExpr

func (c *Column[T]) LtExpr(expr Expression) ComparisonExpr

LtExpr compares this column to another SQL expression.

func (*Column[T]) Lte

func (c *Column[T]) Lte(value T) ComparisonExpr

Lte compares this column to a Go value.

func (*Column[T]) LteExpr

func (c *Column[T]) LteExpr(expr Expression) ComparisonExpr

LteExpr compares this column to another SQL expression.

func (*Column[T]) Ne

func (c *Column[T]) Ne(value T) ComparisonExpr

Ne compares this column to a Go value.

func (*Column[T]) NeExpr

func (c *Column[T]) NeExpr(expr Expression) ComparisonExpr

NeExpr compares this column to another SQL expression.

func (*Column[T]) NotNull

func (c *Column[T]) NotNull() *Column[T]

NotNull marks the column as NOT NULL.

func (*Column[T]) Nullable

func (c *Column[T]) Nullable() *Column[T]

Nullable marks the column as nullable.

func (*Column[T]) PrimaryKey

func (c *Column[T]) PrimaryKey() *Column[T]

PrimaryKey marks the column as a primary key.

func (*Column[T]) References

func (c *Column[T]) References(other ColumnReference) *Column[T]

References creates a foreign-key reference to another column.

func (*Column[T]) Unique

func (c *Column[T]) Unique() *Column[T]

Unique marks the column as unique.

type ColumnDef

type ColumnDef struct {
	Table         *TableDef
	Name          string
	Type          ColumnType
	Nullable      bool
	Default       any
	HasDefault    bool
	DefaultSQL    string
	PrimaryKey    bool
	AutoIncrement bool
	Unique        bool
}

ColumnDef stores immutable column metadata after schema construction.

type ColumnReference

type ColumnReference interface {
	Expression
	ColumnDef() *ColumnDef
}

ColumnReference is implemented by typed and untyped column handles.

type ColumnType

type ColumnType struct {
	DataType        DataType
	Size            int
	LengthSemantics LengthSemantics
	Precision       int
	Scale           int
	TimePrecision   int
	TimestampKind   TimestampKind
	EnumValues      []string
}

ColumnType stores schema metadata about a column's logical type.

type ComparisonExpr

type ComparisonExpr struct {
	Left     Expression
	Operator string
	Right    Expression
}

ComparisonExpr compares two expressions.

type ConstraintBuilder

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

ConstraintBuilder configures a table constraint backed by columns.

func (*ConstraintBuilder) On

On binds columns to the table constraint.

type ConstraintColumnSpec

type ConstraintColumnSpec interface {
	// contains filtered or unexported methods
}

ConstraintColumnSpec is implemented by values that can be bound to a table constraint.

type ConstraintDef

type ConstraintDef struct {
	Name            string
	Type            ConstraintType
	Columns         []*ColumnDef
	Check           Predicate
	ReferencedTable *TableDef
	ReferencedCols  []*ColumnDef
	OnDelete        ForeignKeyAction
	OnUpdate        ForeignKeyAction
}

ConstraintDef stores portable table-level constraint metadata.

type ConstraintType

type ConstraintType string

ConstraintType identifies a portable table constraint kind.

const (
	ConstraintPrimaryKey ConstraintType = "primary_key"
	ConstraintUnique     ConstraintType = "unique"
	ConstraintCheck      ConstraintType = "check"
	ConstraintForeignKey ConstraintType = "foreign_key"
)

type DataType

type DataType string

DataType represents a database column type.

const (
	TypeBigSerial   DataType = "BIGSERIAL"
	TypeSmallInt    DataType = "SMALLINT"
	TypeInteger     DataType = "INTEGER"
	TypeBigInt      DataType = "BIGINT"
	TypeReal        DataType = "REAL"
	TypeDouble      DataType = "DOUBLE"
	TypeDecimal     DataType = "DECIMAL"
	TypeText        DataType = "TEXT"
	TypeVarChar     DataType = "VARCHAR"
	TypeBoolean     DataType = "BOOLEAN"
	TypeJSON        DataType = "JSON"
	TypeJSONB       DataType = "JSONB"
	TypeUUID        DataType = "UUID"
	TypeBytes       DataType = "BYTES"
	TypeDate        DataType = "DATE"
	TypeTimestamp   DataType = "TIMESTAMP"
	TypeTimestampTZ DataType = "TIMESTAMPTZ"
	TypeEnum        DataType = "ENUM"
)

Supported schema data types.

type Expression

type Expression interface {
	// contains filtered or unexported methods
}

Expression is implemented by all query expressions.

type ForeignKeyAction

type ForeignKeyAction string

ForeignKeyAction identifies a portable foreign-key action.

const (
	ForeignKeyActionNoAction   ForeignKeyAction = "NO ACTION"
	ForeignKeyActionRestrict   ForeignKeyAction = "RESTRICT"
	ForeignKeyActionCascade    ForeignKeyAction = "CASCADE"
	ForeignKeyActionSetNull    ForeignKeyAction = "SET NULL"
	ForeignKeyActionSetDefault ForeignKeyAction = "SET DEFAULT"
)

type ForeignKeyBuilder

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

ForeignKeyBuilder configures a table-level foreign key constraint.

func (*ForeignKeyBuilder) On

On binds source columns to the foreign key.

func (*ForeignKeyBuilder) OnDelete

OnDelete sets the ON DELETE action for the foreign key.

func (*ForeignKeyBuilder) OnUpdate

OnUpdate sets the ON UPDATE action for the foreign key.

func (*ForeignKeyBuilder) References

func (b *ForeignKeyBuilder) References(columns ...ConstraintColumnSpec) *ForeignKeyBuilder

References binds referenced columns to the foreign key.

type ForeignKeyDef

type ForeignKeyDef struct {
	Name             string
	Column           *ColumnDef
	ReferencedTable  *TableDef
	ReferencedColumn *ColumnDef
	OnDelete         ForeignKeyAction
	OnUpdate         ForeignKeyAction
}

ForeignKeyDef stores a foreign-key relationship.

type InExpr

type InExpr struct {
	Left   Expression
	Values []Expression
}

InExpr renders an IN predicate.

type IndexBuilder

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

IndexBuilder configures a table index.

func (*IndexBuilder) On

func (b *IndexBuilder) On(columns ...IndexColumnSpec) *IndexBuilder

On binds ordered columns to the index.

type IndexColumn

type IndexColumn struct {
	Column    ColumnReference
	Direction SortDirection
}

IndexColumn stores an indexed column and its sort direction.

type IndexColumnSpec

type IndexColumnSpec interface {
	// contains filtered or unexported methods
}

IndexColumnSpec is implemented by values that can be bound to an index.

type IndexDef

type IndexDef struct {
	Name    string
	Unique  bool
	Columns []IndexColumn
	Where   string
}

IndexDef stores table-level index metadata.

type LengthSemantics

type LengthSemantics string

LengthSemantics describes how a type uses any configured length.

const (
	LengthSemanticsUnspecified LengthSemantics = ""
	LengthSemanticsVariable    LengthSemantics = "variable"
	LengthSemanticsFixed       LengthSemantics = "fixed"
)

type LogicalExpr

type LogicalExpr struct {
	Operator string
	Exprs    []Predicate
}

LogicalExpr groups predicates with AND or OR.

func And

func And(predicates ...Predicate) LogicalExpr

And combines predicates with AND.

func Or

func Or(predicates ...Predicate) LogicalExpr

Or combines predicates with OR.

type NullCheckExpr

type NullCheckExpr struct {
	Expr    Expression
	Negated bool
}

NullCheckExpr renders IS NULL or IS NOT NULL.

type OrderExpr

type OrderExpr struct {
	Expr      Expression
	Direction SortDirection
}

OrderExpr renders ORDER BY expressions and indexed sort directions.

type PlaceholderExpr

type PlaceholderExpr struct {
	Name string
}

PlaceholderExpr references a named runtime value for prepared query execution.

func Placeholder

func Placeholder(name string) PlaceholderExpr

Placeholder references a named runtime value in a prepared query.

type Predicate

type Predicate interface {
	Expression
	// contains filtered or unexported methods
}

Predicate is implemented by boolean SQL expressions.

type RawExpr

type RawExpr struct {
	SQL  string
	Args []any
}

RawExpr is an escape hatch for raw SQL with bound args.

func Raw

func Raw(sql string, args ...any) RawExpr

Raw returns a raw SQL expression.

func (RawExpr) As

func (r RawExpr) As(alias string) AliasExpr

As aliases this raw expression in a SELECT list.

type RelationDef

type RelationDef struct {
	Name         string
	Type         RelationType
	SourceColumn *ColumnDef
	TargetTable  *TableDef
	TargetColumn *ColumnDef
}

RelationDef stores table-level relation metadata used by relation loading.

type RelationType

type RelationType string

RelationType identifies how two tables are related.

const (
	RelationTypeBelongsTo RelationType = "belongs_to"
	RelationTypeHasMany   RelationType = "has_many"
)

type SoftDelete

type SoftDelete struct {
	DeletedAt *time.Time `db:"deleted_at"`
}

SoftDelete can be embedded into models used for scans and payloads.

type SortDirection

type SortDirection string

SortDirection represents an ORDER BY or index column direction.

const (
	SortAsc  SortDirection = "ASC"
	SortDesc SortDirection = "DESC"
)

Supported sort directions.

type TableDef

type TableDef struct {
	Name        string
	Alias       string
	Columns     []*ColumnDef
	Indexes     []IndexDef
	Constraints []ConstraintDef
	ForeignKeys []ForeignKeyDef
	Relations   []RelationDef
	// contains filtered or unexported fields
}

TableDef stores immutable table metadata after schema construction.

func (*TableDef) ColumnByName

func (t *TableDef) ColumnByName(name string) (*ColumnDef, bool)

ColumnByName returns a column definition by name.

func (*TableDef) RelationByName

func (t *TableDef) RelationByName(name string) (RelationDef, bool)

RelationByName returns a relation definition by name.

type TableModel

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

TableModel is embedded in user-defined table structs.

func (*TableModel) BelongsTo

func (t *TableModel) BelongsTo(name string, source ColumnReference, target ColumnReference)

BelongsTo registers a belongs-to relation on the table.

func (*TableModel) BigInt

func (t *TableModel) BigInt(name string) *Column[int64]

BigInt adds a BIGINT column.

func (*TableModel) BigSerial

func (t *TableModel) BigSerial(name string) *Column[int64]

BigSerial adds a BIGSERIAL column.

func (*TableModel) Boolean

func (t *TableModel) Boolean(name string) *Column[bool]

Boolean adds a BOOLEAN column.

func (*TableModel) Bytes

func (t *TableModel) Bytes(name string) *Column[[]byte]

Bytes adds a bytes/blob column for arbitrary binary payloads.

func (*TableModel) C

func (t *TableModel) C(name string) *AnyColumn

C returns an untyped column handle by name for index definitions or dynamic access.

func (*TableModel) Check

func (t *TableModel) Check(name string, predicate Predicate)

Check declares a table-level CHECK constraint.

func (*TableModel) Date

func (t *TableModel) Date(name string) *Column[time.Time]

Date adds a DATE column intended for calendar-date values.

func (*TableModel) Decimal

func (t *TableModel) Decimal(name string, precision, scale int) *Column[string]

Decimal adds a DECIMAL/NUMERIC column with fixed precision and scale.

func (*TableModel) Double

func (t *TableModel) Double(name string) *Column[float64]

Double adds a DOUBLE/DOUBLE PRECISION column for double-precision values.

func (*TableModel) Enum

func (t *TableModel) Enum(name string, values ...string) *Column[string]

Enum adds a string-backed enum-style column with allowed values metadata.

func (*TableModel) ForeignKey

func (t *TableModel) ForeignKey(name string) *ForeignKeyBuilder

ForeignKey declares a table-level foreign key constraint.

func (*TableModel) HasMany

func (t *TableModel) HasMany(name string, source ColumnReference, target ColumnReference)

HasMany registers a has-many relation on the table.

func (*TableModel) Index

func (t *TableModel) Index(name string) *IndexBuilder

Index declares a non-unique index.

func (*TableModel) Integer

func (t *TableModel) Integer(name string) *Column[int32]

Integer adds an INTEGER column intended for standard 32-bit integer values.

func (*TableModel) JSON

func (t *TableModel) JSON(name string) *Column[any]

JSON adds a JSON column for semi-structured values.

func (*TableModel) JSONB

func (t *TableModel) JSONB(name string) *Column[any]

JSONB adds a JSONB binary JSON column where supported.

func (*TableModel) PrimaryKey

func (t *TableModel) PrimaryKey(name string) *ConstraintBuilder

PrimaryKey declares a table-level primary key constraint.

func (*TableModel) Real

func (t *TableModel) Real(name string) *Column[float32]

Real adds a REAL/FLOAT-style column intended for single-precision values.

func (*TableModel) SmallInt

func (t *TableModel) SmallInt(name string) *Column[int16]

SmallInt adds a SMALLINT column intended for 16-bit integer values.

func (*TableModel) TableDef

func (t *TableModel) TableDef() *TableDef

TableDef returns the underlying table metadata.

func (*TableModel) Text

func (t *TableModel) Text(name string) *Column[string]

Text adds a TEXT column.

func (*TableModel) Timestamp

func (t *TableModel) Timestamp(name string) *Column[time.Time]

Timestamp adds a TIMESTAMP column without timezone semantics.

func (*TableModel) TimestampPrecision

func (t *TableModel) TimestampPrecision(name string, precision int) *Column[time.Time]

TimestampPrecision adds a TIMESTAMP column with explicit fractional precision.

func (*TableModel) TimestampTZ

func (t *TableModel) TimestampTZ(name string) *Column[time.Time]

TimestampTZ adds a TIMESTAMPTZ column.

func (*TableModel) TimestampTZPrecision

func (t *TableModel) TimestampTZPrecision(name string, precision int) *Column[time.Time]

TimestampTZPrecision adds a TIMESTAMPTZ column with explicit fractional precision.

func (*TableModel) UUID

func (t *TableModel) UUID(name string) *Column[string]

UUID adds a UUID column for canonical UUID string values.

func (*TableModel) Unique

func (t *TableModel) Unique(name string) *ConstraintBuilder

Unique declares a table-level unique constraint.

func (*TableModel) UniqueIndex

func (t *TableModel) UniqueIndex(name string) *IndexBuilder

UniqueIndex declares a unique index.

func (*TableModel) VarChar

func (t *TableModel) VarChar(name string, size int) *Column[string]

VarChar adds a VARCHAR column.

type TableReference

type TableReference interface {
	TableDef() *TableDef
}

TableReference is implemented by typed table handles.

type TimestampKind

type TimestampKind string

TimestampKind describes timestamp timezone semantics.

const (
	TimestampKindUnspecified TimestampKind = ""
	TimestampKindWithoutTZ   TimestampKind = "without_tz"
	TimestampKindWithTZ      TimestampKind = "with_tz"
)

type Timestamps

type Timestamps struct {
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`
}

Timestamps can be embedded into models used for scans and payloads.

type ValueExpr

type ValueExpr struct {
	Value any
}

ValueExpr wraps a Go value for SQL rendering.

Jump to

Keyboard shortcuts

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