nitr_http/config/database.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! The `[database]` section: the SQLite file plus connection pragmas.
7
8use std::path::PathBuf;
9
10use serde::{Deserialize, Serialize};
11
12/// SQLite settings (`[database]` section).
13///
14/// Written as a table — `path` is the only required key; the pragma
15/// defaults are what a server should have shipped with: WAL so readers do
16/// not block the writer, a busy timeout so contention is a brief wait
17/// rather than an error, and foreign keys actually enforced.
18#[derive(Debug, Clone, Deserialize, Serialize)]
19#[serde(deny_unknown_fields)]
20pub struct DatabaseConfig {
21 /// Path to the SQLite file.
22 pub path: PathBuf,
23 /// Journal mode. `"wal"` lets readers run alongside one writer;
24 /// `"delete"` (SQLite's default) serializes everything. `"keep"` leaves
25 /// whatever the file already uses, which is the safe choice for a
26 /// database other tools also open.
27 #[serde(default = "default_journal_mode")]
28 pub journal_mode: String,
29 /// Milliseconds a statement waits on a locked database before failing
30 /// with `SQLITE_BUSY`.
31 #[serde(default = "default_busy_timeout")]
32 pub busy_timeout: u64,
33 /// `synchronous` pragma. `"normal"` is the correct pairing with WAL:
34 /// durable across an application crash, and only at risk from a power
35 /// loss mid-checkpoint.
36 #[serde(default = "default_synchronous")]
37 pub synchronous: String,
38 /// Enforce foreign-key constraints. SQLite leaves this off by default,
39 /// which surprises everyone who wrote a `REFERENCES` clause.
40 #[serde(default = "default_foreign_keys")]
41 pub foreign_keys: bool,
42 /// `cache_size` pragma, per connection. Negative values are KiB.
43 #[serde(default = "default_cache_size")]
44 pub cache_size: i64,
45 /// Most rows a single `nitr.db:query` may return; a larger result is
46 /// an error naming this setting. Rows are materialized in memory, so
47 /// this is the ceiling on what one query can allocate.
48 #[serde(default = "default_max_rows")]
49 pub max_rows: usize,
50 /// Directory holding `NNN_name.sql` migrations. Unset looks for
51 /// `migrations/` in the working directory and ignores it when absent.
52 #[serde(default)]
53 pub migrations_dir: Option<PathBuf>,
54}
55
56fn default_journal_mode() -> String {
57 "wal".into()
58}
59fn default_busy_timeout() -> u64 {
60 5_000
61}
62fn default_synchronous() -> String {
63 "normal".into()
64}
65fn default_foreign_keys() -> bool {
66 true
67}
68fn default_cache_size() -> i64 {
69 -2_000 // 2 MiB
70}
71fn default_max_rows() -> usize {
72 10_000
73}
74
75impl DatabaseConfig {
76 /// The defaults for a given path.
77 pub fn new(path: impl Into<PathBuf>) -> Self {
78 Self {
79 path: path.into(),
80 journal_mode: default_journal_mode(),
81 busy_timeout: default_busy_timeout(),
82 synchronous: default_synchronous(),
83 foreign_keys: default_foreign_keys(),
84 cache_size: default_cache_size(),
85 max_rows: default_max_rows(),
86 migrations_dir: None,
87 }
88 }
89
90 /// The migrations directory to use, when one exists.
91 pub fn migrations(&self) -> Option<PathBuf> {
92 match &self.migrations_dir {
93 Some(dir) => Some(dir.clone()),
94 None => {
95 let default = PathBuf::from("migrations");
96 default.is_dir().then_some(default)
97 }
98 }
99 }
100
101 /// The pragma set handed to every connection.
102 pub fn pragmas(&self) -> nitr_std::SqlitePragmas {
103 nitr_std::SqlitePragmas {
104 journal_mode: self.journal_mode.clone(),
105 busy_timeout: self.busy_timeout,
106 synchronous: self.synchronous.clone(),
107 foreign_keys: self.foreign_keys,
108 cache_size: self.cache_size,
109 max_rows: self.max_rows,
110 }
111 }
112}