This repository was archived by the owner on Mar 19, 2021. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathsqlitex.ex
More file actions
196 lines (163 loc) · 7.21 KB
/
Copy pathsqlitex.ex
File metadata and controls
196 lines (163 loc) · 7.21 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
defmodule Sqlitex do
if Version.compare(System.version, "1.3.0") == :lt do
@type charlist :: char_list
end
@type connection :: {:connection, reference(), reference()}
@type string_or_charlist :: String.t | charlist
@type sqlite_error :: {:error, {:sqlite_error, charlist}}
@moduledoc """
Sqlitex gives you a way to create and query SQLite databases.
## Basic Example
```
iex> {:ok, db} = Sqlitex.open(":memory:")
iex> Sqlitex.exec(db, "CREATE TABLE t (a INTEGER, b INTEGER, c INTEGER)")
:ok
iex> Sqlitex.exec(db, "INSERT INTO t VALUES (1, 2, 3)")
:ok
iex> Sqlitex.query(db, "SELECT * FROM t")
{:ok, [[a: 1, b: 2, c: 3]]}
iex> Sqlitex.query(db, "SELECT * FROM t", into: %{})
{:ok, [%{a: 1, b: 2, c: 3}]}
```
## Configuration
Sqlitex uses the Erlang library [esqlite](https://github.com/mmzeeman/esqlite)
which accepts a timeout parameter for almost all interactions with the database.
The default value for this timeout is 5000 ms. Many functions in Sqlitex accept
a `:db_timeout` option that is passed on to the esqlite calls and also defaults
to 5000 ms. If required, this default value can be overridden globally with the
following in your `config.exs`:
```
config :sqlitex, db_timeout: 10_000 # or other positive integer number of ms
```
Another esqlite parameter is :db_chunk_size.
This is a count of rows to read from native sqlite and send to erlang process in one bulk.
For example, the table `mytable` has 1000 rows. We make the query to get all rows with `db_chunk_size: 500` parameter:
```
Sqlitex.query(db, "select * from mytable", db_chunk_size: 500)
```
in this case all rows will be passed from native sqlite OS thread to the erlang process in two passes.
Each pass will contain 500 rows.
This parameter decrease overhead of transmitting rows from native OS sqlite thread to the erlang process by
chunking list of result rows.
Please, decrease this value if rows are heavy. Default value is 5000.
If you in doubt what to do with this parameter, please, do nothing. Default value is ok.
```
config :sqlitex, db_chunk_size: 500 # if most of the database rows are heavy
```
"""
alias Sqlitex.Config
@spec close(connection) :: :ok
@spec close(connection, Keyword.t) :: :ok
def close(db, opts \\ []) do
:esqlite3.close(db, Config.db_timeout(opts))
end
@spec open(charlist | String.t) :: {:ok, connection} | {:error, {atom, charlist}}
@spec open(charlist | String.t, Keyword.t) :: {:ok, connection} | {:error, {atom, charlist}}
def open(path, opts \\ [])
def open(path, opts) when is_binary(path), do: open(string_to_charlist(path), opts)
def open(path, opts) do
:esqlite3.open(path, Config.db_timeout(opts))
end
def with_db(path, fun, opts \\ []) do
with {:ok, db} <- open(path, opts) do
res = fun.(db)
close(db, opts)
res
end
end
@doc """
Sets a PID to recieve notifications about table updates.
Messages will come in the shape of:
`{action, table, rowid}`
* `action` -> `:insert | :update | :delete`
* `table` -> charlist of the table name. Example: `'posts'`
* `rowid` -> internal immutable rowid index of the row.
This is *NOT* the `id` or `primary key` of the row.
See the [official docs](https://www.sqlite.org/c3ref/update_hook.html).
"""
@spec set_update_hook(connection, pid, Keyword.t()) :: :ok | {:error, term()}
def set_update_hook(db, pid, opts \\ []) do
:esqlite3.set_update_hook(pid, db, Config.db_timeout(opts))
end
@doc """
Send a raw SQL statement to the database
This function is intended for running fully-complete SQL statements.
No query preparation, or binding of values takes place.
This is generally useful for things like re-playing a SQL export back into the database.
"""
@spec exec(connection, string_or_charlist) :: :ok | sqlite_error
@spec exec(connection, string_or_charlist, Keyword.t) :: :ok | sqlite_error
def exec(db, sql, opts \\ []) do
:esqlite3.exec(sql, db, Config.db_timeout(opts))
end
@doc "A shortcut to `Sqlitex.Query.query/3`"
@spec query(Sqlitex.connection, String.t | charlist) :: {:ok, [keyword]} | {:error, term()}
@spec query(Sqlitex.connection, String.t | charlist, [Sqlitex.Query.query_option]) :: {:ok, [keyword]} | {:error, term()}
def query(db, sql, opts \\ []), do: Sqlitex.Query.query(db, sql, opts)
@doc "A shortcut to `Sqlitex.Query.query!/3`"
@spec query!(Sqlitex.connection, String.t | charlist) :: [keyword]
@spec query!(Sqlitex.connection, String.t | charlist, [Sqlitex.Query.query_option]) :: [Enum.t]
def query!(db, sql, opts \\ []), do: Sqlitex.Query.query!(db, sql, opts)
@doc "A shortcut to `Sqlitex.Query.query_rows/3`"
@spec query_rows(Sqlitex.connection, String.t | charlist) :: {:ok, %{}} | Sqlitex.sqlite_error
@spec query_rows(Sqlitex.connection, String.t | charlist, [Sqlitex.Query.query_option]) :: {:ok, %{}} | Sqlitex.sqlite_error
def query_rows(db, sql, opts \\ []), do: Sqlitex.Query.query_rows(db, sql, opts)
@doc "A shortcut to `Sqlitex.Query.query_rows!/3`"
@spec query_rows!(Sqlitex.connection, String.t | charlist) :: %{}
@spec query_rows!(Sqlitex.connection, String.t | charlist, [Sqlitex.Query.query_option]) :: %{}
def query_rows!(db, sql, opts \\ []), do: Sqlitex.Query.query_rows!(db, sql, opts)
@doc """
Create a new table `name` where `table_opts` is a list of table constraints
and `cols` is a keyword list of columns. The following table constraints are
supported: `:temp` and `:primary_key`. Example:
**[:temp, {:primary_key, [:id]}]**
Columns can be passed as:
* name: :type
* name: {:type, constraints}
where constraints is a list of column constraints. The following column constraints
are supported: `:primary_key`, `:not_null` and `:autoincrement`. Example:
**id: :integer, name: {:text, [:not_null]}**
"""
def create_table(db, name, table_opts \\ [], cols, call_opts \\ []) do
stmt = Sqlitex.SqlBuilder.create_table(name, table_opts, cols)
exec(db, stmt, call_opts)
end
@doc """
Runs `fun` inside a transaction. If `fun` returns without raising an exception,
the transaction will be commited via `commit`. Otherwise, `rollback` will be called.
## Examples
iex> {:ok, db} = Sqlitex.open(":memory:")
iex> Sqlitex.with_transaction(db, fn(db) ->
...> Sqlitex.exec(db, "create table foo(id integer)")
...> Sqlitex.exec(db, "insert into foo (id) values(42)")
...> end)
iex> Sqlitex.query(db, "select * from foo")
{:ok, [[{:id, 42}]]}
"""
@spec with_transaction(Sqlitex.connection, (Sqlitex.connection -> any()), Keyword.t) :: any
def with_transaction(db, fun, opts \\ []) do
with :ok <- exec(db, "begin", opts),
{:ok, result} <- apply_rescuing(fun, [db]),
:ok <- exec(db, "commit", opts)
do
{:ok, result}
else
err ->
:ok = exec(db, "rollback", opts)
err
end
end
if Version.compare(System.version, "1.3.0") == :lt do
defp string_to_charlist(string), do: String.to_char_list(string)
else
defp string_to_charlist(string), do: String.to_charlist(string)
end
## Private Helpers
defp apply_rescuing(fun, args) do
try do
{:ok, apply(fun, args)}
rescue
error -> {:rescued, error, __STACKTRACE__}
end
end
end