Documentation
¶
Overview ¶
Package sequel is a pure-Go (no cgo) reimplementation of the deterministic SQL-generation core of Ruby's Sequel toolkit (the `sequel` gem): the Dataset query builder, the expression DSL, the schema DSL, and per-dialect literalization/identifier-quoting. It emits the exact SQL strings the gem emits, byte-for-byte, across the default, sqlite and postgres dialects.
What it is — and isn't. Turning a chain of `DB[:t].where(...).order(...)` calls into a SQL string is fully deterministic and needs no database and no Ruby runtime, so it lives here as pure Go. Actually running that SQL against a server is the host's job: a Database carries an injectable Executor seam (`Execute(sql) -> rows`) the host wires to a driver such as go-ruby-sqlite3 or go-ruby-pg. The SQL text is what this library generates and tests; execution is the seam.
Index ¶
- func Arith(op string, left, right Value) arithOp
- func JoinOn(kv ...string) joinHash
- type AliasedExpr
- type AlterBuilder
- func (a *AlterBuilder) AddColumn(c Column) *AlterBuilder
- func (a *AlterBuilder) AddIndex(cols []string, opts ...IdxOpt) *AlterBuilder
- func (a *AlterBuilder) DropColumn(name string) *AlterBuilder
- func (a *AlterBuilder) DropIndex(cols []string, opts ...IdxOpt) *AlterBuilder
- func (a *AlterBuilder) RenameColumn(from, to string) *AlterBuilder
- func (a *AlterBuilder) SetColumnDefault(name string, v Value) *AlterBuilder
- func (a *AlterBuilder) SetColumnType(name string, ct ColumnType) *AlterBuilder
- type AssocOption
- type AssocType
- type Blob
- type ColOpt
- type Column
- type ColumnType
- type Database
- func (db *Database) All(d *Dataset) ([]map[string]Value, error)
- func (db *Database) AlterTable(table string, fn func(*AlterBuilder)) []string
- func (db *Database) AlterTableSQL(a *AlterBuilder) []string
- func (db *Database) CreateTable(table string, fn func(*TableBuilder)) []string
- func (db *Database) CreateTableSQL(t *TableBuilder) []string
- func (db *Database) Dataset() *Dataset
- func (db *Database) Dialect() Dialect
- func (db *Database) DropTable(tables ...string) []string
- func (db *Database) DropTableSQL(tables ...string) []string
- func (db *Database) From(tables ...Value) *Dataset
- func (db *Database) Model(table string) *ModelClass
- func (db *Database) Run(sql string) ([]map[string]Value, error)
- func (db *Database) SQLs() []string
- func (db *Database) T(table string) *Dataset
- type Dataset
- func (d *Dataset) CrossJoin(table Value) *Dataset
- func (d *Dataset) DeleteSQL() string
- func (d *Dataset) Distinct() *Dataset
- func (d *Dataset) Except(other *Dataset) *Dataset
- func (d *Dataset) Exclude(cond Value) *Dataset
- func (d *Dataset) From(tables ...Value) *Dataset
- func (d *Dataset) FullJoin(table Value, cond Value) *Dataset
- func (d *Dataset) Group(cols ...Value) *Dataset
- func (d *Dataset) Having(cond Value) *Dataset
- func (d *Dataset) InnerJoin(table Value, cond Value) *Dataset
- func (d *Dataset) InsertSQL(kv ...Value) string
- func (d *Dataset) Intersect(other *Dataset) *Dataset
- func (d *Dataset) Join(table Value, cond Value) *Dataset
- func (d *Dataset) LeftJoin(table Value, cond Value) *Dataset
- func (d *Dataset) Limit(limit int) *Dataset
- func (d *Dataset) LimitOffset(limit, offset int) *Dataset
- func (d *Dataset) Offset(offset int) *Dataset
- func (d *Dataset) Order(terms ...Value) *Dataset
- func (d *Dataset) Reverse() *Dataset
- func (d *Dataset) RightJoin(table Value, cond Value) *Dataset
- func (d *Dataset) SQL() string
- func (d *Dataset) Select(cols ...Value) *Dataset
- func (d *Dataset) SelectSQL() string
- func (d *Dataset) Union(other *Dataset) *Dataset
- func (d *Dataset) UnionAll(other *Dataset) *Dataset
- func (d *Dataset) UpdateSQL(kv ...Value) string
- func (d *Dataset) Where(cond Value) *Dataset
- type Date
- type Dialect
- type Errors
- type Executor
- type ExecutorFunc
- type Expr
- func And(conds ...Value) Expr
- func Cmp(op string, left, right Value) Expr
- func Eq(l, r Value) Expr
- func Gt(l, r Value) Expr
- func Gte(l, r Value) Expr
- func H(kv ...Value) Expr
- func In(col Value, values ...Value) Expr
- func InDataset(col Value, sub *Dataset) Expr
- func Like(col, pattern Value) Expr
- func Lt(l, r Value) Expr
- func Lte(l, r Value) Expr
- func Neq(l, r Value) Expr
- func Not(cond Value) Expr
- func Or(conds ...Value) Expr
- type FunctionCall
- type HashPair
- type Hook
- type HookType
- type Identifier
- type IdxOpt
- type Instance
- func (i *Instance) Add(name string, other *Instance) error
- func (i *Instance) AssociationDataset(name string) *Dataset
- func (i *Instance) ChangedColumns() []string
- func (i *Instance) Delete() error
- func (i *Instance) Destroy() error
- func (i *Instance) Errors() *Errors
- func (i *Instance) Get(col string) Value
- func (i *Instance) IsNew() bool
- func (i *Instance) Modified() bool
- func (i *Instance) PK() Value
- func (i *Instance) Refresh() error
- func (i *Instance) Related(name string) ([]*Instance, error)
- func (i *Instance) RelatedOne(name string) (*Instance, error)
- func (i *Instance) Remove(name string, other *Instance) error
- func (i *Instance) Save() error
- func (i *Instance) Set(col string, v Value) *Instance
- func (i *Instance) SetAll(pairs ...Value) *Instance
- func (i *Instance) Update(pairs ...Value) error
- func (i *Instance) Valid() bool
- func (i *Instance) Values() map[string]Value
- type JoinUsing
- type KeyExecutor
- type LengthOpts
- type LiteralString
- type Migration
- type ModelClass
- func (m *ModelClass) AddHook(t HookType, h Hook) *ModelClass
- func (m *ModelClass) AddValidation(fn func(*Instance)) *ModelClass
- func (m *ModelClass) AfterCreate(h Hook) *ModelClass
- func (m *ModelClass) AfterDestroy(h Hook) *ModelClass
- func (m *ModelClass) AfterSave(h Hook) *ModelClass
- func (m *ModelClass) AfterUpdate(h Hook) *ModelClass
- func (m *ModelClass) AfterValidation(h Hook) *ModelClass
- func (m *ModelClass) All() ([]*Instance, error)
- func (m *ModelClass) BeforeCreate(h Hook) *ModelClass
- func (m *ModelClass) BeforeDestroy(h Hook) *ModelClass
- func (m *ModelClass) BeforeSave(h Hook) *ModelClass
- func (m *ModelClass) BeforeUpdate(h Hook) *ModelClass
- func (m *ModelClass) BeforeValidation(h Hook) *ModelClass
- func (m *ModelClass) Columns() []string
- func (m *ModelClass) Create(pairs ...Value) (*Instance, error)
- func (m *ModelClass) Dataset() *Dataset
- func (m *ModelClass) DatasetMethod(name string) *ModelDataset
- func (m *ModelClass) DatasetModule(methods map[string]func(*Dataset) *Dataset) *ModelClass
- func (m *ModelClass) Def(name string, fn func(*Dataset) *Dataset) *ModelClass
- func (m *ModelClass) Eager(names ...string) *ModelDataset
- func (m *ModelClass) EagerGraph(names ...string) *ModelDataset
- func (m *ModelClass) First() (*Instance, error)
- func (m *ModelClass) Get(pk Value) (*Instance, error)
- func (m *ModelClass) Limit(n int) *ModelDataset
- func (m *ModelClass) Load(row map[string]Value) *Instance
- func (m *ModelClass) ManyToMany(name string, target *ModelClass, opts ...AssocOption) *ModelClass
- func (m *ModelClass) ManyToOne(name string, target *ModelClass, opts ...AssocOption) *ModelClass
- func (m *ModelClass) ModelDataset() *ModelDataset
- func (m *ModelClass) Name() string
- func (m *ModelClass) New(pairs ...Value) *Instance
- func (m *ModelClass) OneToMany(name string, target *ModelClass, opts ...AssocOption) *ModelClass
- func (m *ModelClass) OneToOne(name string, target *ModelClass, opts ...AssocOption) *ModelClass
- func (m *ModelClass) Order(terms ...Value) *ModelDataset
- func (m *ModelClass) PrimaryKey() []string
- func (m *ModelClass) SetColumns(cols ...string) *ModelClass
- func (m *ModelClass) SetName(name string) *ModelClass
- func (m *ModelClass) SetPrimaryKey(cols ...string) *ModelClass
- func (m *ModelClass) Table() string
- func (m *ModelClass) ValidatesFormat(re *regexp.Regexp, col string) *ModelClass
- func (m *ModelClass) ValidatesLength(col string, opts LengthOpts) *ModelClass
- func (m *ModelClass) ValidatesPresence(cols ...string) *ModelClass
- func (m *ModelClass) ValidatesUnique(cols ...string) *ModelClass
- func (m *ModelClass) Where(cond Value) *ModelDataset
- func (m *ModelClass) WithPK(pk Value) (*Instance, error)
- type ModelDataset
- func (md *ModelDataset) All() ([]*Instance, error)
- func (md *ModelDataset) Dataset() *Dataset
- func (md *ModelDataset) Each(fn func(*Instance) error) error
- func (md *ModelDataset) Eager(names ...string) *ModelDataset
- func (md *ModelDataset) EagerGraph(names ...string) *ModelDataset
- func (md *ModelDataset) Exclude(cond Value) *ModelDataset
- func (md *ModelDataset) First() (*Instance, error)
- func (md *ModelDataset) Limit(n int) *ModelDataset
- func (md *ModelDataset) Named(name string) *ModelDataset
- func (md *ModelDataset) Order(terms ...Value) *ModelDataset
- func (md *ModelDataset) SQL() string
- func (md *ModelDataset) Where(cond Value) *ModelDataset
- type OrderedExpr
- type QualifiedIdentifier
- type TableBuilder
- func (t *TableBuilder) Bignum(name string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) Bool(name string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) Column(c Column) *TableBuilder
- func (t *TableBuilder) Date(name string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) DateTime(name string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) Float(name string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) ForeignKey(name, table string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) Index(cols []string, opts ...IdxOpt) *TableBuilder
- func (t *TableBuilder) Integer(name string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) Numeric(name string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) PrimaryKey(name string) *TableBuilder
- func (t *TableBuilder) Raw(name, sqlType string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) String(name string, opts ...ColOpt) *TableBuilder
- func (t *TableBuilder) Time(name string, opts ...ColOpt) *TableBuilder
- type ValidationFailed
- type Value
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AliasedExpr ¶
AliasedExpr is `expr AS alias` — Sequel.as(expr, :alias).
func As ¶
func As(expr Value, alias string) AliasedExpr
As builds an AliasedExpr (expr AS alias). The expr argument may be a bare value (column name via Ident, or a literal) or any Expr.
type AlterBuilder ¶
type AlterBuilder struct {
// contains filtered or unexported fields
}
AlterBuilder accumulates alterations to a table.
func (*AlterBuilder) AddColumn ¶
func (a *AlterBuilder) AddColumn(c Column) *AlterBuilder
AddColumn adds an ADD COLUMN operation.
func (*AlterBuilder) AddIndex ¶
func (a *AlterBuilder) AddIndex(cols []string, opts ...IdxOpt) *AlterBuilder
AddIndex adds a CREATE INDEX operation (emitted as its own statement).
func (*AlterBuilder) DropColumn ¶
func (a *AlterBuilder) DropColumn(name string) *AlterBuilder
DropColumn adds a DROP COLUMN operation.
func (*AlterBuilder) DropIndex ¶
func (a *AlterBuilder) DropIndex(cols []string, opts ...IdxOpt) *AlterBuilder
DropIndex adds a DROP INDEX operation.
func (*AlterBuilder) RenameColumn ¶
func (a *AlterBuilder) RenameColumn(from, to string) *AlterBuilder
RenameColumn adds a RENAME COLUMN operation.
func (*AlterBuilder) SetColumnDefault ¶
func (a *AlterBuilder) SetColumnDefault(name string, v Value) *AlterBuilder
SetColumnDefault adds an ALTER COLUMN ... SET DEFAULT operation.
func (*AlterBuilder) SetColumnType ¶
func (a *AlterBuilder) SetColumnType(name string, ct ColumnType) *AlterBuilder
SetColumnType adds an ALTER COLUMN ... TYPE operation.
type AssocOption ¶
type AssocOption func(*association)
AssocOption configures a declared association.
func Key ¶
func Key(col string) AssocOption
Key sets the foreign-key column for a one_to_many/one_to_one (on the target) or many_to_one (on this model). Defaults follow Sequel's conventions when unset.
func LeftKey ¶
func LeftKey(col string) AssocOption
LeftKey sets the many_to_many join-table column referencing this model.
func RightKey ¶
func RightKey(col string) AssocOption
RightKey sets the many_to_many join-table column referencing the target.
type AssocType ¶
type AssocType int
AssocType names one of Sequel's four core association kinds.
const ( // OneToManyType is a has-many: the target rows carry a foreign key back to // this model's primary key. OneToManyType AssocType = iota // ManyToOneType is a belongs-to: this model carries the foreign key to the // target's primary key. ManyToOneType // OneToOneType is a has-one: like one_to_many but yielding a single row. OneToOneType // ManyToManyType is a has-and-belongs-to-many through a join table. ManyToManyType )
type Blob ¶
type Blob []byte
Blob is a binary string literal — Ruby's Sequel.blob. Each dialect renders it differently (default: hex-escaped C string; sqlite: X'..'; postgres: \\ooo).
type ColOpt ¶
type ColOpt func(*Column)
ColOpt configures a Column.
func DefaultVal ¶
DefaultVal sets a column DEFAULT. (Named DefaultVal to avoid colliding with the Default dialect constant.)
type Column ¶
type Column struct {
Name string
Type ColumnType
RawType string // used when Type == TypeRaw
Size int // varchar(N) / numeric first arg; 0 = unset
Size2 int // numeric second arg (scale)
HasSize bool // Size/Size2 supplied
Text bool // String with text:true
NotNull bool
Unique bool
HasDefault bool
Default Value
PrimaryKey bool // integer PRIMARY KEY AUTOINCREMENT / IDENTITY
// Foreign-key target (empty = not a foreign key).
References string
OnDelete string // e.g. "CASCADE"; empty = none
}
Column describes one column in a CREATE TABLE / ADD COLUMN.
type ColumnType ¶
type ColumnType int
ColumnType names an abstract Sequel column type (the DSL's String, Integer, …). Each dialect maps it to a concrete SQL type via [Dialect.typeName].
const ( // TypeString is Sequel's String: varchar(255) by default, `text` when // Text is set (and, under Postgres, unconditionally `text`). TypeString ColumnType = iota TypeInteger TypeBignum TypeFloat TypeNumeric TypeBool TypeDate TypeDateTime TypeTime // TypeRaw carries a verbatim SQL type in Column.RawType. TypeRaw )
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database is the entry point — the Go equivalent of a Sequel::Database. It carries the SQL dialect (which drives identifier quoting and value literalization) and the host Executor seam. Construct one with Connect or Mock, then index it with Database.T (the Go form of DB[:table]) to obtain datasets.
func Connect ¶
Connect builds a Database for a named dialect ("default", "sqlite", "postgres") wired to the given executor. A nil executor is allowed: the database can still generate SQL, but Dataset execution and DDL execution will collect SQL into the log instead of running it.
func Mock ¶
Mock builds an executor-less Database for a dialect, mirroring `Sequel.mock(host: ...)`. It generates SQL and logs DDL but runs nothing.
func (*Database) AlterTable ¶
func (db *Database) AlterTable(table string, fn func(*AlterBuilder)) []string
AlterTable builds and emits ALTER TABLE statements via fn.
func (*Database) AlterTableSQL ¶
func (db *Database) AlterTableSQL(a *AlterBuilder) []string
AlterTableSQL renders one statement per accumulated alteration, in order.
func (*Database) CreateTable ¶
func (db *Database) CreateTable(table string, fn func(*TableBuilder)) []string
CreateTable builds a table via fn, generates the SQL, and either runs it through the executor or (executor-less) appends it to the SQL log. It returns the generated statements.
func (*Database) CreateTableSQL ¶
func (db *Database) CreateTableSQL(t *TableBuilder) []string
CreateTableSQL renders the CREATE TABLE statement plus any CREATE INDEX statements the builder accumulated, in order.
func (*Database) Dataset ¶
Dataset returns an empty dataset bound to this database (no FROM), a base for compound queries or fully-literal SQL.
func (*Database) DropTableSQL ¶
DropTableSQL renders a DROP TABLE for each named table (Sequel emits one statement per table).
func (*Database) Model ¶
func (db *Database) Model(table string) *ModelClass
Model defines a model class over a named table — the Go form of Sequel::Model(:items) using this database.
type Dataset ¶
type Dataset struct {
// contains filtered or unexported fields
}
Dataset is an immutable, chainable query builder. Every filtering/ordering method returns a new Dataset that shares nothing mutable with the receiver, so datasets are safe to store and branch — matching Sequel's frozen datasets.
func (*Dataset) DeleteSQL ¶
DeleteSQL returns a DELETE statement, applying the dataset's WHERE clause.
func (*Dataset) InsertSQL ¶
InsertSQL returns an INSERT statement from alternating column/value pairs, preserving their order (Sequel iterates the hash in insertion order).
func (*Dataset) Join ¶
Join / InnerJoin add an INNER JOIN. cond may be a hash of {joinColumn => sourceColumn} (via H or JoinHash), a []string USING list, or any boolean Expr used verbatim as the ON condition.
func (*Dataset) LimitOffset ¶
LimitOffset sets both LIMIT and OFFSET.
func (*Dataset) Select ¶
Select sets the SELECT column list. Columns are coerced: strings become identifiers, other Exprs are used directly.
type Date ¶
Date is a calendar date with no time-of-day — Ruby's Date. It literalizes to 'YYYY-MM-DD'. (A time.Time literalizes to a full timestamp.)
type Dialect ¶
type Dialect int
Dialect names a SQL dialect. It selects identifier quoting and value literalization so the emitted SQL is byte-faithful to what the matching Sequel adapter produces.
const ( // Default is Sequel's base dialect (the abstract Database). Identifiers are // unquoted; booleans literalize to IS TRUE / IS FALSE; blobs to a // hex-escaped C string. Default Dialect = iota // SQLite mirrors Sequel's sqlite adapter: backtick-quoted identifiers, // booleans as 't'/'f', blobs as X'..'. SQLite // Postgres mirrors Sequel's postgres adapter: double-quote-quoted // identifiers, booleans as true/false, blobs as '\\ooo' octal escapes. Postgres )
func DialectByName ¶
DialectByName maps a Sequel adapter/host name to a Dialect. Unknown names map to Default, matching how Sequel's mock adapter degrades to the base SQL.
type Errors ¶
type Errors struct {
// contains filtered or unexported fields
}
Errors collects validation failures keyed by column, in insertion order — the Go equivalent of Sequel::Model::Errors.
func (*Errors) FullMessages ¶
FullMessages returns "<column> <message>" for every error, in column then message order — Sequel's errors.full_messages.
type Executor ¶
Executor is the host seam through which generated SQL actually runs. A Database holds one; the host (go-embedded-ruby) wires it to a driver such as go-ruby-sqlite3 or go-ruby-pg. This library never runs SQL itself — it only generates the text and hands it to Execute.
Execute runs a statement and returns its result rows. Each row is a map from column name to value in the small Value model. A statement with no result set (INSERT/UPDATE/DDL) returns a nil or empty slice and a nil error.
type ExecutorFunc ¶
ExecutorFunc adapts a plain function to the Executor interface.
type Expr ¶
type Expr interface {
// contains filtered or unexported methods
}
Expr is a node in Sequel's expression tree — the Go equivalent of the objects under Sequel::SQL. Every builder helper (Ident, Lit, BinaryOp, Function, …) produces an Expr, and Expr values compose via And/Or/Not and the comparison helpers to form the tree a Dataset literalizes into SQL.
func Cmp ¶
Cmp builds a comparison node for the given operator (=, !=, >, <, >=, <=). left is coerced as a column, right as a literal value.
func H ¶
H builds an ordered hash condition from alternating key/value pairs, matching Ruby's insertion-ordered Hash. It is the Go form of `where(a: 1, b: 2)`:
H("a", 1, "b", 2) -> ((a = 1) AND (b = 2))
A nil value becomes IS NULL; a []Value value becomes IN (...); a *Dataset becomes IN (sub-select).
type FunctionCall ¶
FunctionCall is a SQL function invocation — Sequel.function(:name, args...).
func Function ¶
func Function(name string, args ...Value) FunctionCall
Function builds a function call. Each argument is coerced: strings become identifiers (column references), other values become literals.
func (FunctionCall) As ¶
func (f FunctionCall) As(alias string) AliasedExpr
As aliases a function call.
type HashPair ¶
HashPair is one key/value of a hash condition — {key => value}. Key is the column (a string name or an Expr), Value is the literal compared with = (or IS NULL / IN for nil and lists).
type Hook ¶
Hook is a lifecycle callback. Returning a non-nil error aborts the operation (the Go analogue of a Sequel hook returning false / raising HookFailed).
type HookType ¶
type HookType int
HookType names a model lifecycle hook position.
const ( // BeforeValidation runs before validation. BeforeValidation HookType = iota // AfterValidation runs after validation. AfterValidation // BeforeSave runs before any insert or update. BeforeSave // AfterSave runs after any insert or update. AfterSave // BeforeCreate runs before an insert. BeforeCreate // AfterCreate runs after an insert. AfterCreate // BeforeUpdate runs before an update. BeforeUpdate // AfterUpdate runs after an update. AfterUpdate // BeforeDestroy runs before a destroy. BeforeDestroy // AfterDestroy runs after a destroy. AfterDestroy )
type Identifier ¶
type Identifier struct{ Value string }
Identifier is an unqualified column or table name — Sequel[:col]. It is quoted per the dialect when quoting is enabled.
func Ident ¶
func Ident(name string) Identifier
Ident builds an Identifier. It is the Go form of Sequel[:name].
func (Identifier) As ¶
func (i Identifier) As(alias string) AliasedExpr
As aliases this identifier — Sequel[:x].as(:y).
func (Identifier) Col ¶
func (i Identifier) Col(col string) QualifiedIdentifier
Col returns a QualifiedIdentifier for this table's column — the Go form of Sequel[:table][:col].
type Instance ¶
type Instance struct {
// contains filtered or unexported fields
}
Instance is a model row object — the Go equivalent of a Sequel::Model instance. It holds the row values, tracks which columns changed since load, records whether it is a new (unsaved) record, and carries the validation errors and association cache.
func (*Instance) Add ¶
Add associates another instance with this one — Sequel's add_<name>. For one_to_many/one_to_one it sets the target's foreign key to this row's pk and saves the target; for many_to_many it inserts a join-table row.
func (*Instance) AssociationDataset ¶
AssociationDataset returns the dataset for a declared association on this instance — the Go form of Sequel's <name>_dataset. The generated SQL matches the gem's byte-for-byte.
func (*Instance) ChangedColumns ¶
ChangedColumns returns the columns modified since load/save, in set order — Sequel's changed_columns.
func (*Instance) Delete ¶
Delete removes the row with a DELETE keyed on the primary key. It runs no hooks — Sequel's Model#delete.
func (*Instance) Destroy ¶
Destroy removes the row, running the before/after destroy hooks — Sequel's Model#destroy.
func (*Instance) Modified ¶
Modified reports whether any column changed since load/save — Sequel's modified?.
func (*Instance) Refresh ¶
Refresh reloads the instance's columns from the database by primary key, clearing dirty state — Sequel's Model#refresh.
func (*Instance) Related ¶
Related returns the associated instances for a to-many association (or the single-element/empty slice for a to-one), loading and caching on first use — the Go form of Sequel's association accessor.
func (*Instance) RelatedOne ¶
RelatedOne returns the single associated instance for a many_to_one/one_to_one association (or nil), loading and caching on first use.
func (*Instance) Remove ¶
Remove dissociates another instance — Sequel's remove_<name>. For one_to_many/one_to_one it nils the target's foreign key and saves; for many_to_many it deletes the join-table row.
func (*Instance) Save ¶
Save persists the instance: an INSERT for a new record, or an UPDATE of the changed columns for an existing one. It runs validation and the save/create or save/update hooks in Sequel's order. A new record with no columns set, or an existing record with no changes, performs no DML.
func (*Instance) Set ¶
Set assigns a column, marking it changed (dirty) unless the value is identical to the current one — mirroring Sequel only flagging real changes.
type KeyExecutor ¶
type KeyExecutor interface {
// ExecuteInsert runs an INSERT and returns the generated primary key value.
ExecuteInsert(sql string) (Value, error)
}
KeyExecutor is an optional capability an Executor may implement so a Model insert can learn the freshly inserted row's primary key. It mirrors how a Sequel adapter's dataset #insert returns the last insert id. When the wired executor does not implement it, Instance.Save on a new record runs the INSERT through Executor.Execute and expects the caller to have supplied the primary key explicitly (auto-increment recovery needs this seam).
type LengthOpts ¶
type LengthOpts struct {
Min int // minimum length (0 = no minimum)
Max int // maximum length (0 = no maximum)
Is int // exact length; only applied when HasIs is set
HasIs bool
}
LengthOpts configures a length validation. Set the bound(s) that apply; a zero field is ignored except Is, which is applied when >= 0 via HasIs.
type LiteralString ¶
type LiteralString struct{ Value string }
LiteralString is raw, already-formed SQL — Sequel.lit("a = 1"). It is emitted verbatim.
func Lit ¶
func Lit(sql string) LiteralString
Lit builds a LiteralString, emitted verbatim into the SQL.
type Migration ¶
Migration is a reversible schema change — the Go equivalent of Sequel.migration { up {...}; down {...} }. Up and Down each receive the target Database and issue CreateTable/AlterTable/DropTable against it.
type ModelClass ¶
type ModelClass struct {
// contains filtered or unexported fields
}
ModelClass is a model definition bound to a table/dataset — the Go equivalent of a subclass of Sequel::Model. It is mutable at definition time (columns, associations, validations, hooks are registered onto it) and then used to build datasets and instantiate rows.
func Model ¶
func Model(ds *Dataset) *ModelClass
Model defines a model class over a dataset — the Go form of Sequel::Model(DB[:items]). The dataset carries the database (and thus the dialect and executor). The primary key defaults to "id".
func (*ModelClass) AddHook ¶
func (m *ModelClass) AddHook(t HookType, h Hook) *ModelClass
AddHook registers a lifecycle hook at the given position.
func (*ModelClass) AddValidation ¶
func (m *ModelClass) AddValidation(fn func(*Instance)) *ModelClass
AddValidation registers a custom validation callback — the Go form of overriding Sequel's #validate. It runs after the declarative validators.
func (*ModelClass) AfterCreate ¶
func (m *ModelClass) AfterCreate(h Hook) *ModelClass
AfterCreate registers an after-create hook.
func (*ModelClass) AfterDestroy ¶
func (m *ModelClass) AfterDestroy(h Hook) *ModelClass
AfterDestroy registers an after-destroy hook.
func (*ModelClass) AfterSave ¶
func (m *ModelClass) AfterSave(h Hook) *ModelClass
AfterSave registers an after-save hook.
func (*ModelClass) AfterUpdate ¶
func (m *ModelClass) AfterUpdate(h Hook) *ModelClass
AfterUpdate registers an after-update hook.
func (*ModelClass) AfterValidation ¶
func (m *ModelClass) AfterValidation(h Hook) *ModelClass
AfterValidation registers an after-validation hook.
func (*ModelClass) All ¶
func (m *ModelClass) All() ([]*Instance, error)
All returns every row as instances — Sequel's Model.all.
func (*ModelClass) BeforeCreate ¶
func (m *ModelClass) BeforeCreate(h Hook) *ModelClass
BeforeCreate registers a before-create hook.
func (*ModelClass) BeforeDestroy ¶
func (m *ModelClass) BeforeDestroy(h Hook) *ModelClass
BeforeDestroy registers a before-destroy hook.
func (*ModelClass) BeforeSave ¶
func (m *ModelClass) BeforeSave(h Hook) *ModelClass
BeforeSave registers a before-save hook.
func (*ModelClass) BeforeUpdate ¶
func (m *ModelClass) BeforeUpdate(h Hook) *ModelClass
BeforeUpdate registers a before-update hook.
func (*ModelClass) BeforeValidation ¶
func (m *ModelClass) BeforeValidation(h Hook) *ModelClass
BeforeValidation registers a before-validation hook.
func (*ModelClass) Columns ¶
func (m *ModelClass) Columns() []string
Columns returns the model's known columns.
func (*ModelClass) Create ¶
func (m *ModelClass) Create(pairs ...Value) (*Instance, error)
Create builds and saves a new instance in one call — Model.create(col: v).
func (*ModelClass) Dataset ¶
func (m *ModelClass) Dataset() *Dataset
Dataset returns the class's base dataset — the Go form of Model.dataset.
func (*ModelClass) DatasetMethod ¶
func (m *ModelClass) DatasetMethod(name string) *ModelDataset
DatasetMethod applies a registered named dataset method to the base dataset.
func (*ModelClass) DatasetModule ¶
func (m *ModelClass) DatasetModule(methods map[string]func(*Dataset) *Dataset) *ModelClass
DatasetModule registers named dataset methods in one call — the Go form of dataset_module { def young; where{...}; end }. Each entry maps a name to a dataset transform. Invoke a registered method via Model.DatasetMethod(name) or modelDataset.Named(name).
func (*ModelClass) Def ¶
func (m *ModelClass) Def(name string, fn func(*Dataset) *Dataset) *ModelClass
Def registers a single named dataset method — a convenience over DatasetModule.
func (*ModelClass) Eager ¶
func (m *ModelClass) Eager(names ...string) *ModelDataset
Eager returns a model dataset that will eager-load the named associations — Model.eager.
func (*ModelClass) EagerGraph ¶
func (m *ModelClass) EagerGraph(names ...string) *ModelDataset
EagerGraph returns a model dataset that will eager-load via a LEFT OUTER JOIN — Model.eager_graph.
func (*ModelClass) First ¶
func (m *ModelClass) First() (*Instance, error)
First returns the first row, or nil — Sequel's Model.first.
func (*ModelClass) Get ¶
func (m *ModelClass) Get(pk Value) (*Instance, error)
Get is an alias for WithPK — the Go form of Model[pk].
func (*ModelClass) Limit ¶
func (m *ModelClass) Limit(n int) *ModelDataset
Limit returns a model dataset limited to n rows — Model.limit.
func (*ModelClass) Load ¶
func (m *ModelClass) Load(row map[string]Value) *Instance
Load builds an existing (persisted) instance directly from a row, marking it not-new and clean — the Go form of Model.load(row).
func (*ModelClass) ManyToMany ¶
func (m *ModelClass) ManyToMany(name string, target *ModelClass, opts ...AssocOption) *ModelClass
ManyToMany declares a has-and-belongs-to-many association through a join table. Defaults: join table = the two table names joined by "_" in sorted order, left key = "<thismodel>_id", right key = "<target>_id".
func (*ModelClass) ManyToOne ¶
func (m *ModelClass) ManyToOne(name string, target *ModelClass, opts ...AssocOption) *ModelClass
ManyToOne declares a belongs-to association: this model carries the foreign key (default "<name>_id") to the target's primary key.
func (*ModelClass) ModelDataset ¶
func (m *ModelClass) ModelDataset() *ModelDataset
ModelDataset returns the class's base model dataset.
func (*ModelClass) Name ¶
func (m *ModelClass) Name() string
Name returns the model's name (defaults to the table name); used only for error-message prefixes and diagnostics.
func (*ModelClass) New ¶
func (m *ModelClass) New(pairs ...Value) *Instance
New builds a new (unsaved) instance from alternating column/value pairs, in order — the Go form of Model.new(col: v, ...).
func (*ModelClass) OneToMany ¶
func (m *ModelClass) OneToMany(name string, target *ModelClass, opts ...AssocOption) *ModelClass
OneToMany declares a has-many association: the target rows carry a foreign key (default "<thismodel>_id") back to this model's primary key.
func (*ModelClass) OneToOne ¶
func (m *ModelClass) OneToOne(name string, target *ModelClass, opts ...AssocOption) *ModelClass
OneToOne declares a has-one association: like one_to_many but a single row.
func (*ModelClass) Order ¶
func (m *ModelClass) Order(terms ...Value) *ModelDataset
Order returns a model dataset ordered by the given terms — Model.order.
func (*ModelClass) PrimaryKey ¶
func (m *ModelClass) PrimaryKey() []string
PrimaryKey returns the primary-key column(s).
func (*ModelClass) SetColumns ¶
func (m *ModelClass) SetColumns(cols ...string) *ModelClass
SetColumns declares the model's columns. Mirrors setting a model's columns in Sequel specs so no live schema introspection is needed.
func (*ModelClass) SetName ¶
func (m *ModelClass) SetName(name string) *ModelClass
SetName overrides the model name.
func (*ModelClass) SetPrimaryKey ¶
func (m *ModelClass) SetPrimaryKey(cols ...string) *ModelClass
SetPrimaryKey sets the primary-key column(s) — Sequel's set_primary_key.
func (*ModelClass) Table ¶
func (m *ModelClass) Table() string
Table returns the model's table name.
func (*ModelClass) ValidatesFormat ¶
func (m *ModelClass) ValidatesFormat(re *regexp.Regexp, col string) *ModelClass
ValidatesFormat requires a column to match a regexp — Sequel's validates_format. Message: "is invalid".
func (*ModelClass) ValidatesLength ¶
func (m *ModelClass) ValidatesLength(col string, opts LengthOpts) *ModelClass
ValidatesLength checks a column's string length against the options — Sequel's validates_{min,max,exact}_length. Messages mirror the gem: "is shorter than N characters", "is longer than N characters", "is not N characters".
func (*ModelClass) ValidatesPresence ¶
func (m *ModelClass) ValidatesPresence(cols ...string) *ModelClass
ValidatesPresence requires each named column to be non-nil and non-empty — Sequel's validates_presence. Message: "is not present".
func (*ModelClass) ValidatesUnique ¶
func (m *ModelClass) ValidatesUnique(cols ...string) *ModelClass
ValidatesUnique requires the value(s) of the named column(s) to be unique in the table — Sequel's validates_unique. It runs "SELECT 1 AS one FROM t WHERE (...) LIMIT 1" (excluding the current row by primary key for a persisted record) and, if a row exists, adds "is already taken". For a persisted record the check is skipped when none of the columns changed, matching the gem. Message: "is already taken".
func (*ModelClass) Where ¶
func (m *ModelClass) Where(cond Value) *ModelDataset
Where returns a model dataset filtered by cond — Sequel's Model.where.
type ModelDataset ¶
type ModelDataset struct {
// contains filtered or unexported fields
}
ModelDataset is a dataset whose rows are materialised as model instances — the Go equivalent of a Sequel model dataset. Filtering/ordering methods return a new ModelDataset; All/First/Each execute and yield instances.
func (*ModelDataset) All ¶
func (md *ModelDataset) All() ([]*Instance, error)
All executes the dataset and returns instances, applying any eager loading.
func (*ModelDataset) Dataset ¶
func (md *ModelDataset) Dataset() *Dataset
Dataset returns the underlying plain dataset.
func (*ModelDataset) Each ¶
func (md *ModelDataset) Each(fn func(*Instance) error) error
Each executes the dataset and calls fn for each instance until fn errors.
func (*ModelDataset) Eager ¶
func (md *ModelDataset) Eager(names ...string) *ModelDataset
Eager marks associations for batch eager loading.
func (*ModelDataset) EagerGraph ¶
func (md *ModelDataset) EagerGraph(names ...string) *ModelDataset
EagerGraph marks associations for LEFT OUTER JOIN eager loading.
func (*ModelDataset) Exclude ¶
func (md *ModelDataset) Exclude(cond Value) *ModelDataset
Exclude negates a filter on the model dataset.
func (*ModelDataset) First ¶
func (md *ModelDataset) First() (*Instance, error)
First executes the dataset with LIMIT 1 and returns the first instance or nil.
func (*ModelDataset) Limit ¶
func (md *ModelDataset) Limit(n int) *ModelDataset
Limit limits the model dataset.
func (*ModelDataset) Named ¶
func (md *ModelDataset) Named(name string) *ModelDataset
Named applies a named dataset method registered via DatasetModule/Def.
func (*ModelDataset) Order ¶
func (md *ModelDataset) Order(terms ...Value) *ModelDataset
Order orders the model dataset.
func (*ModelDataset) SQL ¶
func (md *ModelDataset) SQL() string
SQL returns the SELECT SQL of the underlying dataset.
func (*ModelDataset) Where ¶
func (md *ModelDataset) Where(cond Value) *ModelDataset
Where filters the model dataset.
type OrderedExpr ¶
OrderedExpr is an ORDER BY term with a direction — Sequel.asc/desc(expr).
type QualifiedIdentifier ¶
QualifiedIdentifier is a table-qualified column — Sequel[:t][:c] -> t.c.
func Qualify ¶
func Qualify(table, column string) QualifiedIdentifier
Qualify builds a QualifiedIdentifier (table.column).
func (QualifiedIdentifier) As ¶
func (q QualifiedIdentifier) As(alias string) AliasedExpr
As aliases this qualified identifier.
type TableBuilder ¶
type TableBuilder struct {
// contains filtered or unexported fields
}
TableBuilder accumulates the columns and indexes of a CREATE TABLE. Obtain one from Database.CreateTable, chain the column helpers, then read the SQL back via Database.SQLs (or let CreateTable run it through the executor).
func (*TableBuilder) Bignum ¶
func (t *TableBuilder) Bignum(name string, opts ...ColOpt) *TableBuilder
func (*TableBuilder) Bool ¶
func (t *TableBuilder) Bool(name string, opts ...ColOpt) *TableBuilder
func (*TableBuilder) Column ¶
func (t *TableBuilder) Column(c Column) *TableBuilder
Column adds a fully-specified column.
func (*TableBuilder) Date ¶
func (t *TableBuilder) Date(name string, opts ...ColOpt) *TableBuilder
func (*TableBuilder) DateTime ¶
func (t *TableBuilder) DateTime(name string, opts ...ColOpt) *TableBuilder
func (*TableBuilder) Float ¶
func (t *TableBuilder) Float(name string, opts ...ColOpt) *TableBuilder
func (*TableBuilder) ForeignKey ¶
func (t *TableBuilder) ForeignKey(name, table string, opts ...ColOpt) *TableBuilder
ForeignKey adds an integer foreign-key column referencing another table.
func (*TableBuilder) Index ¶
func (t *TableBuilder) Index(cols []string, opts ...IdxOpt) *TableBuilder
Index adds a (possibly unique/named) index over one or more columns.
func (*TableBuilder) Integer ¶
func (t *TableBuilder) Integer(name string, opts ...ColOpt) *TableBuilder
Integer/Bignum/Float/Numeric/Bool/Date/DateTime/Time add typed columns.
func (*TableBuilder) Numeric ¶
func (t *TableBuilder) Numeric(name string, opts ...ColOpt) *TableBuilder
func (*TableBuilder) PrimaryKey ¶
func (t *TableBuilder) PrimaryKey(name string) *TableBuilder
PrimaryKey adds an auto-incrementing integer primary key column.
func (*TableBuilder) Raw ¶
func (t *TableBuilder) Raw(name, sqlType string, opts ...ColOpt) *TableBuilder
Raw adds a column with a verbatim SQL type (Sequel's column :n, 'blob').
func (*TableBuilder) String ¶
func (t *TableBuilder) String(name string, opts ...ColOpt) *TableBuilder
String adds a String column. Pass a non-nil opts to set size/text/null/etc.
func (*TableBuilder) Time ¶
func (t *TableBuilder) Time(name string, opts ...ColOpt) *TableBuilder
type ValidationFailed ¶
type ValidationFailed struct{ Errors *Errors }
ValidationFailed is returned by Save when validation fails.
func (*ValidationFailed) Error ¶
func (v *ValidationFailed) Error() string
type Value ¶
type Value = any
Value is a Ruby value in the small model this library literalizes. It mirrors the value model the host (go-embedded-ruby) maps to and from its own objects. The supported dynamic types are:
nil -> NULL bool -> the dialect's boolean literal int, int64 -> integer literal *big.Int -> integer literal float64 -> float literal string -> a quoted, escaped string literal []byte, Blob -> the dialect's blob literal time.Time -> a quoted timestamp literal Date -> a quoted date literal Expr (Expression) -> literalized as SQL (idents, functions, sub-selects…) *Dataset -> a parenthesised sub-select []Value -> a parenthesised, comma-joined list (IN (...))
