reifydb-sqlite 0.4.13

Shared SQLite configuration types used by ReifyDB storage subsystems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2025 ReifyDB

#[cfg(not(target_os = "linux"))]
use std::env;
use std::path::{Path, PathBuf};

use uuid::Uuid;

#[cfg(not(target_arch = "wasm32"))]
pub mod connection;
#[cfg(not(target_arch = "wasm32"))]
pub mod error;
#[cfg(not(target_arch = "wasm32"))]
pub mod pragma;

/// Where the SQLite database file lives on disk.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum DbPath {
	/// A regular file path.
	File(PathBuf),
	/// Tmpfs-backed file for WAL support + automatic cleanup.
	Tmpfs(PathBuf),
	/// RAM-backed file for storage with WAL support + automatic cleanup.
	Memory(PathBuf),
}

fn memory_dir() -> PathBuf {
	#[cfg(target_os = "linux")]
	{
		PathBuf::from("/dev/shm")
	}
	#[cfg(not(target_os = "linux"))]
	{
		env::temp_dir()
	}
}

/// Configuration for a SQLite storage backend.
#[derive(Debug, Clone)]
pub struct SqliteConfig {
	pub path: DbPath,
	pub flags: OpenFlags,
	pub journal_mode: JournalMode,
	pub synchronous_mode: SynchronousMode,
	pub temp_store: TempStore,
	pub cache_size: u32,
	pub wal_autocheckpoint: u32,
	pub page_size: u32,
	pub mmap_size: u64,
}

impl SqliteConfig {
	/// Balanced production defaults.
	/// - WAL journal + NORMAL synchronous: durable across crashes, one fsync per commit
	/// - 8 MiB page cache (2000 pages * 4 KiB) covers a typical hot working set
	/// - 64 MiB mmap window for fast cold reads
	/// - 4 KiB pages match the kernel page size
	/// - Override `cache_size` / `mmap_size` via the fluent builder for unusual workloads.
	pub fn new<P: AsRef<Path>>(path: P) -> Self {
		Self {
			path: DbPath::File(path.as_ref().to_path_buf()),
			flags: OpenFlags::default(),
			journal_mode: JournalMode::Wal,
			synchronous_mode: SynchronousMode::Normal,
			temp_store: TempStore::Memory,
			cache_size: 2000,
			wal_autocheckpoint: 1000,
			page_size: 4096,
			mmap_size: 64 * 1024 * 1024,
		}
	}

	/// Safety-first configuration optimized for data integrity.
	/// - WAL journal mode for crash recovery
	/// - FULL synchronous mode forces fsync on every commit
	/// - FILE temp store so a big sort cannot blow up RSS
	/// - mmap disabled: reads must go through the fsync-respecting page cache
	pub fn safe<P: AsRef<Path>>(path: P) -> Self {
		Self {
			path: DbPath::File(path.as_ref().to_path_buf()),
			flags: OpenFlags::default(),
			journal_mode: JournalMode::Wal,
			synchronous_mode: SynchronousMode::Full,
			temp_store: TempStore::File,
			cache_size: 2000,
			wal_autocheckpoint: 1000,
			page_size: 4096,
			mmap_size: 0,
		}
	}

	/// High-performance configuration optimized for throughput.
	/// - WAL journal so a crash can still replay batched writes
	/// - OFF synchronous mode skips fsync entirely (data may be lost on power loss)
	/// - 16 KiB pages cut per-page metadata overhead for large tables
	/// - 160 MiB page cache (10000 pages * 16 KiB) and 256 MiB mmap window
	/// - WAL allowed to grow up to 10000 pages before checkpoint
	pub fn fast<P: AsRef<Path>>(path: P) -> Self {
		Self {
			path: DbPath::File(path.as_ref().to_path_buf()),
			flags: OpenFlags::default(),
			journal_mode: JournalMode::Wal,
			synchronous_mode: SynchronousMode::Off,
			temp_store: TempStore::Memory,
			cache_size: 10000,
			wal_autocheckpoint: 10000,
			page_size: 16384,
			mmap_size: 256 * 1024 * 1024,
		}
	}

