feat(sqlite): add read_only to SqliteConnectionOptions

This commit is contained in:
Ryan Leckey 2020-07-04 02:55:01 -07:00
parent 3c3356675e
commit d209c60eb7
2 changed files with 18 additions and 3 deletions

View File

@ -4,7 +4,7 @@ use std::ptr::{null, null_mut};
use libsqlite3_sys::{
sqlite3_busy_timeout, sqlite3_extended_result_codes, sqlite3_open_v2, SQLITE_OK,
SQLITE_OPEN_CREATE, SQLITE_OPEN_MEMORY, SQLITE_OPEN_NOMUTEX, SQLITE_OPEN_PRIVATECACHE,
SQLITE_OPEN_READWRITE,
SQLITE_OPEN_READONLY, SQLITE_OPEN_READWRITE,
};
use sqlx_rt::blocking;
@ -33,8 +33,14 @@ pub(super) async fn establish(options: &SqliteConnectOptions) -> Result<SqliteCo
// By default, we connect to an in-memory database.
// [SQLITE_OPEN_NOMUTEX] will instruct [sqlite3_open_v2] to return an error if it
// cannot satisfy our wish for a thread-safe, lock-free connection object
let mut flags =
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_PRIVATECACHE;
let mut flags = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_PRIVATECACHE;
flags |= if options.read_only {
SQLITE_OPEN_READONLY
} else {
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
};
if options.in_memory {
flags |= SQLITE_OPEN_MEMORY;

View File

@ -60,6 +60,7 @@ impl FromStr for SqliteJournalMode {
pub struct SqliteConnectOptions {
pub(crate) filename: PathBuf,
pub(crate) in_memory: bool,
pub(crate) read_only: bool,
pub(crate) journal_mode: SqliteJournalMode,
pub(crate) foreign_keys: bool,
pub(crate) statement_cache_capacity: usize,
@ -76,6 +77,7 @@ impl SqliteConnectOptions {
Self {
filename: PathBuf::from(":memory:"),
in_memory: false,
read_only: false,
foreign_keys: true,
statement_cache_capacity: 100,
journal_mode: SqliteJournalMode::Wal,
@ -99,6 +101,13 @@ impl SqliteConnectOptions {
self
}
/// Sets the [access mode](https://www.sqlite.org/c3ref/open.html) to open the database
/// for read-only access.
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
/// Sets the capacity of the connection's statement cache in a number of stored
/// distinct statements. Caching is handled using LRU, meaning when the
/// amount of queries hits the defined limit, the oldest statement will get