Skip to content

std.sqlite

type Column = {
name: String,
/// `INTEGER`, `REAL`, `TEXT`, or `BLOB` (JSONB).
sql_type: String,
/// Whether it may be NULL: an `Option` field.
nullable: Bool,
/// Whether it is the table's key, or one of its columns.
key: Bool,
/// The table and column its values are keys of (a `Key[T]` field):
/// `REFERENCES`.
references: Option[(String, String)],
/// Its field's refinement, as written (`it != ""`).
condition: Option[String],
/// Its field's default as written: `false`. It is the `DEFAULT` when it is a literal.
default: Option[String] = None,
/// Whether SQLite gives its values: the default key `id`, an integer (the
/// row id).
generated: Bool = false,
/// Whether it holds JSONB (a record, union, list or dict deriving
/// `Json`): written with `jsonb(?)`, read with `json(..)`.
json: Bool = false,
/// Whether it holds a `Real`'s exact text (`0.1`, `1/3`). SQL would
/// compare it as text, so no `CHECK` compares it: reading checks it.
exact: Bool = false,
}

A column of a table, as CREATE TABLE declares it.

type SqlValue = KeyValue | Float | Bool

A value crossing to SQLite or back: what SQLite stores, plus Bool. A Bool is stored as 0 or 1 and read back as an Int. A value that may be NULL is an Option[SqlValue], None for NULL. Not supported: blobs. SQL’s hex and unhex pass them as text.

type KeyValue = Int | String

A key as the model Database.rows holds it: a key of one integer column its value (a Bool’s 0 or 1), of one text column its text, any other (a REAL column, a key of several columns) its values written out ([1, "a"]).

capability Sqlite {
/// The database in the file `path`, created if missing.
fn open(path: String) -> Result[Connection, SqlError]
assumed ensures match it {
Ok(c) => !c.in_transaction(),
Err(_) => true,
}
/// A new, empty database in memory, gone once closed.
fn memory() -> Result[Connection, SqlError]
assumed ensures match it {
Ok(c) => len(c.rows()) == 0 && !c.in_transaction(),
Err(_) => true,
}
/// The SQLite library's version, such as `3.51.0`.
fn version() -> String
}

SQLite itself. Only the runtime makes one, for main and tests that ask for it.

type Connection = { handle: Sqlite3, path: String }

A database SQLite opened with sqlite.open(path). Close it when done.

type SqlError =
/// The database couldn't be opened: a missing folder, no permission.
| CantOpen { path: String, message: String }
/// A constraint refused the change: `UNIQUE`, `NOT NULL`, `CHECK`, a foreign key.
| Constraint { message: String }
/// Another connection holds the database (SQLITE_BUSY, SQLITE_LOCKED).
| Busy { message: String }
/// Column `column` holds another type than the one asked for.
| WrongType { column: Int, wanted: String, found: String }
/// There is no column `column`. The rows have `count`.
| NoColumn { column: Int, count: Int }
/// There is no parameter `index`. The statement has `count`.
| NoParameter { index: Int, count: Int }
/// `given` values for a statement with `wanted` parameters.
| WrongParameters { given: Int, wanted: Int }
/// A value SQLite can't hold or this module can't read: an integer beyond 64 bits, a NUL in text, a blob.
| NotRepresentable { message: String }
/// Any other SQLite error, with its result code and message.
| SqlFailed { code: Int, message: String }
/// A row read back that its record type refuses (`std.orm`): a value breaks a refinement.
| BadRow { table: String, message: String }

Why a database operation failed.

type Row = { values: List[Option[SqlValue]] }

A result row’s values, by column: None for NULL.

type Statement = { handle: Sqlite3Stmt, sql: String }

A prepared statement from db.prepare(sql). Bind its parameters, step through its rows, read their columns. Finalize it when done.

type SqlOrder[T] = { ordered: Bool }

Whether SQL orders values of T as Strata does.

type Schema = {
table: String,
columns: List[Column],
/// The columns of its key, in order: one (`PRIMARY KEY` on it) or
/// several (`PRIMARY KEY (a, b)`). With none, a row's key is its row id.
key: List[String] = [],
/// A condition on each row as Strata writes it (`it.start <= it.end`),
/// a `CHECK` where SQL can say it.
condition: Option[String] = None,
}