	/// Tmpfs-backed configuration for ephemeral database storage.
	/// Uses /tmp (often tmpfs). The DB file already lives in RAM, so mmap is
	/// disabled; mmap'ing a tmpfs file would just give the process a second
	/// resident copy of every page.
	pub fn tmpfs() -> Self {
		Self {
			path: DbPath::Tmpfs(PathBuf::from(format!("/tmp/reifydb_{}.db", Uuid::new_v4()))),
			flags: OpenFlags::default(),
			journal_mode: JournalMode::Wal,
			synchronous_mode: SynchronousMode::Off,
			temp_store: TempStore::Memory,
			cache_size: 2000,
			wal_autocheckpoint: 10000,
			page_size: 16384,
			mmap_size: 0,
		}
	}

	/// In-memory configuration backed by /dev/shm on Linux, temp dir elsewhere.
	/// Same reasoning as `tmpfs`: the file lives in RAM, so mmap is disabled
	/// to avoid the second resident copy.
	pub fn in_memory() -> Self {
		Self {
			path: DbPath::Memory(memory_dir().join(format!("reifydb_{}.db", Uuid::new_v4()))),
			flags: OpenFlags::default(),
			journal_mode: JournalMode::Wal,
			synchronous_mode: SynchronousMode::Off,
			temp_store: TempStore::Memory,
			cache_size: 2000,
			wal_autocheckpoint: 10000,
			page_size: 16384,
			mmap_size: 0,
		}
	}

	/// Test configuration with an in-memory database and minimal cache.
	/// Uses /dev/shm on Linux, temp dir on other platforms.
	pub fn test() -> Self {
		Self {
			path: DbPath::Memory(memory_dir().join(format!("reifydb_{}.db", Uuid::new_v4()))),
			flags: OpenFlags::default(),
			journal_mode: JournalMode::Wal,
			synchronous_mode: SynchronousMode::Off,
			temp_store: TempStore::Memory,
			cache_size: 1000,
			wal_autocheckpoint: 10000,
			page_size: 4096,
			mmap_size: 0,
		}
	}

	pub fn path<P: AsRef<Path>>(mut self, path: P) -> Self {
		self.path = DbPath::File(path.as_ref().to_path_buf());
		self
	}

	pub fn flags(mut self, flags: OpenFlags) -> Self {
		self.flags = flags;
		self
	}

	pub fn journal_mode(mut self, mode: JournalMode) -> Self {
		self.journal_mode = mode;
		self
	}

	pub fn synchronous_mode(mut self, mode: SynchronousMode) -> Self {
		self.synchronous_mode = mode;
		self
	}

	pub fn temp_store(mut self, store: TempStore) -> Self {
		self.temp_store = store;
		self
	}

	pub fn cache_size(mut self, size_kb: u32) -> Self {
		self.cache_size = size_kb;
		self
	}

	pub fn wal_autocheckpoint(mut self, pages: u32) -> Self {
		self.wal_autocheckpoint = pages;
		self
	}

	/// Set the page size in bytes (must be a power of 2 between 512 and 65536).
	/// Must be set before the database is created; changing the page size
	/// on an existing database requires a VACUUM.
	pub fn page_size(mut self, size: u32) -> Self {
		self.page_size = size;
		self
	}

	/// Memory-mapped I/O size in bytes (0 = disabled).
	pub fn mmap_size(mut self, size: u64) -> Self {
		self.mmap_size = size;
		self
	}
}

impl Default for SqliteConfig {
	fn default() -> Self {
		Self::new("reifydb.db")
	}
}

/// SQLite database open flags.
#[derive(Debug, Clone)]
pub struct OpenFlags {
	pub read_write: bool,
	pub create: bool,
	pub full_mutex: bool,
	pub no_mutex: bool,
	pub shared_cache: bool,
	pub private_cache: bool,
	pub uri: bool,
}

impl OpenFlags {
	pub fn new() -> Self {
		Self::default()
	}

	pub fn read_write(mut self, enabled: bool) -> Self {
		self.read_write = enabled;
		self
	}

	pub fn create(mut self, enabled: bool) -> Self {
		self.create = enabled;
		self
	}

	pub fn full_mutex(mut self, enabled: bool) -> Self {
		self.full_mutex = enabled;
		self.no_mutex = !enabled;
		self
	}

	pub fn no_mutex(mut self, enabled: bool) -> Self {
		self.no_mutex = enabled;
		self.full_mutex = !enabled;
		self
	}

	pub fn shared_cache(mut self, enabled: bool) -> Self {
		self.shared_cache = enabled;
		self.private_cache = !enabled;
		self
	}

