sqlitex v1.2.0 Sqlitex.Server

Sqlitex.Server provides a GenServer to wrap a sqlitedb. This makes it easy to share a sqlite database between multiple processes without worrying about concurrency issues. You can also register the process with a name so you can query by name later.

Unsupervised Example

iex> {:ok, pid} = Sqlitex.Server.start_link(":memory:", [name: :example])
iex> Sqlitex.Server.exec(pid, "CREATE TABLE t (a INTEGER, b INTEGER)")
:ok
iex> Sqlitex.Server.exec(pid, "INSERT INTO t (a, b) VALUES (1, 1), (2, 2), (3, 3)")
:ok
iex> Sqlitex.Server.query(pid, "SELECT * FROM t WHERE b = 2")
{:ok, [[a: 2, b: 2]]}
iex> Sqlitex.Server.query(:example, "SELECT * FROM t ORDER BY a LIMIT 1", into: %{})
{:ok, [%{a: 1, b: 1}]}
iex> Sqlitex.Server.query_rows(:example, "SELECT * FROM t ORDER BY a LIMIT 2")
{:ok, %{rows: [[1, 1], [2, 2]], columns: [:a, :b], types: [:INTEGER, :INTEGER]}}
iex> Sqlitex.Server.prepare(:example, "SELECT * FROM t")
{:ok, %{columns: [:a, :b], types: [:INTEGER, :INTEGER]}}
  # Subsequent queries using this exact statement will now operate more efficiently
  # because this statement has been cached.
iex> Sqlitex.Server.prepare(:example, "INVALID SQL")
{:error, {:sqlite_error, 'near "INVALID": syntax error'}}
iex> Sqlitex.Server.stop(:example)
:ok
iex> :timer.sleep(10) # wait for the process to exit asynchronously
iex> Process.alive?(pid)
false

Supervised Example

import Supervisor.Spec

children = [
  worker(Sqlitex.Server, ["priv/my_db.sqlite3", [name: :my_db])
]

Supervisor.start_link(children, strategy: :one_for_one)

Summary

Functions

create_table(pid, name, table_opts \\ [], cols)
exec(pid, sql, opts \\ [])
prepare(pid, sql, opts \\ [])

Prepares a SQL statement for future use.

This causes a call to sqlite3_prepare_v2 to be executed in the Server process. To protect the reference to the corresponding sqlite3_stmt struct from misuse in other processes, that reference is not passed back. Instead, prepared statements are cached in the Server process. If a subsequent call to query/3 or query_rows/3 is made with a matching SQL statement, the prepared statement is reused.

Prepared statements are purged from the cache when the cache exceeds a pre-set limit (20 statements by default).

Returns summary information about the prepared statement {:ok, %{columns: [:column1_name, :column2_name,... ], types: [:column1_type, ...]}} on success or {:error, {:reason_code, 'SQLite message'}} if the statement could not be prepared.

query(pid, sql, opts \\ [])
query_rows(pid, sql, opts \\ [])
start_link(db_path, opts \\ [])

Starts a SQLite Server (GenServer) instance.

In addition to the options that are typically provided to GenServer.start_link/3, you can also specify stmt_cache_size: (positive_integer) to override the default limit (20) of statements that are cached when calling prepare/3.

stop(pid)