A table as the database keeps it: its name, its columns in order, the columns of its key, and a condition on whole rows. Written by hand, or made from a record type by std.orm (Todo.schema()).

type Comparison =
/// Equal, with NULL equal to NULL (SQL's `IS`).
| Is
/// Not equal, with NULL equal to NULL (SQL's `IS NOT`).
| IsNot
/// Less than (`<`). A comparison with NULL holds for no row.
| Below
/// At most (`<=`).
| AtMost
/// Greater than (`>`).
| Above
/// At least (`>=`).
| AtLeast

How a column is compared with a value in a Filter.

type Filter =
/// Rows whose column `column` compares to `value` as `comparison` says
/// (`None`: NULL).
| Compared { column: String, comparison: Comparison, value: Option[SqlValue] }
/// Rows meeting both.
| Both { left: Filter, right: Filter }
/// Rows meeting either.
| Either { left: Filter, right: Filter }
/// Rows not meeting it, those a comparison with NULL leaves out included.
| Negated { filter: Filter }

Which rows to read, count or delete: columns compared with values, combined. The values are passed as parameters, never as SQL text.

type Order = { column: String, descending: Bool = false }

An order of rows: by column, smallest first unless descending.

type Selection = {
filter: Option[Filter] = None,
order: List[Order] = [],
limit: Option[Natural] = None,
}

The rows a read selects: those meeting filter (every row without one), in order (the first given first), at most limit.

fn value(self, i: Int) -> Result[Option[SqlValue], SqlError]

The value of column i, from 0: None for NULL.

fn int(self, i: Int) -> Result[Int, SqlError]

Column i as an integer.

fn float(self, i: Int) -> Result[Float, SqlError]

Column i as a float. An integer column converts (SQLite’s are 64-bit; a larger Int, which no column holds, is WrongType).

fn real(self, i: Int) -> Result[Real, SqlError]

Column i as an exact Real: text as Real writes it (0.1, 1/3, how Reals are stored), an integer, or a float by its shortest digits.

fn text(self, i: Int) -> Result[String, SqlError]

Column i as text.

fn bool(self, i: Int) -> Result[Bool, SqlError]

Column i as a boolean: an integer, 0 for false.

fn is_null(self, i: Int) -> Result[Bool, SqlError]

Whether column i is NULL.

fn prepare(self, sql: String) -> Result[Statement, SqlError]

Compiles one statement.

fn close(mut self) -> Result[(), SqlError]

Closes the connection. What it prepared must be finalized first.

fn autocommit(self) -> Bool

Whether no transaction is open.

fn parameter_count(self) -> Int where 0 <= it && it <= 2147483647

How many ? parameters the statement has.

fn column_count(self) -> Int where 0 <= it && it <= 2147483647

How many columns its rows have.

fn column_name(self, i: Int) -> Result[String, SqlError]

The name of column i, from 0.

fn bind(mut self, i: Int, v: Option[SqlValue]) -> Result[(), SqlError]

Binds parameter i to v (None: NULL). Parameters count from 1, as in SQLite.

fn bind_all(mut self, params: List[Option[SqlValue]]) -> Result[(), SqlError]

Binds every parameter in order. params must have one value per parameter.

fn step(mut self) -> Result[Bool, SqlError]

Steps to the next row. true when there is one to read, false once done.

fn value(self, i: Int) -> Result[Option[SqlValue], SqlError]

Column i of the current row: None for NULL.

fn row(self) -> Result[Row, SqlError]

The current row, every column.

fn reset(mut self) -> Result[(), SqlError]

Goes back to before the first row, keeping the bindings.

fn finalize(mut self)

Frees the statement. It can’t be used after.

trait Sql {
/// This value as SQLite stores it: `None` for NULL.
fn to_sql(self) -> Option[SqlValue]
/// Whether SQL orders these values as Strata does (`<`, `ORDER BY`): not a
/// `Real`, stored as its exact text.
fn sql_order() -> SqlOrder[Self]
}

Values that cross to SQLite as an SqlValue, or as NULL.

