Skip to content

Commit 0400f5e

Browse files
authored
Allow setting key PRAGMA before anything else (#187)
This allows for the use of encrypted sqlite databases
1 parent 240265f commit 0400f5e

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

lib/exqlite/connection.ex

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ defmodule Exqlite.Connection do
9090
* `:busy_timeout` - Sets the busy timeout in milliseconds for a connection.
9191
Default is `2000`.
9292
* `:chunk_size` - The chunk size for bulk fetching. Defaults to `50`.
93+
* `:key` - Optional key to set during database initialization. This PRAGMA
94+
is often used to set up database level encryption.
9395
9496
For more information about the options above, see [sqlite documenation][1]
9597
@@ -340,6 +342,16 @@ defmodule Exqlite.Connection do
340342
end
341343
end
342344

345+
defp set_key(db, options) do
346+
# we can't use maybe_set_pragma here since
347+
# the only thing that will work on an encrypted
348+
# database without error is setting the key.
349+
case Keyword.fetch(options, :key) do
350+
{:ok, key} -> set_pragma(db, "key", key)
351+
_ -> :ok
352+
end
353+
end
354+
343355
defp set_journal_mode(db, options) do
344356
maybe_set_pragma(db, "journal_mode", Pragma.journal_mode(options))
345357
end
@@ -391,6 +403,7 @@ defmodule Exqlite.Connection do
391403
defp do_connect(path, options) do
392404
with :ok <- mkdir_p(path),
393405
{:ok, db} <- Sqlite3.open(path),
406+
:ok <- set_key(db, options),
394407
:ok <- set_journal_mode(db, options),
395408
:ok <- set_temp_store(db, options),
396409
:ok <- set_synchronous(db, options),

0 commit comments

Comments
 (0)