-
Notifications
You must be signed in to change notification settings - Fork 15
/
adbc_database.ex
103 lines (80 loc) · 2.73 KB
/
adbc_database.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
defmodule Adbc.Database do
@moduledoc """
Documentation for `Adbc.Database`.
Databases are modelled as processes. They required
a driver to be started.
"""
use GenServer
import Adbc.Helper, only: [error_to_exception: 1]
@doc """
Starts a database process.
## Options
* `:driver` (required) - the driver to use for this database.
It must be an atom (see `Adbc` module documentation for all
built-in drivers) or a string representing the path to a driver
* `:process_options` - the options to be given to the underlying
process. See `GenServer.start_link/3` for all options
All other options are given as database options to the underlying driver.
## Examples
Adbc.Database.start_link(
driver: :sqlite,
process_options: [name: MyApp.DB]
)
In your supervision tree it would be started like this:
children = [
{Adbc.Database,
driver: :sqlite,
process_options: [name: MyApp.DB]},
]
"""
def start_link(opts \\ []) do
{driver, opts} = Keyword.pop(opts, :driver, nil)
unless driver do
raise ArgumentError, ":driver option must be specified"
end
{process_options, opts} = Keyword.pop(opts, :process_options, [])
opts = Keyword.merge(driver_default_options(driver), opts)
with {:ok, ref} <- Adbc.Nif.adbc_database_new(),
:ok <- init_driver(ref, driver),
:ok <- init_options(ref, opts),
:ok <- Adbc.Nif.adbc_database_init(ref) do
GenServer.start_link(__MODULE__, {driver, ref}, process_options)
else
{:error, reason} -> {:error, error_to_exception(reason)}
end
end
defp driver_default_options(:duckdb), do: [entrypoint: "duckdb_adbc_init"]
defp driver_default_options(_), do: []
## Callbacks
@impl true
def init({driver, db}) do
Process.flag(:trap_exit, true)
{:ok, {driver, db}}
end
@impl true
def handle_call({:initialize_connection, conn_ref}, {pid, _}, {driver, db}) do
case Adbc.Nif.adbc_connection_init(conn_ref, db) do
:ok ->
Process.link(pid)
{:reply, {:ok, driver}, {driver, db}}
{:error, reason} ->
{:reply, {:error, reason}, {driver, db}}
end
end
@impl true
def handle_info(_msg, state), do: {:noreply, state}
defp init_driver(ref, driver) do
case Adbc.Driver.so_path(driver) do
{:ok, path} -> Adbc.Nif.adbc_database_set_option(ref, "driver", path)
{:error, reason} -> {:error, reason}
end
end
defp init_options(ref, opts) do
Enum.reduce_while(opts, :ok, fn {key, value}, :ok ->
case Adbc.Nif.adbc_database_set_option(ref, to_string(key), to_string(value)) do
:ok -> {:cont, :ok}
{:error, _} = error -> {:halt, error}
end
end)
end
end