- OCaml 100%
- C <1%
- Shell <1%
sql #
The SQLite dialect and the query engine it runs on, over any store.
An OCaml application that wants SQL usually links the SQLite C library and
takes its storage format along with its query language. This package keeps
the two apart. It parses the SQLite dialect, plans each statement and lowers
it to its own intermediate representation, which runs on a register virtual
machine or as compiled closures. Statements, and the typed queries of
catalog, then run over
any store that implements Catalog.Spi, such as a set of tables in memory,
a B-tree file in the SQLite format or an Irmin tree.
Installation #
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam install sql
Place in the stack #
sql takes the values, errors, store interface and typed queries of
catalog, and holds everything that runs them: the engine (Sql.Ir,
Sql.Vdbe, Sql.Closure, Sql.Join) and sqlite3's value semantics
(Sql.Sqlite3_semantics, Sql.Value_ops, Sql.Collation,
Sql.Encoding, Sql.Order). The engine's IR, VM, closure compiler, joins
and result rows are functors over a dialect's value semantics, and the
modules named here are their sqlite3 instances.
btree takes the order of
an index key from it, and
sqlite runs this parser,
planner and engine over SQLite database files, with transactions,
constraints and triggers on top. An application that wants SQL over SQLite
files uses sqlite, and one that wants SQL or typed queries over its own
store uses this package.
Usage #
Sql.v store opens a connection over the Catalog.t store. Sql.exec db text parses the statements in text, separated by ;, and runs them in
order on the connection db. It returns the rows of the last statement
(Rows) or Done. Sql.query runs one SELECT with its ? placeholders
bound to ~params.
let store = Catalog.of_mem []
let db = Sql.v store
let () =
match
Sql.exec db
"CREATE TABLE t (a INTEGER, b TEXT);\n\
INSERT INTO t VALUES (1, 'x'), (2, 'y'), (3, 'z');\n\
SELECT b, a * 10 FROM t WHERE a > 1 ORDER BY a DESC"
with
| Sql.Rows rows ->
assert (
rows
= Catalog.Value.[ [ Text "z"; Int 30L ]; [ Text "y"; Int 20L ] ])
| Sql.Done -> assert false
let () =
assert (
Sql.query db "SELECT b FROM t WHERE a = ?"
~params:[ Catalog.Value.Int 2L ]
= Catalog.Value.[ [ Text "y" ] ])
A SELECT runs the whole read dialect, with joins, GROUP BY and HAVING,
window functions, compound queries, recursive WITH, subqueries and
table-valued functions. Sql.exec also runs CREATE TABLE, DROP TABLE,
INSERT, UPDATE and DELETE, with their OR and ON CONFLICT
resolutions, upserts and CHECK constraints, fires triggers and, under
PRAGMA foreign_keys, enforces foreign keys and takes their actions. It runs
BEGIN, COMMIT, ROLLBACK and savepoints over the store's own
transactions, and every statement that writes is atomic.
A store becomes queryable by implementing Catalog.Spi.S and building its
Catalog.t with Catalog.Spi.Make; a connection runs over that
Catalog.t.
A typed query of catalog runs over the same store with Sql.run, lowered
straight to the engine's representation with no SQL text in between:
type item = { a : int64; b : string }
let a = Catalog.Col.v "a" Catalog.int (fun i -> i.a)
let b = Catalog.Col.v "b" Catalog.text (fun i -> i.b)
let items =
Catalog.Table.map "t" (fun a b -> { a; b })
|> Catalog.Table.col a |> Catalog.Table.col b |> Catalog.Table.seal
let () =
let large =
Catalog.Query.(from items @@ fun i -> where Expr.(get i a > int 1L) @@ all i)
in
assert (List.map (fun i -> i.b) (Sql.run store large) = [ "y"; "z" ])
Sql.update and Sql.delete rewrite and remove the rows a typed predicate
selects, and Sql.text_of_query writes a typed query as the SQL text a
store that runs SQL itself executes.
The connection holds what sqlite3 keeps on its own beside the store: the
rows the last write changed (Sql.changes), the rows every write changed
(Sql.total_changes) and the rowid of the last row inserted
(Sql.last_insert_rowid), which a statement reads as changes(),
total_changes() and last_insert_rowid():
let () =
ignore (Sql.exec db "UPDATE t SET b = upper(b) WHERE a > 1");
assert (Sql.changes db = 2L);
assert (Sql.total_changes db = 5L);
assert (Sql.last_insert_rowid db = 3L)
Execution #
A statement lowers to a positional intermediate representation, Sql.Ir,
which runs on Sql.Vdbe, a register virtual machine modelled on SQLite's
VDBE (Virtual DataBase Engine). Its code is a flat list of opcodes over
numbered registers, which open cursors, read columns, compare, jump and emit
rows. A store's cursor decodes each column it is asked for straight into a
register, so a scan allocates for its registers and not for each row.
Sql.Closure compiles the simplest plans once more, those that read one
source through a filter of comparisons. Each becomes a tree of OCaml
closures, so a row costs direct calls instead of opcode dispatch. Every
other plan runs on the machine. Sql.Join chooses how a join reads its
inner relation, an index seek, a hash or a scan, from how often the loop
rewinds it.
Standards #
The dialect is the SQL language of sqlite3
3.54.1, not ISO SQL. Where both define a construct, such as
window functions and
common table expressions, this
package follows sqlite3. So do the value rules:
type affinity, collation, NULL in
three-valued logic, the
built-in functions,
date and time and
JSON. Errors carry sqlite3's messages.
Two terms need a definition. Type affinity is the type a column prefers
(INTEGER, REAL, TEXT, BLOB or NUMERIC). An inserted value is converted to it
when nothing is lost, and otherwise kept as it is. Three-valued logic is how
SQL treats NULL. A comparison with NULL is unknown, neither true nor false,
and WHERE keeps only the rows where its condition is true.
API #
Sql.parseparses SQL text intoSql.Aststatements, andSql.pp_expr,Sql.pp_selectandSql.pp_identprint them back as SQL that parses to the same tree.Sql.vopens a connection over aCatalog.t, andSql.changes,Sql.total_changesandSql.last_insert_rowidread what it counted.Sql.exec,Sql.query,Sql.selectandSql.evalrun text, aSELECTtree or an expression on a connection, andSql.explain_selectprints the access path of each source of aSELECT.Sql.run,Sql.iter,Sql.explain,Sql.update,Sql.deleteandSql.text_of_queryrun the typed queries and writes ofcatalog.Sql.Ir,Sql.Vdbe,Sql.ClosureandSql.Joinare the engine, andSql.Rowthe result row a query hands over.Sql.Sqlite3_semanticsis what the engine compares, tests, sorts and folds by: sqlite3's comparison, truth, arithmetic, collation and aggregates.Sql.Value_ops,Sql.Collation,Sql.EncodingandSql.Orderare sqlite3's value semantics: affinity andCAST, the collating sequences, the text encodings and the order of an index key.Sql.Jsonbreads and writes JSONB, the binary JSON the JSON functions store, byte for byte as sqlite3 does: its values, codecs between elements and OCaml values, and cursors that search and edit a document in place with SQLite's paths.Sql_shell, in thesql-shellpackage, is an interactive shell that reads one line at a time; a backend instantiates it with its own way of running statements.
Papers #
- Patricia Selinger, Morton Astrahan, Donald Chamberlin, Raymond Lorie and
Thomas Price, "Access Path Selection in a Relational Database Management
System", SIGMOD 1979. The choice, for each source of a query, between a
scan and an index seek, which
Sql.explainprints. - Marc Feeley and Guy Lapalme, "Using Closures for Code Generation", Computer
Languages 12(1), 1987. The technique
Sql.Closureuses. - Thomas Neumann, "Efficiently Compiling Efficient Query Plans for Modern Hardware", PVLDB 4(9), 2011. Why a query compiled once beats an interpreter that dispatches on the plan for every row.
Licence #
ISC. See LICENSE.md.