diff --git a/c_src/sqlite3_nif.c b/c_src/sqlite3_nif.c index 1984e1d..f71b491 100644 --- a/c_src/sqlite3_nif.c +++ b/c_src/sqlite3_nif.c @@ -319,6 +319,15 @@ exqlite_open(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) rc = sqlite3_open_v2((char*)bin.data, &db, flags, NULL); if (rc != SQLITE_OK) { + if (db != NULL) { + char error_msg[1024]; + const char* msg = sqlite3_errmsg(db); + int code = sqlite3_system_errno(db); + snprintf(error_msg, sizeof(error_msg), "%s (errno: %d)", msg, code); + sqlite3_close_v2(db); + return make_error_tuple(env, make_binary(env, error_msg, strlen(error_msg))); + } + return make_error_tuple(env, am_database_open_failed); } diff --git a/test/exqlite/sqlite3_test.exs b/test/exqlite/sqlite3_test.exs index 22f4b98..9af54e6 100644 --- a/test/exqlite/sqlite3_test.exs +++ b/test/exqlite/sqlite3_test.exs @@ -20,6 +20,13 @@ defmodule Exqlite.Sqlite3Test do File.rm(path) end + test "fails opening a database on disk" do + {:ok, path} = Temp.path() + :ok = File.mkdir(path) + {:error, "unable to open database file (errno: " <> _number} = Sqlite3.open(path) + File.rm_rf(path) + end + test "creates database path on disk when non-existent" do {:ok, path} = Temp.mkdir() {:ok, conn} = Sqlite3.open(path <> "/non_exist.db")