sequel

package module
v0.0.0-...-d327833 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: BSD-3-Clause Imports: 8 Imported by: 0

README

go-ruby-sequel/sequel

sequel — go-ruby-sequel

Docs License Go Coverage

A pure-Go (no cgo) reimplementation of the deterministic SQL-generation core of Ruby's Sequel toolkit (the sequel gem) — the chainable Dataset query builder, the expression DSL, the schema DSL, and the per-dialect literalization/identifier-quoting that turn a chain of DB[:table].where(…).order(…) calls into a SQL string. It emits the exact bytes the gem emits, across the default, sqlite and postgres dialects — without any Ruby runtime and without a database.

It is the SQL-toolkit backend for go-embedded-ruby, but is a standalone, reusable module — a sibling of go-ruby-regexp (the Onigmo engine) and go-ruby-erb (the ERB compiler).

What it is — and isn't. Turning a dataset/schema DSL chain into a SQL string is fully deterministic and needs no interpreter and no database, 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. The Model (active-record) layer sits on this seam — see below.

Features

Faithful port of Sequel's SQL generation, validated byte-for-byte against the sequel gem's mock adapter on every supported platform:

  • Dataset query builder — immutable, chainable datasets: Select, Where (hash / comparison / list / sub-select / raw literal), Exclude, Order / Reverse, Limit / LimitOffset / Offset, Distinct, Group / Having, From (multi-source, aliased, sub-select), and InsertSQL / UpdateSQL / DeleteSQL / SelectSQL.
  • JoinsJoin / InnerJoin / LeftJoin / RightJoin / FullJoin / CrossJoin, with hash {joinCol ⇒ srcCol} conditions (auto-qualified), USING (…) lists, and arbitrary Expr ON conditions.
  • Compound queriesUnion / UnionAll / Intersect / Except, wrapped as SELECT * FROM (a OP b) AS t1 exactly like the gem.
  • Expression DSL — identifiers (Ident, Qualify), literals (Lit), functions (Function), comparisons (Eq/Neq/Gt/Lt/Gte/Lte), Like, In / InDataset, And / Or / Not, arithmetic (Arith), and aliasing (As).
  • Per-dialect literalization — identifier quoting (unquoted / ` / "…", with quote-doubling), string escaping (single-quote doubling), booleans (IS TRUE/IS FALSE vs 't'/'f'), blobs (hex string / X'..' / \ooo octal), floats (Ruby Float#to_s), dates, and timestamps.
  • Schema DSLCreateTable (typed columns, primary_key, foreign_key, defaults, not-null/unique, indexes), AlterTable (add/drop/rename column, set default/type, add/drop index), DropTable, and a reversible Migration up/down pair — with per-dialect type mapping (Postgres IDENTITY, SQLite NOT NULL PRIMARY KEY + paren-wrapped defaults, String → text, …).
  • Adapter seamExecutor / ExecutorFunc, wired by the host; SQL runs through it or, executor-less, is collected for inspection (mirrors the gem's mock #sqls).
  • Model (active-record) layerSequel::Model over a table/dataset: instance CRUD (Create/Save/Update/Delete/Destroy/Refresh), dataset-backed finders (Get/WithPK/First/All/Where/Order/Limit), the four core associations (OneToMany/ManyToOne/OneToOne/ManyToMany) with lazy accessors, Add/Remove modifiers, and both eager strategies (Eager batch IN (…) + EagerGraph LEFT OUTER JOIN), validations (ValidatesPresence/ValidatesUnique/ValidatesFormat/ValidatesLength, Valid + Errors), before/after hooks (create/update/save/destroy/ validation), dirty tracking (ChangedColumns/Modified), and named dataset methods (DatasetModule/Def).

CGO-free, dependency-free, 100% test coverage, gofmt + go vet clean, and green across the six 64-bit Go targets (amd64, arm64, riscv64, loong64, ppc64le, s390x).

Install

go get github.com/go-ruby-sequel/sequel

Usage

package main

import (
	"fmt"

	"github.com/go-ruby-sequel/sequel"
)

func main() {
	db := sequel.Mock("postgres") // or Connect("postgres", executor)

	ds := db.T("items").
		Where(sequel.H("category", "books")).
		Where(sequel.Gt("price", 10)).
		Order(sequel.Desc("price")).
		Limit(5)

	fmt.Println(ds.SelectSQL())
	// SELECT * FROM "items" WHERE (("category" = 'books') AND ("price" > 10))
	//   ORDER BY "price" DESC LIMIT 5

	fmt.Println(db.T("items").InsertSQL("name", "Go", "price", 42))
	// INSERT INTO "items" ("name", "price") VALUES ('Go', 42)

	db.CreateTable("users", func(t *sequel.TableBuilder) {
		t.PrimaryKey("id")
		t.String("name", sequel.NotNull())
		t.Integer("age")
		t.Index([]string{"name"}, sequel.UniqueIndex())
	})
	for _, s := range db.SQLs() {
		fmt.Println(s)
	}
	// CREATE TABLE "users" ("id" integer GENERATED BY DEFAULT AS IDENTITY
	//   PRIMARY KEY, "name" text NOT NULL, "age" integer)
	// CREATE UNIQUE INDEX "users_name_index" ON "users" ("name")
}

Dialects

Mock / Connect take a dialect name; unknown names degrade to the base SQL:

name(s) quoting booleans blobs
default none IS TRUE/IS FALSE 'bytes'
sqlite `x` 't' / 'f' X'..'
postgres / postgresql / pg "x" IS TRUE/IS FALSE '\ooo'

Adapter seam & Model

Execution goes through the Executor the host wires in:

type Executor interface {
	Execute(sql string) ([]map[string]any, error)
}
db := sequel.Connect("sqlite", myDriver) // rows, _ := db.All(db.T("items"))

An Executor may additionally implement KeyExecutor (ExecuteInsert(sql) → key) so a Model insert recovers an auto-increment primary key, mirroring a Sequel adapter's #insert returning the last id.

Model (active-record) layer

Sequel::Model is available directly on the seam above — the class builds the same SQL the gem's Model builds and maps the executor's rows into instances:

db := sequel.Connect("sqlite", myDriver)
Artist := db.Model("artists").SetColumns("id", "name")
Album := db.Model("albums").SetColumns("id", "name", "artist_id")
Artist.OneToMany("albums", Album, sequel.Key("artist_id"))
Album.ManyToOne("artist", Artist, sequel.Key("artist_id"))
Artist.ValidatesPresence("name")

a, _ := Artist.Create("name", "Prince") // INSERT + refresh
albums, _ := a.Related("albums")        // SELECT * FROM albums WHERE (albums.artist_id = …)
loaded, _ := Artist.Where(sequel.H("name", "Prince")).Eager("albums").All()

Implemented: class definition over a table/dataset; instance CRUD (Create/Save/Update/Delete/Destroy/Refresh); finders (Get/WithPK/First/All/Where/Order/Limit); the four core associations with lazy accessors, Add/Remove, and eager Eager (batch IN) + EagerGraph (LEFT OUTER JOIN); validations (presence/unique/format/length) with an Errors object; before/after hooks (create/update/save/destroy/validation); dirty tracking (ChangedColumns/Modified); and named dataset methods (DatasetModule/Def). The association-dataset, finder, CRUD-statement and validates_unique SQL is pinned byte-for-byte to the gem's Model layer by the differential oracle.

Not included (named, not silently dropped): plugins beyond this core — single_table_inheritance, timestamps, nested_attributes, dirty (change history beyond changed_columns), serialization, association_pks, many_through_many, prepared statements, sharding, and transaction wrapping of saves (the Executor seam models a single statement, so the gem's BEGIN/COMMIT around a save is not emitted). EagerGraph implements the LEFT OUTER JOIN + row-splitting behaviour, but its per-column alias text uses a plain <assoc>_<column> scheme rather than the gem's internal aliasing.

Tests & coverage

The suite pairs deterministic, ruby-free golden vectors — which alone hold coverage at 100%, so the qemu cross-arch and Windows lanes pass the gate — with a differential oracle against the real sequel gem: each dataset and schema statement is built here and in Ruby (via the gem's mock adapter, so no database is touched) and the emitted SQL is compared byte-for-byte across the default, sqlite and postgres dialects. The oracle skips itself where ruby or the gem is absent.

COVERPKG=$(go list ./... | paste -sd, -)
go test -race -coverpkg="$COVERPKG" -coverprofile=cover.out ./...
go tool cover -func=cover.out | tail -1   # 100.0%

License

BSD-3-Clause — see LICENSE. Copyright the go-ruby-sequel/sequel authors.

WebAssembly

Being pure Go (CGO=0), this library also compiles to WebAssembly — both GOOS=js GOARCH=wasm (browser / Node.js) and GOOS=wasip1 GOARCH=wasm (WASI). CI builds both targets on every push, alongside the six 64-bit native/qemu arches.

GOOS=js     GOARCH=wasm go build ./...   # browser / Node
GOOS=wasip1 GOARCH=wasm go build ./...   # WASI (wasmtime, wasmer, wasmedge, …)

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func Arith

func Arith(op string, left, right Value) arithOp

Arith builds an arithmetic node (op in +, -, *, /). The concrete type is returned so .As can alias it directly.

func JoinOn

func JoinOn(kv ...string) joinHash

JoinOn builds a join condition from alternating joinColumn/sourceColumn names.

Types

type AliasedExpr

type AliasedExpr struct {
	Expr  Expr
	Alias string
}

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 JoinTable

func JoinTable(t string) AssocOption

JoinTable sets the many_to_many join table.

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

func DefaultVal(v Value) ColOpt

DefaultVal sets a column DEFAULT. (Named DefaultVal to avoid colliding with the Default dialect constant.)

func NotNull

func NotNull() ColOpt

NotNull marks a column NOT NULL.

func OnDelete

func OnDelete(action string) ColOpt

OnDelete sets a foreign key's ON DELETE action (e.g. "CASCADE").

func Precision

func Precision(p, s int) ColOpt

Precision sets a numeric(p, s) precision/scale.

func Size

func Size(n int) ColOpt

Size sets a single size argument (varchar(N)).

func Text

func Text() ColOpt

Text marks a String column as TEXT.

func Unique

func Unique() ColOpt

Unique marks a column UNIQUE.

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

func Connect(dialectName string, exec Executor) *Database

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

func Mock(dialectName string) *Database

Mock builds an executor-less Database for a dialect, mirroring `Sequel.mock(host: ...)`. It generates SQL and logs DDL but runs nothing.

func (*Database) All

func (db *Database) All(d *Dataset) ([]map[string]Value, error)

All runs a dataset's SELECT through the executor and returns its rows.

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

func (db *Database) Dataset() *Dataset

Dataset returns an empty dataset bound to this database (no FROM), a base for compound queries or fully-literal SQL.

func (*Database) Dialect

func (db *Database) Dialect() Dialect

Dialect returns the database's SQL dialect.

func (*Database) DropTable

func (db *Database) DropTable(tables ...string) []string

DropTable generates and emits DROP TABLE statements.

func (*Database) DropTableSQL

func (db *Database) DropTableSQL(tables ...string) []string

DropTableSQL renders a DROP TABLE for each named table (Sequel emits one statement per table).

func (*Database) From

func (db *Database) From(tables ...Value) *Dataset

From returns a dataset over one or more FROM sources — DB.from(:a, :b).

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.

func (*Database) Run

func (db *Database) Run(sql string) ([]map[string]Value, error)

Run executes a raw SQL statement through the wired executor.

func (*Database) SQLs

func (db *Database) SQLs() []string

SQLs returns and clears the collected DDL/statement log (mirrors the mock adapter's #sqls followed by a clear), so successive assertions see only the statements from the most recent operation.

func (*Database) T

func (db *Database) T(table string) *Dataset

T returns a dataset over the named table — the Go form of DB[:table].

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) CrossJoin

func (d *Dataset) CrossJoin(table Value) *Dataset

CrossJoin adds a CROSS JOIN (no ON condition).

func (*Dataset) DeleteSQL

func (d *Dataset) DeleteSQL() string

DeleteSQL returns a DELETE statement, applying the dataset's WHERE clause.

func (*Dataset) Distinct

func (d *Dataset) Distinct() *Dataset

Distinct marks the SELECT as DISTINCT.

func (*Dataset) Except

func (d *Dataset) Except(other *Dataset) *Dataset

Except wraps this and the other dataset in an EXCEPT sub-select.

func (*Dataset) Exclude

func (d *Dataset) Exclude(cond Value) *Dataset

Exclude adds a negated filter (Sequel's Dataset#exclude).

func (*Dataset) From

func (d *Dataset) From(tables ...Value) *Dataset

From replaces the dataset's FROM sources.

func (*Dataset) FullJoin

func (d *Dataset) FullJoin(table Value, cond Value) *Dataset

FullJoin adds a FULL JOIN.

func (*Dataset) Group

func (d *Dataset) Group(cols ...Value) *Dataset

Group sets the GROUP BY columns.

func (*Dataset) Having

func (d *Dataset) Having(cond Value) *Dataset

Having adds a HAVING condition, AND-combined with any existing ones.

func (*Dataset) InnerJoin

func (d *Dataset) InnerJoin(table Value, cond Value) *Dataset

InnerJoin is an explicit alias for Join.

func (*Dataset) InsertSQL

func (d *Dataset) InsertSQL(kv ...Value) string

InsertSQL returns an INSERT statement from alternating column/value pairs, preserving their order (Sequel iterates the hash in insertion order).

func (*Dataset) Intersect

func (d *Dataset) Intersect(other *Dataset) *Dataset

Intersect wraps this and the other dataset in an INTERSECT sub-select.

func (*Dataset) Join

func (d *Dataset) Join(table Value, cond Value) *Dataset

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) LeftJoin

func (d *Dataset) LeftJoin(table Value, cond Value) *Dataset

LeftJoin adds a LEFT JOIN.

func (*Dataset) Limit

func (d *Dataset) Limit(limit int) *Dataset

Limit sets a LIMIT (and, when offset is non-nil, an OFFSET).

func (*Dataset) LimitOffset

func (d *Dataset) LimitOffset(limit, offset int) *Dataset

LimitOffset sets both LIMIT and OFFSET.

func (*Dataset) Offset

func (d *Dataset) Offset(offset int) *Dataset

Offset sets an OFFSET with no LIMIT.

func (*Dataset) Order

func (d *Dataset) Order(terms ...Value) *Dataset

Order sets the ORDER BY terms, replacing any existing ones.

func (*Dataset) Reverse

func (d *Dataset) Reverse() *Dataset

Reverse flips every ORDER BY term's direction (Sequel's Dataset#reverse).

func (*Dataset) RightJoin

func (d *Dataset) RightJoin(table Value, cond Value) *Dataset

RightJoin adds a RIGHT JOIN.

func (*Dataset) SQL

func (d *Dataset) SQL() string

SQL is an alias for SelectSQL (Sequel's Dataset#sql).

func (*Dataset) Select

func (d *Dataset) Select(cols ...Value) *Dataset

Select sets the SELECT column list. Columns are coerced: strings become identifiers, other Exprs are used directly.

func (*Dataset) SelectSQL

func (d *Dataset) SelectSQL() string

SelectSQL returns the SELECT statement for this dataset.

func (*Dataset) Union

func (d *Dataset) Union(other *Dataset) *Dataset

Union wraps this and the other dataset in a UNION sub-select.

func (*Dataset) UnionAll

func (d *Dataset) UnionAll(other *Dataset) *Dataset

UnionAll is UNION ALL.

func (*Dataset) UpdateSQL

func (d *Dataset) UpdateSQL(kv ...Value) string

UpdateSQL returns an UPDATE statement from alternating column/value pairs, applying the dataset's WHERE clause.

func (*Dataset) Where

func (d *Dataset) Where(cond Value) *Dataset

Where adds a filter, AND-combined with any existing filters.

type Date

type Date struct {
	Year  int
	Month int
	Day   int
}

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.)

func NewDate

func NewDate(year, month, day int) Date

NewDate builds a Date.

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

func DialectByName(name string) Dialect

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.

func (Dialect) String

func (d Dialect) String() string

String returns the dialect's canonical name.

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) Add

func (e *Errors) Add(col, msg string)

Add records a message against a column.

func (*Errors) Count

func (e *Errors) Count() int

Count returns the total number of error messages.

func (*Errors) Empty

func (e *Errors) Empty() bool

Empty reports whether there are no errors.

func (*Errors) FullMessages

func (e *Errors) FullMessages() []string

FullMessages returns "<column> <message>" for every error, in column then message order — Sequel's errors.full_messages.

func (*Errors) On

func (e *Errors) On(col string) []string

On returns the messages for a column (nil when none) — Sequel's errors.on.

type Executor

type Executor interface {
	Execute(sql string) ([]map[string]Value, error)
}

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

type ExecutorFunc func(sql string) ([]map[string]Value, error)

ExecutorFunc adapts a plain function to the Executor interface.

func (ExecutorFunc) Execute

func (f ExecutorFunc) Execute(sql string) ([]map[string]Value, error)

Execute calls the underlying function.

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 And

func And(conds ...Value) Expr

And composes conditions with AND.

func Cmp

func Cmp(op string, left, right Value) Expr

Cmp builds a comparison node for the given operator (=, !=, >, <, >=, <=). left is coerced as a column, right as a literal value.

func Eq

func Eq(l, r Value) Expr

func Gt

func Gt(l, r Value) Expr

Gt/Lt/Gte/Lte/Eq/Neq are convenience comparison builders.

func Gte

func Gte(l, r Value) Expr

func H

func H(kv ...Value) Expr

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).

func In

func In(col Value, values ...Value) Expr

In builds a col IN (...) expression from an explicit value list.

func InDataset

func InDataset(col Value, sub *Dataset) Expr

InDataset builds a col IN (sub-select) expression.

func Like

func Like(col, pattern Value) Expr

Like builds a LIKE expression (col LIKE pattern ESCAPE '\').

func Lt

func Lt(l, r Value) Expr

func Lte

func Lte(l, r Value) Expr

func Neq

func Neq(l, r Value) Expr

func Not

func Not(cond Value) Expr

Not negates a condition (Sequel.~ / Dataset#exclude).

func Or

func Or(conds ...Value) Expr

Or composes conditions with OR.

type FunctionCall

type FunctionCall struct {
	Name string
	Args []Expr
}

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

type HashPair struct {
	Key   Value
	Value Value
}

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

type Hook func(*Instance) error

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

Col returns a QualifiedIdentifier for this table's column — the Go form of Sequel[:table][:col].

type IdxOpt

type IdxOpt func(*indexDef)

IdxOpt configures an index.

func IndexName

func IndexName(name string) IdxOpt

IndexName sets an explicit index name.

func UniqueIndex

func UniqueIndex() IdxOpt

UniqueIndex marks an index UNIQUE.

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

func (i *Instance) Add(name string, other *Instance) error

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

func (i *Instance) AssociationDataset(name string) *Dataset

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

func (i *Instance) ChangedColumns() []string

ChangedColumns returns the columns modified since load/save, in set order — Sequel's changed_columns.

func (*Instance) Delete

func (i *Instance) Delete() error

Delete removes the row with a DELETE keyed on the primary key. It runs no hooks — Sequel's Model#delete.

func (*Instance) Destroy

func (i *Instance) Destroy() error

Destroy removes the row, running the before/after destroy hooks — Sequel's Model#destroy.

func (*Instance) Errors

func (i *Instance) Errors() *Errors

Errors returns the instance's validation errors (populated by Valid).

func (*Instance) Get

func (i *Instance) Get(col string) Value

Get returns the value of a column.

func (*Instance) IsNew

func (i *Instance) IsNew() bool

IsNew reports whether the instance is a new (unsaved) record.

func (*Instance) Modified

func (i *Instance) Modified() bool

Modified reports whether any column changed since load/save — Sequel's modified?.

func (*Instance) PK

func (i *Instance) PK() Value

PK returns the primary-key value (or a []Value for a composite key).

func (*Instance) Refresh

func (i *Instance) Refresh() error

Refresh reloads the instance's columns from the database by primary key, clearing dirty state — Sequel's Model#refresh.

func (*Instance) Related

func (i *Instance) Related(name string) ([]*Instance, error)

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

func (i *Instance) RelatedOne(name string) (*Instance, error)

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

func (i *Instance) Remove(name string, other *Instance) error

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

func (i *Instance) Save() error

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

func (i *Instance) Set(col string, v Value) *Instance

Set assigns a column, marking it changed (dirty) unless the value is identical to the current one — mirroring Sequel only flagging real changes.

func (*Instance) SetAll

func (i *Instance) SetAll(pairs ...Value) *Instance

SetAll assigns several columns from alternating column/value pairs.

func (*Instance) Update

func (i *Instance) Update(pairs ...Value) error

Update assigns the given columns and saves — Sequel's instance update.

func (*Instance) Valid

func (i *Instance) Valid() bool

Valid runs the before/after-validation hooks and every registered validator, (re)populating the instance's errors, and reports whether the instance is valid — Sequel's valid?.

func (*Instance) Values

func (i *Instance) Values() map[string]Value

Values returns the instance's column values (the live map — do not mutate directly; use Set).

type JoinUsing

type JoinUsing []string

JoinUsing represents a USING(...) join condition.

func Using

func Using(cols ...string) JoinUsing

Using builds a JoinUsing condition for a join.

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

type Migration struct {
	Up   func(*Database)
	Down func(*Database)
}

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.

func (Migration) Apply

func (m Migration) Apply(db *Database, direction string)

Apply runs the migration in the given direction ("up" or "down") against db. An unknown direction runs nothing. A nil handler for the chosen direction is a no-op (an irreversible migration with no Down).

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.

func (*ModelClass) WithPK

func (m *ModelClass) WithPK(pk Value) (*Instance, error)

WithPK loads the row with the given primary key, or returns (nil, nil) when absent — Sequel's Model.with_pk / Model[pk].

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

type OrderedExpr struct {
	Expr       Expr
	Descending bool
}

OrderedExpr is an ORDER BY term with a direction — Sequel.asc/desc(expr).

func Asc

func Asc(v Value) OrderedExpr

Asc marks a column/expression ascending in ORDER BY.

func Desc

func Desc(v Value) OrderedExpr

Desc marks a column/expression descending in ORDER BY.

type QualifiedIdentifier

type QualifiedIdentifier struct {
	Table  string
	Column string
}

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

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 (...))

Jump to

Keyboard shortcuts

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