Skip to content

Commit d0c96e7

Browse files
greg-rychlewskiGreg Rychlewski
andauthored
expose :mode from connect/1 (#212)
Co-authored-by: Greg Rychlewski <grychle@LLL7WPM64V5M.ngco.com>
1 parent 2edb69d commit d0c96e7

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

lib/exqlite/connection.ex

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,9 @@ defmodule Exqlite.Connection do
8282
8383
* `:database` - The path to the database. In memory is allowed. You can use
8484
`:memory` or `":memory:"` to designate that.
85+
* `:mode` - use `:readwrite` to open the database for reading and writing
86+
or `:readonly` to open it in read-only mode. `:readwrite` will also create
87+
the database if it doesn't already exist. Defaults to `:readwrite`.
8588
* `:journal_mode` - Sets the journal mode for the sqlite connection. Can be
8689
one of the following `:delete`, `:truncate`, `:persist`, `:memory`,
8790
`:wal`, or `:off`. Defaults to `:delete`. It is recommended that you use
@@ -450,7 +453,7 @@ defmodule Exqlite.Connection do
450453

451454
defp do_connect(path, options) do
452455
with :ok <- mkdir_p(path),
453-
{:ok, db} <- Sqlite3.open(path),
456+
{:ok, db} <- Sqlite3.open(path, options),
454457
:ok <- set_key(db, options),
455458
:ok <- set_journal_mode(db, options),
456459
:ok <- set_temp_store(db, options),

test/exqlite/connection_test.exs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,31 @@ defmodule Exqlite.ConnectionTest do
7272

7373
File.rm(path)
7474
end
75+
76+
test "setting connection mode" do
77+
path = Temp.path!()
78+
79+
# Create readwrite connection
80+
{:ok, rw_state} = Connection.connect(database: path)
81+
create_table_query = "create table test (id integer primary key, stuff text)"
82+
:ok = Sqlite3.execute(rw_state.db, create_table_query)
83+
84+
insert_value_query = "insert into test (stuff) values ('This is a test')"
85+
:ok = Sqlite3.execute(rw_state.db, insert_value_query)
86+
87+
# Read from database with a readonly connection
88+
{:ok, ro_state} = Connection.connect(database: path, mode: :readonly)
89+
90+
select_query = "select id, stuff from test order by id asc"
91+
{:ok, statement} = Sqlite3.prepare(ro_state.db, select_query)
92+
{:row, columns} = Sqlite3.step(ro_state.db, statement)
93+
94+
assert [1, "This is a test"] == columns
95+
96+
# Readonly connection cannot insert
97+
assert {:error, "attempt to write a readonly database"} ==
98+
Sqlite3.execute(ro_state.db, insert_value_query)
99+
end
75100
end
76101

77102
defp get_pragma(db, pragma_name) do

0 commit comments

Comments
 (0)