capability trait Database {
/// Each row as its table and its key (`key_of`). SQL run by hand
/// (`execute`, `run`) doesn't say how it changes, so after it is unknown.
model rows: Set[(String, KeyValue)]
/// Whether a transaction is open (`begin`). Inside one no other
/// connection writes, so `rows` changes only by this program's
/// operations, and `insert` requires a record the database will take.
model in_transaction: Bool
/// Makes the table `schema` describes, if it is missing. No row changes.
fn create_table(mut self, schema: Schema) -> Result[(), SqlError]
ensures self.rows == old self.rows
&& self.in_transaction == old self.in_transaction
/// Adds a row: `values` a column's each, in order, `None` for NULL (a column whose
/// values the database gives, `generated`, is left out). Returns its
/// key, which was no row's before. A row the database refuses (a key in
/// use, a reference to no row, a `CHECK`) is `Constraint`, and nothing
/// changes.
fn insert_row(
mut self,
schema: Schema,
values: List[Option[SqlValue]],
) -> Result[KeyValue, SqlError]
ensures self.in_transaction == old self.in_transaction
ensures match it {
Ok(k) => !contains(old self.rows, (schema.table, k))
&& self.rows == with(old self.rows, (schema.table, k)),
Err(_) => self.rows == old self.rows,
}
/// Writes `values` (a column's each, in order) over the row with their
/// key: whether there was one. No key is added or removed.
fn update_row(
mut self,
schema: Schema,
values: List[Option[SqlValue]],
) -> Result[Bool, SqlError]
ensures self.rows == old self.rows
&& self.in_transaction == old self.in_transaction
/// Deletes the row whose key's columns hold `key`: whether there was
/// one. A row another row references isn't deleted: `Constraint`.
fn delete_row(
mut self,
schema: Schema,
key: List[SqlValue],
) -> Result[Bool, SqlError]
ensures self.in_transaction == old self.in_transaction
ensures match it {
Ok(true) => contains(old self.rows, (schema.table, key_value_of(key)))
&& self.rows == without(old self.rows, (schema.table, key_value_of(key))),
Ok(false) => !contains(old self.rows, (schema.table, key_value_of(key)))
&& self.rows == old self.rows,
Err(_) => self.rows == old self.rows,
}
/// The row whose key's columns hold `key`, its columns in the schema's
/// order, if there is one.
fn load_row(
self,
schema: Schema,
key: List[SqlValue],
) -> Result[Option[Row], SqlError]
ensures match it {
Ok(Some(_)) => contains(self.rows, (schema.table, key_value_of(key))),
Ok(None) => !contains(self.rows, (schema.table, key_value_of(key))),
Err(_) => true,
}
/// The rows `selection` selects, their columns in the schema's order.
/// Comparing or ordering an `exact` column is `NotRepresentable`.
fn select_rows(
self,
schema: Schema,
selection: Selection,
) -> Result[List[Row], SqlError]
/// How many rows meet `filter` (every row without one).
fn count_rows(
self,
schema: Schema,
filter: Option[Filter],
) -> Result[Natural, SqlError]
/// Deletes the rows meeting `filter` (every row without one). Returns
/// how many.
fn delete_rows(
mut self,
schema: Schema,
filter: Option[Filter],
) -> Result[Natural, SqlError]
/// Runs one statement with its `?` parameters in order (`None` binds
/// NULL). Returns how many rows it changed.
fn execute(
mut self,
sql: String,
params: List[Option[SqlValue]],
) -> Result[Int, SqlError]
/// Runs one statement with its parameters. Returns its rows.
fn query(
self,
sql: String,
params: List[Option[SqlValue]],
) -> Result[List[Row], SqlError]
/// Runs statements without parameters one after the other, such as a schema.
fn run(mut self, sql: String) -> Result[(), SqlError]
/// The row id of the last row inserted.
fn last_insert_id(self) -> Int
/// Starts a transaction, taking the database's write lock (SQLite's
/// `BEGIN IMMEDIATE`): until `commit` or `rollback` no other connection
/// writes. `Busy` if another holds it.
fn begin(mut self) -> Result[(), SqlError]
requires !self.in_transaction
ensures self.rows == old self.rows
ensures match it {
Ok(_) => self.in_transaction,
Err(_) => !self.in_transaction,
}
/// Keeps what the transaction changed: the rows are the transaction's.
/// `Busy` keeps the transaction open.
fn commit(mut self) -> Result[(), SqlError]
requires self.in_transaction
ensures self.rows == old self.rows
ensures match it {
Ok(_) => !self.in_transaction,
Err(_) => true,
}
/// Undoes what the transaction changed.
fn rollback(mut self) -> Result[(), SqlError]
requires self.in_transaction
ensures !self.in_transaction
/// Makes the table of records `R` (`Todo.table()`), if it is missing.
/// No row changes.
fn create[R: Table](mut self, table: TableOf[R]) -> Result[(), SqlError]
ensures self.rows == old self.rows
&& self.in_transaction == old self.in_transaction
/// Adds `record` as a row of its table. Returns its key: the one the
/// database gives (the default key `id`), else the record's own. A row
/// the database refuses is `Constraint`, and nothing changes. Inside a
/// transaction the rows its keys name must exist and its key be new.
fn insert[R: Table](mut self, record: R) -> Result[Key[R], SqlError]
requires !self.in_transaction
|| record.references_held(self.rows)
&& record.key_is_new(self.rows)
ensures self.in_transaction == old self.in_transaction
ensures match it {
Ok(k) => !contains(old self.rows, (R.table().schema.table, k.value))
&& self.rows == with(old self.rows, (R.table().schema.table, k.value)),
Err(_) => self.rows == old self.rows,
}
/// Writes `record` over the row with its key: whether there was one.
fn update[R: Table](mut self, record: R) -> Result[Bool, SqlError]
ensures self.rows == old self.rows
&& self.in_transaction == old self.in_transaction
/// Deletes the row with the key `key`: whether there was one. A row
/// another row references isn't deleted: `Constraint`.
fn delete[R: Table](mut self, key: Key[R]) -> Result[Bool, SqlError]
ensures self.in_transaction == old self.in_transaction
ensures match it {
Ok(true) => contains(old self.rows, (R.table().schema.table, key.value))
&& self.rows == without(old self.rows, (R.table().schema.table, key.value)),
Ok(false) => !contains(old self.rows, (R.table().schema.table, key.value))
&& self.rows == old self.rows,
Err(_) => self.rows == old self.rows,
}
/// The row with the key `key`, as a record, if there is one.
fn load[R: Table](self, key: Key[R]) -> Result[Option[R], SqlError]
ensures match it {
Ok(Some(_)) => contains(self.rows, (R.table().schema.table, key.value)),
Ok(None) => !contains(self.rows, (R.table().schema.table, key.value)),
Err(_) => true,
}
/// The records `query` selects (`Todo.filter(Todo.done.eq(false))`).
fn select[R: Table](self, query: Query[R]) -> Result[List[R], SqlError]
/// The first record `query` selects, if any.
fn first[R: Table](self, query: Query[R]) -> Result[Option[R], SqlError]
/// How many records `query` selects (its order and limit aside).
fn count[R: Table](self, query: Query[R]) -> Result[Natural, SqlError]
/// Deletes the records `query` selects (its order and limit aside).
/// Returns how many.
fn delete_where[R: Table](
mut self,
query: Query[R],
) -> Result[Natural, SqlError]
}

A database: tables of rows, changed through typed operations or SQL. The operations’ contracts say how they change the model rows, so code using them is proven through the contracts alone. A Connection is one (its contracts are trusted: SQLite keeps them); a mock Database with its own rows is another.

fn sql[T: Sql](x: T) -> Option[SqlValue]

x as SQLite stores it: None for NULL (an Option’s None).

fn key_value_of(values: List[SqlValue]) -> KeyValue
ensures match values {
[v] => match v {
Int => match it {
Int => it == v,
String => false,
},
String => match it {
String => it == v,
Int => false,
},
_ => true,
},
_ => true,
}

The KeyValue of a row’s key: its columns’ values, in order.

fn key_of(schema: Schema, values: List[Option[SqlValue]]) -> KeyValue

The key of a row of the table schema describes, as the model rows holds it: the values of its key’s columns (key_value_of).

fn create_sql(schema: Schema) -> String

The SQL create_table runs for the table schema describes.

  • impl Sql for Int
  • impl Sql for Float
  • impl Sql for String
  • impl Sql for Bool
  • impl[T: Sql] Sql for Option[T]
  • impl Database for Connection
  • impl Sql for Real: A Real is stored exactly, as text (0.1, 1/3): SQLite’s REAL is a Float.