	pub fn private_cache(mut self, enabled: bool) -> Self {
		self.private_cache = enabled;
		self.shared_cache = !enabled;
		self
	}

	pub fn uri(mut self, enabled: bool) -> Self {
		self.uri = enabled;
		self
	}
}

impl Default for OpenFlags {
	fn default() -> Self {
		Self {
			read_write: true,
			create: true,
			full_mutex: true,
			no_mutex: false,
			shared_cache: false,
			private_cache: false,
			uri: false,
		}
	}
}

/// SQLite journal mode options.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JournalMode {
	Delete,
	Truncate,
	Persist,
	Memory,
	Wal,
	Off,
}

impl JournalMode {
	pub fn as_str(&self) -> &'static str {
		match self {
			JournalMode::Delete => "DELETE",
			JournalMode::Truncate => "TRUNCATE",
			JournalMode::Persist => "PERSIST",
			JournalMode::Memory => "MEMORY",
			JournalMode::Wal => "WAL",
			JournalMode::Off => "OFF",
		}
	}
}

/// SQLite synchronous mode options.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SynchronousMode {
	Off,
	Normal,
	Full,
	Extra,
}

impl SynchronousMode {
	pub fn as_str(&self) -> &'static str {
		match self {
			SynchronousMode::Off => "OFF",
			SynchronousMode::Normal => "NORMAL",
			SynchronousMode::Full => "FULL",
			SynchronousMode::Extra => "EXTRA",
		}
	}
}

/// SQLite temporary storage location.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TempStore {
	Default,
	File,
	Memory,
}

impl TempStore {
	pub fn as_str(&self) -> &'static str {
		match self {
			TempStore::Default => "DEFAULT",
			TempStore::File => "FILE",
			TempStore::Memory => "MEMORY",
		}
	}
}

#[cfg(test)]
mod tests {
	use reifydb_testing::tempdir::temp_dir;

	use super::*;

	#[test]
	fn test_config_fluent_api() {
		let config = SqliteConfig::new("/tmp/test.reifydb")
			.journal_mode(JournalMode::Wal)
			.synchronous_mode(SynchronousMode::Normal)
			.temp_store(TempStore::Memory)
			.cache_size(30000)
			.flags(OpenFlags::new().read_write(true).create(true).full_mutex(true));

		assert_eq!(config.path, DbPath::File(PathBuf::from("/tmp/test.reifydb")));
		assert_eq!(config.journal_mode, JournalMode::Wal);
		assert_eq!(config.synchronous_mode, SynchronousMode::Normal);
		assert_eq!(config.temp_store, TempStore::Memory);
		assert_eq!(config.cache_size, 30000);
		assert!(config.flags.read_write);
		assert!(config.flags.create);
		assert!(config.flags.full_mutex);
	}

	#[test]
	fn test_enum_string_conversion() {
		assert_eq!(JournalMode::Wal.as_str(), "WAL");
		assert_eq!(SynchronousMode::Normal.as_str(), "NORMAL");
		assert_eq!(TempStore::Memory.as_str(), "MEMORY");
	}

	#[test]
	fn test_all_journal_modes() {
		assert_eq!(JournalMode::Delete.as_str(), "DELETE");
		assert_eq!(JournalMode::Truncate.as_str(), "TRUNCATE");
		assert_eq!(JournalMode::Persist.as_str(), "PERSIST");
		assert_eq!(JournalMode::Memory.as_str(), "MEMORY");
		assert_eq!(JournalMode::Wal.as_str(), "WAL");
		assert_eq!(JournalMode::Off.as_str(), "OFF");
	}

	#[test]
	fn test_all_synchronous_modes() {
		assert_eq!(SynchronousMode::Off.as_str(), "OFF");
		assert_eq!(SynchronousMode::Normal.as_str(), "NORMAL");
		assert_eq!(SynchronousMode::Full.as_str(), "FULL");
		assert_eq!(SynchronousMode::Extra.as_str(), "EXTRA");
	}

	#[test]
	fn test_all_temp_store_modes() {
		assert_eq!(TempStore::Default.as_str(), "DEFAULT");
		assert_eq!(TempStore::File.as_str(), "FILE");
		assert_eq!(TempStore::Memory.as_str(), "MEMORY");
	}

