sqlx_core/sqlite/options/mod.rs
1use std::path::Path;
2
3mod auto_vacuum;
4mod connect;
5mod journal_mode;
6mod locking_mode;
7mod parse;
8mod synchronous;
9
10use crate::connection::LogSettings;
11pub use auto_vacuum::SqliteAutoVacuum;
12pub use journal_mode::SqliteJournalMode;
13pub use locking_mode::SqliteLockingMode;
14use std::cmp::Ordering;
15use std::sync::Arc;
16use std::{borrow::Cow, time::Duration};
17pub use synchronous::SqliteSynchronous;
18
19use crate::common::DebugFn;
20use crate::sqlite::connection::collation::Collation;
21use indexmap::IndexMap;
22
23/// Options and flags which can be used to configure a SQLite connection.
24///
25/// A value of `SqliteConnectOptions` can be parsed from a connection URL,
26/// as described by [SQLite](https://www.sqlite.org/uri.html).
27///
28/// | URL | Description |
29/// | -- | -- |
30/// `sqlite::memory:` | Open an in-memory database. |
31/// `sqlite:data.db` | Open the file `data.db` in the current directory. |
32/// `sqlite://data.db` | Open the file `data.db` in the current directory. |
33/// `sqlite:///data.db` | Open the file `data.db` from the root (`/`) directory. |
34/// `sqlite://data.db?mode=ro` | Open the file `data.db` for read-only access. |
35///
36/// # Example
37///
38/// ```rust,no_run
39/// # use sqlx_core::connection::ConnectOptions;
40/// # use sqlx_core::error::Error;
41/// use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode};
42/// use std::str::FromStr;
43///
44/// # fn main() {
45/// # #[cfg(feature = "_rt-async-std")]
46/// # sqlx_rt::async_std::task::block_on::<_, Result<(), Error>>(async move {
47/// let conn = SqliteConnectOptions::from_str("sqlite://data.db")?
48/// .journal_mode(SqliteJournalMode::Wal)
49/// .read_only(true)
50/// .connect().await?;
51/// # Ok(())
52/// # }).unwrap();
53/// # }
54/// ```
55#[derive(Clone, Debug)]
56pub struct SqliteConnectOptions {
57 pub(crate) filename: Cow<'static, Path>,
58 pub(crate) in_memory: bool,
59 pub(crate) read_only: bool,
60 pub(crate) create_if_missing: bool,
61 pub(crate) shared_cache: bool,
62 pub(crate) statement_cache_capacity: usize,
63 pub(crate) busy_timeout: Duration,
64 pub(crate) log_settings: LogSettings,
65 pub(crate) immutable: bool,
66 pub(crate) vfs: Option<Cow<'static, str>>,
67
68 pub(crate) pragmas: IndexMap<Cow<'static, str>, Option<Cow<'static, str>>>,
69 /// Extensions are specified as a pair of <Extension Name : Optional Entry Point>, the majority
70 /// of SQLite extensions will use the default entry points specified in the docs, these should
71 /// be added to the map with a `None` value.
72 /// <https://www.sqlite.org/loadext.html#loading_an_extension>
73 pub(crate) extensions: IndexMap<Cow<'static, str>, Option<Cow<'static, str>>>,
74
75 pub(crate) command_channel_size: usize,
76 pub(crate) row_channel_size: usize,
77
78 pub(crate) collations: Vec<Collation>,
79
80 pub(crate) serialized: bool,
81 pub(crate) thread_name: Arc<DebugFn<dyn Fn(u64) -> String + Send + Sync + 'static>>,
82}
83
84impl Default for SqliteConnectOptions {
85 fn default() -> Self {
86 Self::new()
87 }
88}
89
90impl SqliteConnectOptions {
91 /// Construct `Self` with default options.
92 ///
93 /// See the source of this method for the current defaults.
94 pub fn new() -> Self {
95 let mut pragmas: IndexMap<Cow<'static, str>, Option<Cow<'static, str>>> = IndexMap::new();
96
97 // Standard pragmas
98 //
99 // Most of these don't actually need to be sent because they would be set to their
100 // default values anyway. See the SQLite documentation for default values of these PRAGMAs:
101 // https://www.sqlite.org/pragma.html
102 //
103 // However, by inserting into the map here, we can ensure that they're set in the proper
104 // order, even if they're overwritten later by their respective setters or
105 // directly by `pragma()`
106
107 // SQLCipher special case: if the `key` pragma is set, it must be executed first.
108 pragmas.insert("key".into(), None);
109
110 // Other SQLCipher pragmas that has to be after the key, but before any other operation on the database.
111 // https://www.zetetic.net/sqlcipher/sqlcipher-api/
112
113 // Bytes of the database file that is not encrypted
114 // Default for SQLCipher v4 is 0
115 // If greater than zero 'cipher_salt' pragma must be also defined
116 pragmas.insert("cipher_plaintext_header_size".into(), None);
117
118 // Allows to provide salt manually
119 // By default SQLCipher sets salt automatically, use only in conjunction with
120 // 'cipher_plaintext_header_size' pragma
121 pragmas.insert("cipher_salt".into(), None);
122
123 // Number of iterations used in PBKDF2 key derivation.
124 // Default for SQLCipher v4 is 256000
125 pragmas.insert("kdf_iter".into(), None);
126
127 // Define KDF algorithm to be used.
128 // Default for SQLCipher v4 is PBKDF2_HMAC_SHA512.
129 pragmas.insert("cipher_kdf_algorithm".into(), None);
130
131 // Enable or disable HMAC functionality.
132 // Default for SQLCipher v4 is 1.
133 pragmas.insert("cipher_use_hmac".into(), None);
134
135 // Set default encryption settings depending on the version 1,2,3, or 4.
136 pragmas.insert("cipher_compatibility".into(), None);
137
138 // Page size of encrypted database.
139 // Default for SQLCipher v4 is 4096.
140 pragmas.insert("cipher_page_size".into(), None);
141
142 // Choose algorithm used for HMAC.
143 // Default for SQLCipher v4 is HMAC_SHA512.
144 pragmas.insert("cipher_hmac_algorithm".into(), None);
145
146 // Normally, page_size must be set before any other action on the database.
147 // Defaults to 4096 for new databases.
148 pragmas.insert("page_size".into(), None);
149
150 // locking_mode should be set before journal_mode:
151 // https://www.sqlite.org/wal.html#use_of_wal_without_shared_memory
152 pragmas.insert("locking_mode".into(), None);
153
154 // Don't set `journal_mode` unless the user requested it.
155 // WAL mode is a permanent setting for created databases and changing into or out of it
156 // requires an exclusive lock that can't be waited on with `sqlite3_busy_timeout()`.
157 // https://github.com/launchbadge/sqlx/pull/1930#issuecomment-1168165414
158 pragmas.insert("journal_mode".into(), None);
159
160 // We choose to enable foreign key enforcement by default, though SQLite normally
161 // leaves it off for backward compatibility: https://www.sqlite.org/foreignkeys.html#fk_enable
162 pragmas.insert("foreign_keys".into(), Some("ON".into()));
163
164 // The `synchronous` pragma defaults to FULL
165 // https://www.sqlite.org/compile.html#default_synchronous.
166 pragmas.insert("synchronous".into(), None);
167
168 pragmas.insert("auto_vacuum".into(), None);
169
170 Self {
171 filename: Cow::Borrowed(Path::new(":memory:")),
172 in_memory: false,
173 read_only: false,
174 create_if_missing: false,
175 shared_cache: false,
176 statement_cache_capacity: 100,
177 busy_timeout: Duration::from_secs(5),
178 log_settings: Default::default(),
179 immutable: false,
180 vfs: None,
181 pragmas,
182 extensions: Default::default(),
183 collations: Default::default(),
184 serialized: false,
185 thread_name: Arc::new(DebugFn(|id| format!("sqlx-sqlite-worker-{}", id))),
186 command_channel_size: 50,
187 row_channel_size: 50,
188 }
189 }
190
191 /// Sets the name of the database file.
192 pub fn filename(mut self, filename: impl AsRef<Path>) -> Self {
193 self.filename = Cow::Owned(filename.as_ref().to_owned());
194 self
195 }
196
197 /// Set the enforcement of [foreign key constraints](https://www.sqlite.org/pragma.html#pragma_foreign_keys).
198 ///
199 /// SQLx chooses to enable this by default so that foreign keys function as expected,
200 /// compared to other database flavors.
201 pub fn foreign_keys(self, on: bool) -> Self {
202 self.pragma("foreign_keys", if on { "ON" } else { "OFF" })
203 }
204
205 /// Set the [`SQLITE_OPEN_SHAREDCACHE` flag](https://sqlite.org/sharedcache.html).
206 ///
207 /// By default, this is disabled.
208 pub fn shared_cache(mut self, on: bool) -> Self {
209 self.shared_cache = on;
210 self
211 }
212
213 /// Sets the [journal mode](https://www.sqlite.org/pragma.html#pragma_journal_mode) for the database connection.
214 ///
215 /// Journal modes are ephemeral per connection, with the exception of the
216 /// [Write-Ahead Log (WAL) mode](https://www.sqlite.org/wal.html).
217 ///
218 /// A database created in WAL mode retains the setting and will apply it to all connections
219 /// opened against it that don't set a `journal_mode`.
220 ///
221 /// Opening a connection to a database created in WAL mode with a different `journal_mode` will
222 /// erase the setting on the database, requiring an exclusive lock to do so.
223 /// You may get a `database is locked` (corresponding to `SQLITE_BUSY`) error if another
224 /// connection is accessing the database file at the same time.
225 ///
226 /// SQLx does not set a journal mode by default, to avoid unintentionally changing a database
227 /// into or out of WAL mode.
228 ///
229 /// The default journal mode for non-WAL databases is `DELETE`, or `MEMORY` for in-memory
230 /// databases.
231 ///
232 /// For consistency, any commands in `sqlx-cli` which create a SQLite database will create it
233 /// in WAL mode.
234 pub fn journal_mode(self, mode: SqliteJournalMode) -> Self {
235 self.pragma("journal_mode", mode.as_str())
236 }
237
238 /// Sets the [locking mode](https://www.sqlite.org/pragma.html#pragma_locking_mode) for the database connection.
239 ///
240 /// The default locking mode is NORMAL.
241 pub fn locking_mode(self, mode: SqliteLockingMode) -> Self {
242 self.pragma("locking_mode", mode.as_str())
243 }
244
245 /// Sets the [access mode](https://www.sqlite.org/c3ref/open.html) to open the database
246 /// for read-only access.
247 pub fn read_only(mut self, read_only: bool) -> Self {
248 self.read_only = read_only;
249 self
250 }
251
252 /// Sets the [access mode](https://www.sqlite.org/c3ref/open.html) to create the database file
253 /// if the file does not exist.
254 ///
255 /// By default, a new file **will not be created** if one is not found.
256 pub fn create_if_missing(mut self, create: bool) -> Self {
257 self.create_if_missing = create;
258 self
259 }
260
261 /// Sets the capacity of the connection's statement cache in a number of stored
262 /// distinct statements. Caching is handled using LRU, meaning when the
263 /// amount of queries hits the defined limit, the oldest statement will get
264 /// dropped.
265 ///
266 /// The default cache capacity is 100 statements.
267 pub fn statement_cache_capacity(mut self, capacity: usize) -> Self {
268 self.statement_cache_capacity = capacity;
269 self
270 }
271
272 /// Sets a timeout value to wait when the database is locked, before
273 /// returning a busy timeout error.
274 ///
275 /// The default busy timeout is 5 seconds.
276 pub fn busy_timeout(mut self, timeout: Duration) -> Self {
277 self.busy_timeout = timeout;
278 self
279 }
280
281 /// Sets the [synchronous](https://www.sqlite.org/pragma.html#pragma_synchronous) setting for the database connection.
282 ///
283 /// The default synchronous settings is FULL. However, if durability is not a concern,
284 /// then NORMAL is normally all one needs in WAL mode.
285 pub fn synchronous(self, synchronous: SqliteSynchronous) -> Self {
286 self.pragma("synchronous", synchronous.as_str())
287 }
288
289 /// Sets the [auto_vacuum](https://www.sqlite.org/pragma.html#pragma_auto_vacuum) setting for the database connection.
290 ///
291 /// The default auto_vacuum setting is NONE.
292 ///
293 /// For existing databases, a change to this value does not take effect unless a
294 /// [`VACUUM` command](https://www.sqlite.org/lang_vacuum.html) is executed.
295 pub fn auto_vacuum(self, auto_vacuum: SqliteAutoVacuum) -> Self {
296 self.pragma("auto_vacuum", auto_vacuum.as_str())
297 }
298
299 /// Sets the [page_size](https://www.sqlite.org/pragma.html#pragma_page_size) setting for the database connection.
300 ///
301 /// The default page_size setting is 4096.
302 ///
303 /// For existing databases, a change to this value does not take effect unless a
304 /// [`VACUUM` command](https://www.sqlite.org/lang_vacuum.html) is executed.
305 /// However, it cannot be changed in WAL mode.
306 pub fn page_size(self, page_size: u32) -> Self {
307 self.pragma("page_size", page_size.to_string())
308 }
309
310 /// Sets custom initial pragma for the database connection.
311 pub fn pragma<K, V>(mut self, key: K, value: V) -> Self
312 where
313 K: Into<Cow<'static, str>>,
314 V: Into<Cow<'static, str>>,
315 {
316 self.pragmas.insert(key.into(), Some(value.into()));
317 self
318 }
319
320 /// Add a custom collation for comparing strings in SQL.
321 ///
322 /// If a collation with the same name already exists, it will be replaced.
323 ///
324 /// See [`sqlite3_create_collation()`](https://www.sqlite.org/c3ref/create_collation.html) for details.
325 ///
326 /// Note this excerpt:
327 /// > The collating function must obey the following properties for all strings A, B, and C:
328 /// >
329 /// > If A==B then B==A.
330 /// > If A==B and B==C then A==C.
331 /// > If A\<B then B>A.
332 /// > If A<B and B<C then A<C.
333 /// >
334 /// > If a collating function fails any of the above constraints and that collating function is
335 /// > registered and used, then the behavior of SQLite is undefined.
336 pub fn collation<N, F>(mut self, name: N, collate: F) -> Self
337 where
338 N: Into<Arc<str>>,
339 F: Fn(&str, &str) -> Ordering + Send + Sync + 'static,
340 {
341 self.collations.push(Collation::new(name, collate));
342 self
343 }
344
345 /// Set to `true` to signal to SQLite that the database file is on read-only media.
346 ///
347 /// If enabled, SQLite assumes the database file _cannot_ be modified, even by higher
348 /// privileged processes, and so disables locking and change detection. This is intended
349 /// to improve performance but can produce incorrect query results or errors if the file
350 /// _does_ change.
351 ///
352 /// Note that this is different from the `SQLITE_OPEN_READONLY` flag set by
353 /// [`.read_only()`][Self::read_only], though the documentation suggests that this
354 /// does _imply_ `SQLITE_OPEN_READONLY`.
355 ///
356 /// See [`sqlite3_open`](https://www.sqlite.org/capi3ref.html#sqlite3_open) (subheading
357 /// "URI Filenames") for details.
358 pub fn immutable(mut self, immutable: bool) -> Self {
359 self.immutable = immutable;
360 self
361 }
362
363 /// Sets the [threading mode](https://www.sqlite.org/threadsafe.html) for the database connection.
364 ///
365 /// The default setting is `false` corresponding to using `OPEN_NOMUTEX`.
366 /// If set to `true` then `OPEN_FULLMUTEX`.
367 ///
368 /// See [open](https://www.sqlite.org/c3ref/open.html) for more details.
369 ///
370 /// ### Note
371 /// Setting this to `true` may help if you are getting access violation errors or segmentation
372 /// faults, but will also incur a significant performance penalty. You should leave this
373 /// set to `false` if at all possible.
374 ///
375 /// If you do end up needing to set this to `true` for some reason, please
376 /// [open an issue](https://github.com/launchbadge/sqlx/issues/new/choose) as this may indicate
377 /// a concurrency bug in SQLx. Please provide clear instructions for reproducing the issue,
378 /// including a sample database schema if applicable.
379 pub fn serialized(mut self, serialized: bool) -> Self {
380 self.serialized = serialized;
381 self
382 }
383
384 /// Provide a callback to generate the name of the background worker thread.
385 ///
386 /// The value passed to the callback is an auto-incremented integer for use as the thread ID.
387 pub fn thread_name(
388 mut self,
389 generator: impl Fn(u64) -> String + Send + Sync + 'static,
390 ) -> Self {
391 self.thread_name = Arc::new(DebugFn(generator));
392 self
393 }
394
395 /// Set the maximum number of commands to buffer for the worker thread before backpressure is
396 /// applied.
397 ///
398 /// Given that most commands sent to the worker thread involve waiting for a result,
399 /// the command channel is unlikely to fill up unless a lot queries are executed in a short
400 /// period but cancelled before their full resultsets are returned.
401 pub fn command_buffer_size(mut self, size: usize) -> Self {
402 self.command_channel_size = size;
403 self
404 }
405
406 /// Set the maximum number of rows to buffer back to the calling task when a query is executed.
407 ///
408 /// If the calling task cannot keep up, backpressure will be applied to the worker thread
409 /// in order to limit CPU and memory usage.
410 pub fn row_buffer_size(mut self, size: usize) -> Self {
411 self.row_channel_size = size;
412 self
413 }
414
415 /// Sets the [`vfs`](https://www.sqlite.org/vfs.html) parameter of the database connection.
416 ///
417 /// The default value is empty, and sqlite will use the default VFS object depending on the
418 /// operating system.
419 pub fn vfs(mut self, vfs_name: impl Into<Cow<'static, str>>) -> Self {
420 self.vfs = Some(vfs_name.into());
421 self
422 }
423
424 /// Load an [extension](https://www.sqlite.org/loadext.html) at run-time when the database connection
425 /// is established, using the default entry point.
426 ///
427 /// Most common SQLite extensions can be loaded using this method, for extensions where you need
428 /// to specify the entry point, use [`extension_with_entrypoint`][`Self::extension_with_entrypoint`] instead.
429 ///
430 /// Multiple extensions can be loaded by calling the method repeatedly on the options struct, they
431 /// will be loaded in the order they are added.
432 /// ```rust,no_run
433 /// # use sqlx_core::error::Error;
434 /// use std::str::FromStr;
435 /// use sqlx::sqlite::SqliteConnectOptions;
436 /// # fn options() -> Result<SqliteConnectOptions, Error> {
437 /// let options = SqliteConnectOptions::from_str("sqlite://data.db")?
438 /// .extension("vsv")
439 /// .extension("mod_spatialite");
440 /// # Ok(options)
441 /// # }
442 /// ```
443 pub fn extension(mut self, extension_name: impl Into<Cow<'static, str>>) -> Self {
444 self.extensions.insert(extension_name.into(), None);
445 self
446 }
447
448 /// Load an extension with a specified entry point.
449 ///
450 /// Useful when using non-standard extensions, or when developing your own, the second argument
451 /// specifies where SQLite should expect to find the extension init routine.
452 pub fn extension_with_entrypoint(
453 mut self,
454 extension_name: impl Into<Cow<'static, str>>,
455 entry_point: impl Into<Cow<'static, str>>,
456 ) -> Self {
457 self.extensions
458 .insert(extension_name.into(), Some(entry_point.into()));
459 self
460 }
461}