Skip to content

std.orm

The mapping between record types and tables. derive Table for Todo gives the table of Todo (its schema: a column per field, its key, its references and checks), the row of a record and the record of a row, and typed conditions on its fields. It runs nothing: a Database (std.sqlite) runs every operation, on a record through this mapping.

type Project = { id: Int = 0, name: String where it != "" }
type Todo = {
id: Int = 0,
title: String where it != "",
priority: Int where 1 <= it && it <= 5,
done: Bool = false,
project: Key[Project],
}
derive Table for Project
derive Table for Todo
fn main(sqlite: Sqlite) -> Result[(), SqlError] {
mut db := sqlite.memory()!
mut db.create(Project.table())!
mut db.create(Todo.table())!
p := (mut db.insert(Project { name: "home" }))!
_ := (mut db.insert(
Todo { title: "write docs", priority: 2, project: p },
))!
open := db.select(
Todo.filter(Todo.done.eq(false)).order_by(Todo.priority),
)!
..
}

The table is named after the type in snake case (TodoItem: todo_item), a column per field: Int and Bool (0 or 1) are INTEGER, Float is REAL, String is TEXT, an Option is the same column without NOT NULL, a distinct type is what it is made of. The key is written in the derive’s block, derive Table for Item { key code } (key (shelf, slot) for one of several columns); without one, the field id, an integer the database gives each row (its row id). A Key[T] field is a key of T’s table (REFERENCES), an Option[Key[T]] one that may be NULL; a field holding a record, a union, a list or a dict whose type derives Json is kept as JSONB. A refinement is a CHECK where SQL can say it, a literal default is a DEFAULT, and every row read back is checked again in Strata, so a row breaking a refinement SQL couldn’t state is an error value (BadRow), never a fault.

Conditions are values: Todo.title is a KeyPath[Todo, String], so Todo.title.eq("x") (a Cond[Todo]) is checked against the field’s type.

type Cond[R] = { filter: Filter }

A condition on rows of the table of R, such as Todo.done.eq(false): a Filter checked against the record’s fields.

type Query[R] = {
cond: Option[Cond[R]] = None,
order: List[Order] = [],
limit: Option[Natural] = None,
}

A query on the table of R: the rows meeting a condition, in an order, at most so many. Made with Todo.query() or Todo.filter(c), run by a Database (db.select(q), db.first(q), db.count(q), db.delete_where(q)).

type TableOf[R] = { schema: Schema }

The table of records R: its schema, made from the record type by derive Table (Todo.table()).

type Key[T] = { value: KeyValue }

A key of a row of T’s table (a key of one column: an integer or text). A field project: Key[Project] is a foreign key: its column holds a Project’s key and REFERENCES its table, and verify checks that the row exists when a record holding it is inserted or updated. p.key() gives a row’s; k.load(db) reads the row.

fn and(self, other: Cond[R]) -> Cond[R]

Rows meeting both.

fn either(self, other: Cond[R]) -> Cond[R]

Rows meeting either.

fn not(self) -> Cond[R]

Rows not meeting it, those a comparison with None leaves out included.

fn filter(self, c: Cond[R]) -> Query[R]

Narrows to rows that also meet c.

fn order_by[T: Sql](self, col: KeyPath[R, T]) -> Query[R]

Orders by col, smallest first, after the orders given before.

fn order_by_desc[T: Sql](self, col: KeyPath[R, T]) -> Query[R]

Orders by col, largest first.

fn limit(self, n: Natural) -> Query[R]

At most n rows.

fn selection(self) -> Selection

The rows it selects, as a Database reads them.

fn values(self) -> List[SqlValue]
ensures key_value_of(it) == self.value

The values of the key’s column, as a Database takes a key.

trait Compare[R, T] {
/// Rows whose column is `v`.
fn eq(self, v: T) -> Cond[R]
/// Rows whose column isn't `v`.
fn ne(self, v: T) -> Cond[R]
/// Rows whose column is less than `v`.
fn lt(self, v: T) -> Cond[R]
/// Rows whose column is at most `v`.
fn le(self, v: T) -> Cond[R]
/// Rows whose column is more than `v`.
fn gt(self, v: T) -> Cond[R]
/// Rows whose column is at least `v`.
fn ge(self, v: T) -> Cond[R]
}

Compares a column with a value of its field’s type: Todo.done.eq(false), where Todo.done is a KeyPath[Todo, Bool]. eq and ne match None too (SQL’s IS). An order with None holds for no row. An order on a Real column, kept as its exact text, makes running the query an error.

derivable(Record) trait Table {
/// The table: its name (the type's, in snake case), its columns (a
/// field's each, in order), the record's own refinement and its key.
derived fn table() -> TableOf[Self]
/// The name of its table (the type's, in snake case).
derived fn table_name(self) -> String
/// Its values, a column's each, in order (a JSON one as text, `None`
/// for NULL).
derived fn values(self) -> Result[List[Option[SqlValue]], SqlError]
/// Its key (of several columns: their values written out, as
/// `key_value_of` writes them).
derived fn key(self) -> Key[Self]
/// Whether each row its `Key[T]` fields name is in `rows` (a
/// database's model).
derived fn references_held(self, rows: Set[(String, KeyValue)]) -> Bool
/// Whether its key is no row's in `rows` (a database's model). A key
/// the database gives (the default key `id`) always is.
derived fn key_is_new(self, rows: Set[(String, KeyValue)]) -> Bool
/// The record a row holds, columns in field order, every refinement checked. A row breaking one is `BadRow`.
derived fn from_row(r: Row) -> Result[Self, SqlError]
/// The record with the key SQLite gave it (the default key `id`, an
/// integer; others are kept).
derived fn with_key(self, id: Int) -> Self
/// A query of every row, to narrow with `filter`, order and limit.
fn query() -> Query[Self]
/// A query of the rows meeting `c`.
fn filter(c: Cond[Self]) -> Query[Self]
}

A record kept as a row of a table (see above): derive Table for Todo, derive Table for Item { key code } (see above).

  • impl[R, T: Sql] Compare[R, T] for KeyPath[R, T]
  • impl[T] Sql for Key[T]