wasm_sqlite (wasm_sqlite v0.1.0)

View Source

The API of wasm_sqlite: SQLite, running inside WebAssembly.

Each database you open is a server process (wasm_sqlite_db) in front of a guest that runs SQLite with one connection. The functions here check and encode your arguments in your process, then call that server. Start here; you normally do not need the other modules.

{ok, Db} = wasm_sqlite:open(#{storage => {wasm_storage_file, "data.sqlite"}}),
ok = wasm_sqlite:execute(Db,
    <<"CREATE TABLE items (id INTEGER PRIMARY KEY, value TEXT)">>, []),
ok = wasm_sqlite:execute(Db, <<"INSERT INTO items VALUES (?, ?)">>,
                         [1, <<"example">>]),
{ok, [[1, <<"example">>]]} =
    wasm_sqlite:query(Db, <<"SELECT * FROM items">>, []),
ok = wasm_sqlite:close(Db).

Values: null, integers, floats, binaries (TEXT) and {blob, Binary} (BLOB). A float that is not a number comes back as {float, Bits}.

Errors are {error, {Reason, Message}} with SQLite's primary result code as an atom (constraint, error for SQL errors, busy, ...), or, after a storage failure, a trap or a deadline, {error, {Reason, Detail}} and {error, {commit_unknown, Why}} as in wasm_redb: the guest is replaced, the database reopens (SQLite rolls back an interrupted transaction from its journal) and statements and the open transaction are lost. timeout, overloaded, closed and {unavailable, Why} mean what they mean in wasm_redb.

See the SQLite guide for the build options, the journal mode and what the storage guarantees, and failures for what to do about each error.

Summary

Types

A database: the handle open/1 returns, or the name or pid of one that start_link/1 started.

Functions

Copy the database, online, into another file of the same storage ({wasm_storage_file, Path}: the same directory). The copy is committed the way the database is, through a truncated journal.

Bind every parameter of the statement, resetting it first.

A child spec for start_link/1.

Close the database. An open transaction is rolled back.

The column names of the statement's rows.

Run every statement in Sql, in order, discarding rows: a script. Returns how many rows they changed.

exec/2 with options: timeout.

Run one statement with parameters, discarding rows.

Every remaining row.

Finalize the statement. It runs even when the call's deadline passes first.

SQLite's version, open statements, transaction state, guest memory, whether it is reopening (opening), last failure.

SQLite's integrity check. ok, or the problems it found.

Open a database, creating it when missing. It closes when the calling process exits, unless owner => none. Options

Prepare one statement. It belongs to the calling process and is finalized when that process exits. Only the first statement of Sql is prepared.

Run one statement and return every row.

Run one statement and return the rows with their column names: {ok, #{columns := [binary()], rows := [[value()]]}}. With limit, at most that many rows, and done says whether there were more. For large results, use prepare/2 and step/2.

Reset the statement, so that the next step starts again. Bindings stay. It runs even when the call's deadline passes first.

Like execute/3, and say how many rows changed and the last rowid inserted.

Start a database process linked to the caller, for your own supervision tree. Takes the options of open/1; owner defaults to none. Give it a name and pass the name wherever a database is expected.

Fetch up to N rows. {rows, Rows} when more may follow, {done, Rows} when the statement has finished (a write is applied by the step that finishes it).

transaction(Db, Fun, #{}).

Run Fun() between BEGIN and COMMIT; the calling process owns the database meanwhile, and other callers wait. Returns {ok, Result}. {abort, Reason} from Fun, or an exception, rolls back. mode is deferred, immediate (default) or exclusive.

Types

database()

-type database() :: db() | atom() | pid().

A database: the handle open/1 returns, or the name or pid of one that start_link/1 started.

db()

-opaque db()

stmt()

-opaque stmt()

value()

-type value() :: wasm_sqlite_proto:value().

Functions

backup/2

-spec backup(database(), binary()) -> ok | {error, term()}.

Copy the database, online, into another file of the same storage ({wasm_storage_file, Path}: the same directory). The copy is committed the way the database is, through a truncated journal.

Returns {error, already_open} if a database of this node has that file open, and {error, {badarg, _}} for the database's own file or a journal. An empty name or :memory: raises badarg.

bind/2

-spec bind(stmt(), [value()]) -> ok | {error, term()}.

Bind every parameter of the statement, resetting it first.

child_spec(Opts)

-spec child_spec(map()) -> supervisor:child_spec().

A child spec for start_link/1.

close(Db)

-spec close(database()) -> ok.

Close the database. An open transaction is rolled back.

columns/1

-spec columns(stmt()) -> [binary()].

The column names of the statement's rows.

exec(Db, Sql)

-spec exec(database(), iodata()) -> {ok, non_neg_integer()} | {error, term()}.

Run every statement in Sql, in order, discarding rows: a script. Returns how many rows they changed.

exec(Db, Sql, Opts)

-spec exec(database(), iodata(), map()) -> {ok, non_neg_integer()} | {error, term()}.

exec/2 with options: timeout.

execute(Db, Sql, Params)

-spec execute(database(), iodata(), [value()]) -> ok | {error, term()}.

Run one statement with parameters, discarding rows.

fetch_all(Stmt)

-spec fetch_all(stmt()) -> {ok, [[value()]]} | {error, term()}.

Every remaining row.

finalize/1

-spec finalize(stmt()) -> ok | {error, term()}.

Finalize the statement. It runs even when the call's deadline passes first.

info(Db)

-spec info(database()) -> map().

SQLite's version, open statements, transaction state, guest memory, whether it is reopening (opening), last failure.

integrity_check(Db)

-spec integrity_check(database()) -> ok | {error, term()}.

SQLite's integrity check. ok, or the problems it found.

open(Opts)

-spec open(map()) -> {ok, db()} | {error, term()}.

Open a database, creating it when missing. It closes when the calling process exits, unless owner => none. Options:

  • storage (required): {wasm_storage_file, Path} (the journal goes next to it), {wasm_storage_memory, new} (in memory, journal included), or a namespace {wasm_storage_dir, Dir} / {wasm_storage_memory_ns, Ns} with file, the database's name in it (default main.db).
  • journal_mode: truncate (default), persist, delete, memory, off. See the SQLite guide before changing it.
  • synchronous: full (default), normal, off.
  • pragmas: more PRAGMA statements to run at every open.
  • read_only, timeout (default 30000 ms per call), cleanup_timeout (default 30000 ms: the rollback for an owner that exited, closing), open_timeout (default 600000 ms: an open, the rollback of an interrupted transaction included), compile, instance, min_heap_size, hibernate_after, max_queue, owner: as in wasm_redb:open/1.
  • name: register the database process under this name.

prepare(Db, Sql)

-spec prepare(database(), iodata()) -> {ok, stmt()} | {error, term()}.

Prepare one statement. It belongs to the calling process and is finalized when that process exits. Only the first statement of Sql is prepared.

query(Db, Sql, Params)

-spec query(database(), iodata(), [value()]) -> {ok, [[value()]]} | {error, term()}.

Run one statement and return every row.

query(Db, Sql, Params, Opts)

-spec query(database(), iodata(), [value()], map()) -> {ok, map()} | {error, term()}.

Run one statement and return the rows with their column names: {ok, #{columns := [binary()], rows := [[value()]]}}. With limit, at most that many rows, and done says whether there were more. For large results, use prepare/2 and step/2.

reset/1

-spec reset(stmt()) -> ok | {error, term()}.

Reset the statement, so that the next step starts again. Bindings stay. It runs even when the call's deadline passes first.

run(Db, Sql, Params)

-spec run(database(), iodata(), [value()]) ->
             {ok, #{changes := integer(), last_insert_rowid := integer()}} | {error, term()}.

Like execute/3, and say how many rows changed and the last rowid inserted.

start_link(Opts)

-spec start_link(map()) -> {ok, pid()} | {error, term()}.

Start a database process linked to the caller, for your own supervision tree. Takes the options of open/1; owner defaults to none. Give it a name and pass the name wherever a database is expected.

step/2

-spec step(stmt(), pos_integer()) -> {rows, [[value()]]} | {done, [[value()]]} | {error, term()}.

Fetch up to N rows. {rows, Rows} when more may follow, {done, Rows} when the statement has finished (a write is applied by the step that finishes it).

transaction(Db, Fun)

transaction(Db, Fun, #{}).

transaction(Db, Fun, Opts)

-spec transaction(database(), fun(() -> term()), map()) -> {ok, term()} | {error, term()}.

Run Fun() between BEGIN and COMMIT; the calling process owns the database meanwhile, and other callers wait. Returns {ok, Result}. {abort, Reason} from Fun, or an exception, rolls back. mode is deferred, immediate (default) or exclusive.