	#[test]
	fn test_default_config() {
		let config = SqliteConfig::default();
		assert_eq!(config.path, DbPath::File(PathBuf::from("reifydb.db")));
		assert_eq!(config.journal_mode, JournalMode::Wal);
		assert_eq!(config.synchronous_mode, SynchronousMode::Normal);
		assert_eq!(config.temp_store, TempStore::Memory);
	}

	#[test]
	fn test_safe_config() {
		temp_dir(|db_path| {
			let db_file = db_path.join("safe.reifydb");
			let config = SqliteConfig::safe(&db_file);

			assert_eq!(config.path, DbPath::File(db_file));
			assert_eq!(config.journal_mode, JournalMode::Wal);
			assert_eq!(config.synchronous_mode, SynchronousMode::Full);
			assert_eq!(config.temp_store, TempStore::File);
			Ok(())
		})
		.expect("test failed");
	}

	#[test]
	fn test_fast_config() {
		temp_dir(|db_path| {
			let db_file = db_path.join("fast.reifydb");
			let config = SqliteConfig::fast(&db_file);

			assert_eq!(config.path, DbPath::File(db_file));
			assert_eq!(config.journal_mode, JournalMode::Wal);
			assert_eq!(config.synchronous_mode, SynchronousMode::Off);
			assert_eq!(config.temp_store, TempStore::Memory);
			Ok(())
		})
		.expect("test failed");
	}

	#[test]
	fn test_tmpfs_config() {
		let config = SqliteConfig::tmpfs();

		match config.path {
			DbPath::Tmpfs(path) => {
				assert!(path.to_string_lossy().starts_with("/tmp/reifydb_"));
				assert!(path.to_string_lossy().ends_with(".db"));
			}
			_ => panic!("Expected DbPath::Tmpfs variant"),
		}

		assert_eq!(config.journal_mode, JournalMode::Wal);
		assert_eq!(config.synchronous_mode, SynchronousMode::Off);
		assert_eq!(config.temp_store, TempStore::Memory);
		assert_eq!(config.cache_size, 2000);
		assert_eq!(config.wal_autocheckpoint, 10000);
	}

	#[test]
	fn test_config_chaining() {
		temp_dir(|db_path| {
			let db_file = db_path.join("chain.reifydb");

			let config = SqliteConfig::new(&db_file)
				.journal_mode(JournalMode::Delete)
				.synchronous_mode(SynchronousMode::Extra)
				.temp_store(TempStore::File)
				.flags(OpenFlags::new().read_write(false).create(false).shared_cache(true));

			assert_eq!(config.journal_mode, JournalMode::Delete);
			assert_eq!(config.synchronous_mode, SynchronousMode::Extra);
			assert_eq!(config.temp_store, TempStore::File);
			assert!(!config.flags.read_write);
			assert!(!config.flags.create);
			assert!(config.flags.shared_cache);
			Ok(())
		})
		.expect("test failed");
	}

	#[test]
	fn test_open_flags_mutex_exclusivity() {
		let flags = OpenFlags::new().full_mutex(true);
		assert!(flags.full_mutex);
		assert!(!flags.no_mutex);

		let flags = OpenFlags::new().no_mutex(true);
		assert!(!flags.full_mutex);
		assert!(flags.no_mutex);
	}

	#[test]
	fn test_open_flags_cache_exclusivity() {
		let flags = OpenFlags::new().shared_cache(true);
		assert!(flags.shared_cache);
		assert!(!flags.private_cache);

		let flags = OpenFlags::new().private_cache(true);
		assert!(!flags.shared_cache);
		assert!(flags.private_cache);
	}

	#[test]
	fn test_open_flags_all_combinations() {
		let flags =
			OpenFlags::new().read_write(true).create(true).full_mutex(true).shared_cache(true).uri(true);

		assert!(flags.read_write);
		assert!(flags.create);
		assert!(flags.full_mutex);
		assert!(!flags.no_mutex);
		assert!(flags.shared_cache);
		assert!(!flags.private_cache);
		assert!(flags.uri);
	}

	#[test]
	fn test_path_handling() {
		temp_dir(|db_path| {
			let file_path = db_path.join("test.reifydb");
			let config = SqliteConfig::new(&file_path);
			assert_eq!(config.path, DbPath::File(file_path));

			let config = SqliteConfig::new(db_path);
			assert_eq!(config.path, DbPath::File(db_path.to_path_buf()));
			Ok(())
		})
		.expect("test failed");
	}
}