Skip to content

Commit dec23bd

Browse files
authored
Support mkdir -p behavior when DB file does not exist (#180)
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
1 parent aa488d7 commit dec23bd

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

lib/exqlite/connection.ex

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,8 @@ defmodule Exqlite.Connection do
389389
end
390390

391391
defp do_connect(path, options) do
392-
with {:ok, db} <- Sqlite3.open(path),
392+
with :ok <- mkdir_p(path),
393+
{:ok, db} <- Sqlite3.open(path),
393394
:ok <- set_journal_mode(db, options),
394395
:ok <- set_temp_store(db, options),
395396
:ok <- set_synchronous(db, options),
@@ -549,4 +550,11 @@ defmodule Exqlite.Connection do
549550
{:disconnect, %Error{message: reason, statement: statement}, state}
550551
end
551552
end
553+
554+
# SQLITE_OPEN_CREATE will create the DB file if not existing, but
555+
# will not create intermediary directories if they are missing.
556+
# So let's preemptively create the intermediate directories here
557+
# before trying to open the DB file.
558+
defp mkdir_p(":memory:"), do: :ok
559+
defp mkdir_p(path), do: File.mkdir_p(Path.dirname(path))
552560
end

test/exqlite/sqlite3_test.exs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,15 @@ defmodule Exqlite.Sqlite3Test do
1818

1919
File.rm(path)
2020
end
21+
22+
test "creates database path on disk when non-existant" do
23+
{:ok, path} = Temp.mkdir()
24+
{:ok, conn} = Sqlite3.open(path <> "/non_exist.db")
25+
26+
assert conn
27+
28+
File.rm(path)
29+
end
2130
end
2231

2332
describe ".close/2" do

0 commit comments

Comments
 (0)