Skip to content

Commit

Permalink
Support mkdir -p behavior when DB file does not exist (#180)
Browse files Browse the repository at this point in the history
Currently, if you supply a DB path that includes directories which
do not exist, sqlite3 will not attempt to create them and the open
will crash.

This adds a quick attempt to `mkdir` on the db path to ensure all intermediary
directories exist before attempting to create the DB file for cases that
`SQLITE_OPEN_CREATE` flag is enabled and would expect the file to be
created when non-existant
  • Loading branch information
jjcarstens authored Dec 7, 2021
1 parent aa488d7 commit dec23bd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/exqlite/connection.ex
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,8 @@ defmodule Exqlite.Connection do
end

defp do_connect(path, options) do
with {:ok, db} <- Sqlite3.open(path),
with :ok <- mkdir_p(path),
{:ok, db} <- Sqlite3.open(path),
:ok <- set_journal_mode(db, options),
:ok <- set_temp_store(db, options),
:ok <- set_synchronous(db, options),
Expand Down Expand Up @@ -549,4 +550,11 @@ defmodule Exqlite.Connection do
{:disconnect, %Error{message: reason, statement: statement}, state}
end
end

# SQLITE_OPEN_CREATE will create the DB file if not existing, but
# will not create intermediary directories if they are missing.
# So let's preemptively create the intermediate directories here
# before trying to open the DB file.
defp mkdir_p(":memory:"), do: :ok
defp mkdir_p(path), do: File.mkdir_p(Path.dirname(path))
end
9 changes: 9 additions & 0 deletions test/exqlite/sqlite3_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ defmodule Exqlite.Sqlite3Test do

File.rm(path)
end

test "creates database path on disk when non-existant" do
{:ok, path} = Temp.mkdir()
{:ok, conn} = Sqlite3.open(path <> "/non_exist.db")

assert conn

File.rm(path)
end
end

describe ".close/2" do
Expand Down

0 comments on commit dec23bd

Please sign in to comment.