feat: support in-memory SQLite database

This commit is contained in:
Greg Heartsfield 2022-09-06 06:06:01 -05:00
parent 8774416b92
commit e48bae10e6
3 changed files with 20 additions and 6 deletions

View File

@ -22,6 +22,11 @@ description = "A newly created nostr-rs-relay.\n\nCustomize this with your own i
# line option. # line option.
data_directory = "." data_directory = "."
# Use an in-memory database instead of 'nostr.db'.
# Caution; this will not survive a process restart!
#in_memory = false
# Database connection pool settings for subscribers: # Database connection pool settings for subscribers:
# Minimum number of SQLite reader connections # Minimum number of SQLite reader connections

View File

@ -25,6 +25,7 @@ pub struct Info {
#[allow(unused)] #[allow(unused)]
pub struct Database { pub struct Database {
pub data_directory: String, pub data_directory: String,
pub in_memory: bool,
pub min_conn: u32, pub min_conn: u32,
pub max_conn: u32, pub max_conn: u32,
} }
@ -189,6 +190,7 @@ impl Default for Settings {
}, },
database: Database { database: Database {
data_directory: ".".to_owned(), data_directory: ".".to_owned(),
in_memory: false,
min_conn: 4, min_conn: 4,
max_conn: 128, max_conn: 128,
}, },

View File

@ -54,13 +54,20 @@ pub fn build_pool(
// small hack; if the database doesn't exist yet, that means the // small hack; if the database doesn't exist yet, that means the
// writer thread hasn't finished. Give it a chance to work. This // writer thread hasn't finished. Give it a chance to work. This
// is only an issue with the first time we run. // is only an issue with the first time we run.
if !settings.database.in_memory {
while !full_path.exists() && wait_for_db { while !full_path.exists() && wait_for_db {
debug!("Database reader pool is waiting on the database to be created..."); debug!("Database reader pool is waiting on the database to be created...");
thread::sleep(Duration::from_millis(500)); thread::sleep(Duration::from_millis(500));
} }
let manager = SqliteConnectionManager::file(&full_path) }
let manager = match settings.database.in_memory {
true => SqliteConnectionManager::memory()
.with_flags(flags) .with_flags(flags)
.with_init(|c| c.execute_batch(STARTUP_SQL)); .with_init(|c| c.execute_batch(STARTUP_SQL)),
false => SqliteConnectionManager::file(&full_path)
.with_flags(flags)
.with_init(|c| c.execute_batch(STARTUP_SQL)),
};
let pool: SqlitePool = r2d2::Pool::builder() let pool: SqlitePool = r2d2::Pool::builder()
.test_on_check_out(true) // no noticeable performance hit .test_on_check_out(true) // no noticeable performance hit
.min_idle(Some(min_size)) .min_idle(Some(min_size))