Current section
Files
Jump to
Current section
Files
lib/depo.ex
defmodule Depo do
@moduledoc """
Depo provides lightweight storage and querying capabilities
in Elixir by providing a minimal and polished API
that builds on the unique advantages of SQLite.
You can [read about SQLite's architecture
](https://www.sqlite.org/arch.html)
to learn about the SQLite bytecode compiler and other
modules within SQLite that you can utilize.
Depo provides `create/1` to create a new `Depo.DB`
object with which you can interact with the database.
Anywhere you give a command, you can give either a valid
string of SQL or an atom registered to a cached statement.
You can also include numbered variables like `?1` in your
SQL statements and pass a list of values as the third
parameter to `write/3`, `read/3`, and `stream/3`.
## Usage Example
```
# Open a new in-memory database.
{:ok, db} = Depo.open(:memory)
# {:ok, #PID<0.155.0>}
# Write SQL statements to the database.
Depo.write(db, "CREATE TABLE greetings (phrase)")
# :ok
# Teach the database statements to cache them.
Depo.teach(db, %{
new_greeting: "INSERT INTO greetings VALUES (?1)",
greetings: "SELECT * FROM greetings",
})
# :ok
# Enclose operations within a transaction.
Depo.transact(db, fn ->
Enum.each(["hola", "bonjour", "今日は"], fn phrase ->
Depo.write(db, :new_greeting, [phrase])
end)
end)
# :ok
# Stream the results of a query to a PID.
Depo.stream(db, self(), :greetings)
# #PID<0.187.0>
:timer.sleep(5)
self() |> Process.info() |> Keyword.get(:messages)
# [ {#PID<0.187.0>, %{phrase: "hola"}},
# {#PID<0.187.0>, %{phrase: "bonjour"}},
# {#PID<0.187.0>, %{phrase: "今日は"}}]
```
"""
defmacrop is_cmd(cmd) do
quote do
is_binary(unquote(cmd)) or is_atom(unquote(cmd))
end
end
@doc """
Open a connection to a database and return a new
`Depo.DB` object to manage the database connection.
There are a few ways you can open a database:
- pass a `path` to open an existing on-disk database
- pass `create: path` to create and open a database at the path
- pass `:memory` to create a new in-memory database
"""
def open(:memory) do
GenServer.start_link(Depo.DB, :memory)
end
def open(create: path) when is_binary(path) do
GenServer.start_link(Depo.DB, create: path)
end
def open(path) when is_binary(path) do
GenServer.start_link(Depo.DB, path)
end
@doc """
Asynchronously write SQL statements to the database.
Optionally supply a list of values as the third
argument to bind to variables in the statement.
"""
def write(db, cmd, values) when is_cmd(cmd) do
GenServer.cast(db, {:write, cmd, values})
end
def write(db, cmd) when is_cmd(cmd) do
GenServer.cast(db, {:write, cmd})
end
@doc """
Synchronously read an SQL query from the database
and return a list of the results.
Optionally supply a list of values as the third
argument to bind to variables in the query.
"""
def read(db, query, values) when is_cmd(query) do
GenServer.call(db, {:read, query, values})
end
def read(db, query) when is_cmd(query) do
GenServer.call(db, {:read, query})
end
@doc """
Asynchronously stream the results of an SQL query from
the database to the given PID.
The given process will receive each result as a tuple
`{stream_id, value}` where `stream_id` is the PID of the
stream process that uniquely identifies the stream,
and `value` is a single result map.
Optionally supply a list of values as the fourth
argument to bind to variables in the query.
"""
def stream(db, pid, query, values) when is_cmd(query) do
GenServer.call(db, {:stream, pid, query, values})
end
def stream(db, pid, query) when is_cmd(query) do
GenServer.call(db, {:stream, pid, query})
end
@doc """
Prepare, cache, and register named SQL statements for
more efficient repeated use.
`statements` should be a keyword list, where the keys
are atoms and the values are SQL statements.
"""
def teach(db, stmts) do
GenServer.cast(db, {:teach, stmts})
end
@doc """
Wrap any operations within the given anonymous function
in a nestable transaction.
If any error occurs within, the transaction will be
automatically rolled back.
You can [read about SQLite's transactions in depth in its
documentation.](https://sqlite.org/lang_transaction.html)
"""
def transact(db, func) do
Depo.write(db, "SAVEPOINT _depo_transaction;")
func.()
Depo.write(db, "RELEASE _depo_transaction;")
end
@doc """
Safely close the database connection.
"""
def close(db) do
GenServer.stop(db)
end
end