turso-orm-driver 0.1.7

Connection pool, transactions and typed rows for the Turso database
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
//! The options a database is opened with, modeled by [`ConnectOptions`].
//!
//! The options cover three layers that the rest of the crate keeps apart:
//! how the engine opens the file (source, read-only, encryption, the
//! experimental feature flags of `turso::Builder`), how the pool behaves
//! (size and acquire timeout) and what every new connection is configured
//! with (busy timeout, `foreign_keys`, MVCC and arbitrary pragmas). This
//! module owns the data and the translation into a `turso::Builder`; it
//! does not open anything, which is [`Database::connect`]'s job.
//!
//! Defaults follow what an application usually wants rather than SQLite's
//! own: foreign keys are enforced, a lock is waited on for five seconds and
//! the pool holds eight connections.
//!
//! - [`ConnectOptions`]: the builder;
//! - [`Source`], [`Encryption`], [`Experimental`]: the pieces of it;
//! - `SyncOptions`: the embedded-replica settings, behind the `sync`
//!   feature;
//! - `RemoteOptions`: the Turso Cloud HTTP settings, behind the
//!   `serverless` feature.
//!
//! [`Database::connect`]: crate::Database::connect

use std::fmt;
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Where the database lives.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Source {
    /// A private in-memory database shared by every connection of the pool.
    Memory,
    /// A local database file, created if missing.
    File(PathBuf),
    /// A local file kept in sync with a Turso Cloud database — an embedded
    /// replica.
    #[cfg(feature = "sync")]
    #[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
    Sync(SyncOptions),
    /// A Turso Cloud database reached over HTTP, with no local file.
    #[cfg(feature = "serverless")]
    #[cfg_attr(docsrs, doc(cfg(feature = "serverless")))]
    Remote(RemoteOptions),
}

/// The settings of a remote Turso Cloud database.
#[cfg(feature = "serverless")]
#[cfg_attr(docsrs, doc(cfg(feature = "serverless")))]
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RemoteOptions {
    /// The database URL (`turso://`, `libsql://` or `https://`).
    pub url: String,
    /// The bearer token for the database.
    pub auth_token: Option<String>,
    /// The base64 key of a database encrypted with a customer-managed key.
    pub remote_encryption_key: Option<String>,
}

#[cfg(feature = "serverless")]
impl fmt::Debug for RemoteOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RemoteOptions")
            .field("url", &self.url)
            .field("auth_token", &self.auth_token.as_ref().map(|_| Redacted))
            .field(
                "remote_encryption_key",
                &self.remote_encryption_key.as_ref().map(|_| Redacted),
            )
            .finish()
    }
}

/// The settings of an embedded replica synchronised with Turso Cloud.
#[cfg(feature = "sync")]
#[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
#[derive(Clone, PartialEq, Eq)]
pub struct SyncOptions {
    /// The local replica file.
    pub path: PathBuf,
    /// The remote database URL (`turso://`, `libsql://` or `https://`).
    pub remote_url: String,
    /// The bearer token for the remote database.
    pub auth_token: Option<String>,
    /// Whether to download the remote database on first open when the local
    /// file is empty.
    pub bootstrap_if_empty: bool,
}

#[cfg(feature = "sync")]
impl fmt::Debug for SyncOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SyncOptions")
            .field("path", &self.path)
            .field("remote_url", &self.remote_url)
            .field("auth_token", &self.auth_token.as_ref().map(|_| Redacted))
            .field("bootstrap_if_empty", &self.bootstrap_if_empty)
            .finish()
    }
}

/// The encryption-at-rest settings — experimental in Turso.
#[derive(Clone, PartialEq, Eq)]
pub struct Encryption {
    /// The cipher name, for example `aes256gcm`.
    pub cipher: String,
    /// The hex-encoded key.
    pub hexkey: String,
}

impl fmt::Debug for Encryption {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Encryption")
            .field("cipher", &self.cipher)
            .field("hexkey", &Redacted)
            .finish()
    }
}

/// Stands in for a secret in `Debug` output, so that options written to a
/// log — a `Database` prints its source — never show a token or a key.
struct Redacted;

impl fmt::Debug for Redacted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("<redacted>")
    }
}

/// Turso engine features that are opt-in because they are still
/// experimental.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
#[allow(
    clippy::struct_excessive_bools,
    reason = "the flags mirror the independent flags of turso::Builder"
)]
pub struct Experimental {
    /// `ATTACH` and `DETACH`.
    pub attach: bool,
    /// `CREATE TYPE`, `CREATE DOMAIN` and array column types.
    pub custom_types: bool,
    /// Virtual generated columns.
    pub generated_columns: bool,
    /// `CREATE INDEX ... USING fts` and vector indexes.
    pub index_method: bool,
    /// `CREATE MATERIALIZED VIEW`.
    pub materialized_views: bool,
    /// In-place `VACUUM`.
    pub vacuum: bool,
    /// Several OS processes opening the same file.
    pub multiprocess_wal: bool,
    /// `WITHOUT ROWID` tables.
    pub without_rowid: bool,
}

/// The options for opening a Turso database.
///
/// ```
/// use std::time::Duration;
/// use turso_orm_driver::ConnectOptions;
///
/// let opts = ConnectOptions::new("app.db")
///     .max_connections(4)
///     .busy_timeout(Duration::from_secs(5))
///     .foreign_keys(true);
/// assert_eq!(opts.max_connections_value(), 4);
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConnectOptions {
    /// Where the database lives.
    pub(crate) source: Source,
    /// Whether to open read-only.
    pub(crate) read_only: bool,
    /// The encryption-at-rest settings, if any.
    pub(crate) encryption: Option<Encryption>,
    /// The experimental engine features to enable.
    pub(crate) experimental: Experimental,
    /// The pool size, at least one.
    pub(crate) max_connections: usize,
    /// How long to wait for a free pooled connection.
    pub(crate) acquire_timeout: Duration,
    /// How long a connection waits on a lock; `None` fails immediately.
    pub(crate) busy_timeout: Option<Duration>,
    /// Whether to enforce foreign keys on every connection.
    pub(crate) foreign_keys: bool,
    /// Whether to switch the journal mode to MVCC on every connection.
    pub(crate) mvcc: bool,
    /// Extra `PRAGMA name = value` pairs run on every new connection.
    pub(crate) pragmas: Vec<(String, String)>,
}

impl ConnectOptions {
    /// The defaults for any source.
    fn with_source(source: Source) -> Self {
        Self {
            source,
            read_only: false,
            encryption: None,
            experimental: Experimental::default(),
            max_connections: 8,
            acquire_timeout: Duration::from_secs(30),
            busy_timeout: Some(Duration::from_secs(5)),
            foreign_keys: true,
            mvcc: false,
            pragmas: Vec::new(),
        }
    }

    /// Opens, or creates, the database file at `path`; `":memory:"` opens
    /// an in-memory database.
    pub fn new(path: impl AsRef<Path>) -> Self {
        let path = path.as_ref();
        if path.as_os_str() == ":memory:" {
            Self::in_memory()
        } else {
            Self::with_source(Source::File(path.to_path_buf()))
        }
    }

    /// Opens a private in-memory database.
    pub fn in_memory() -> Self {
        Self::with_source(Source::Memory)
    }

    /// Opens a local replica of a Turso Cloud database.
    #[cfg(feature = "sync")]
    #[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
    pub fn sync(path: impl AsRef<Path>, remote_url: impl Into<String>) -> Self {
        Self::with_source(Source::Sync(SyncOptions {
            path: path.as_ref().to_path_buf(),
            remote_url: remote_url.into(),
            auth_token: None,
            bootstrap_if_empty: true,
        }))
    }

    /// Opens a Turso Cloud database over HTTP, without a local file.
    ///
    /// Every statement is an HTTP request, so the busy timeout and the
    /// MVCC setting do not apply; the pool, the pragmas and the
    /// transactions do, since each connection is a server-side session.
    #[cfg(feature = "serverless")]
    #[cfg_attr(docsrs, doc(cfg(feature = "serverless")))]
    pub fn remote(url: impl Into<String>) -> Self {
        Self::with_source(Source::Remote(RemoteOptions {
            url: url.into(),
            auth_token: None,
            remote_encryption_key: None,
        }))
    }

    /// Sets the bearer token of a remote database or of an embedded
    /// replica's remote; ignored for local sources.
    #[cfg(any(feature = "sync", feature = "serverless"))]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "sync", feature = "serverless"))))]
    #[must_use]
    pub fn auth_token(mut self, token: impl Into<String>) -> Self {
        match &mut self.source {
            #[cfg(feature = "sync")]
            Source::Sync(opts) => opts.auth_token = Some(token.into()),
            #[cfg(feature = "serverless")]
            Source::Remote(opts) => opts.auth_token = Some(token.into()),
            _ => {}
        }
        self
    }

    /// Sets the base64 key of a remote database encrypted with a
    /// customer-managed key; ignored for other sources.
    #[cfg(feature = "serverless")]
    #[cfg_attr(docsrs, doc(cfg(feature = "serverless")))]
    #[must_use]
    pub fn remote_encryption_key(mut self, key: impl Into<String>) -> Self {
        if let Source::Remote(opts) = &mut self.source {
            opts.remote_encryption_key = Some(key.into());
        }
        self
    }

    /// Opens the database in read-only mode.
    #[must_use]
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.read_only = read_only;
        self
    }

    /// Enables encryption at rest — experimental in Turso.
    #[must_use]
    pub fn encryption(mut self, cipher: impl Into<String>, hexkey: impl Into<String>) -> Self {
        self.encryption = Some(Encryption {
            cipher: cipher.into(),
            hexkey: hexkey.into(),
        });
        self
    }

    /// Enables experimental engine features.
    #[must_use]
    pub fn experimental(mut self, experimental: Experimental) -> Self {
        self.experimental = experimental;
        self
    }

    /// Sets the maximum number of pooled connections (minimum 1, default 8).
    #[must_use]
    pub fn max_connections(mut self, max: usize) -> Self {
        self.max_connections = max.max(1);
        self
    }

    /// Sets how long to wait for a free pooled connection (default 30 s).
    #[must_use]
    pub fn acquire_timeout(mut self, timeout: Duration) -> Self {
        self.acquire_timeout = timeout;
        self
    }

    /// Sets how long a connection waits on a lock before failing with a busy
    /// error (default 5 s); `None` fails immediately.
    ///
    /// The local engine does the waiting itself. An embedded replica's
    /// engine reports a held lock at once instead, so there the driver
    /// retries the connection setup, each statement and each `pull` with a
    /// backoff for this duration, which makes a replica behave like a file.
    #[must_use]
    pub fn busy_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.busy_timeout = timeout.into();
        self
    }

    /// Enforces foreign keys (`PRAGMA foreign_keys = ON`, default on).
    #[must_use]
    pub fn foreign_keys(mut self, enabled: bool) -> Self {
        self.foreign_keys = enabled;
        self
    }

    /// Switches the database to MVCC (`PRAGMA journal_mode = 'mvcc'`), which
    /// enables `BEGIN CONCURRENT` and multiple concurrent writers.
    ///
    /// Experimental in Turso; conflicts surface at commit as busy errors.
    #[must_use]
    pub fn mvcc(mut self, enabled: bool) -> Self {
        self.mvcc = enabled;
        self
    }

    /// Runs `PRAGMA name = value` on every new connection.
    #[must_use]
    pub fn pragma(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.pragmas.push((name.into(), value.into()));
        self
    }

    /// The configured source.
    pub fn source(&self) -> &Source {
        &self.source
    }

    /// The configured pool size.
    pub fn max_connections_value(&self) -> usize {
        self.max_connections
    }

    /// The configured busy timeout.
    pub fn busy_timeout_value(&self) -> Option<Duration> {
        self.busy_timeout
    }

    /// Whether this points at the in-memory database.
    pub fn is_in_memory(&self) -> bool {
        matches!(self.source, Source::Memory)
    }

    /// The budget for retrying a statement that found the database busy,
    /// `Some` for an embedded replica only.
    ///
    /// A local engine waits for a held lock itself, for `busy_timeout`; the
    /// replica's engine reports the lock at once instead, so the driver does
    /// the waiting for it with the same budget. A `None` busy timeout gives a
    /// zero budget: one attempt, no retry.
    #[allow(
        clippy::unused_self,
        reason = "the source is only inspected when the sync feature is on"
    )]
    pub(crate) fn replica_retry_budget(&self) -> Option<Duration> {
        #[cfg(feature = "sync")]
        if matches!(self.source, Source::Sync(_)) {
            return Some(self.busy_timeout.unwrap_or_default());
        }
        None
    }

    /// Builds the engine builder for a local database at `path`, applying
    /// the read-only, encryption and experimental settings.
    pub(crate) fn local_builder(&self, path: &str) -> turso::Builder {
        let mut builder = turso::Builder::new_local(path).read_only(self.read_only);
        if let Some(enc) = &self.encryption {
            builder =
                builder
                    .experimental_encryption(true)
                    .with_encryption(turso::EncryptionOpts {
                        cipher: enc.cipher.clone(),
                        hexkey: enc.hexkey.clone(),
                    });
        }
        let x = self.experimental;
        builder
            .experimental_attach(x.attach)
            .experimental_custom_types(x.custom_types)
            .experimental_generated_columns(x.generated_columns)
            .experimental_index_method(x.index_method)
            .experimental_materialized_views(x.materialized_views)
            .experimental_vacuum(x.vacuum)
            .experimental_multiprocess_wal(x.multiprocess_wal)
            .experimental_without_rowid(x.without_rowid)
    }
}

impl From<&str> for ConnectOptions {
    fn from(path: &str) -> Self {
        Self::new(path)
    }
}

impl From<String> for ConnectOptions {
    fn from(path: String) -> Self {
        Self::new(path)
    }
}

impl From<PathBuf> for ConnectOptions {
    fn from(path: PathBuf) -> Self {
        Self::new(path)
    }
}

impl From<&Path> for ConnectOptions {
    fn from(path: &Path) -> Self {
        Self::new(path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The `Debug` form of the encryption settings shows the cipher and hides the key.
    #[test]
    fn debug_redacts_the_encryption_key() {
        let opts = ConnectOptions::new("app.db").encryption("aes256gcm", "deadbeef");
        let printed = format!("{opts:?}");
        assert!(printed.contains("aes256gcm"));
        assert!(printed.contains("<redacted>"));
        assert!(!printed.contains("deadbeef"));
    }

    /// The `Debug` form of a replica's options shows the URL and hides the token.
    #[cfg(feature = "sync")]
    #[test]
    fn debug_redacts_the_replica_token() {
        let opts = ConnectOptions::sync("replica.db", "turso://db.turso.io").auth_token("s3cret");
        let printed = format!("{opts:?}");
        assert!(printed.contains("turso://db.turso.io"));
        assert!(printed.contains("Some(<redacted>)"));
        assert!(!printed.contains("s3cret"));
    }

    /// The `Debug` form of a remote database's options hides the token and the key.
    #[cfg(feature = "serverless")]
    #[test]
    fn debug_redacts_the_remote_secrets() {
        let opts = ConnectOptions::remote("turso://db.turso.io")
            .auth_token("s3cret")
            .remote_encryption_key("a2V5");
        let printed = format!("{opts:?}");
        assert!(printed.contains("turso://db.turso.io"));
        assert!(!printed.contains("s3cret"));
        assert!(!printed.contains("a2V5"));
    }
}

#[cfg(all(test, feature = "sync"))]
mod replica_tests {
    use super::*;

    /// A replica gets the busy timeout as its retry budget; a local file gets none.
    #[test]
    fn replica_retry_budget_follows_the_source() {
        let replica = ConnectOptions::sync("replica.db", "turso://db.turso.io");
        assert_eq!(replica.replica_retry_budget(), Some(Duration::from_secs(5)));
        let replica = ConnectOptions::sync("replica.db", "turso://db.turso.io").busy_timeout(None);
        assert_eq!(replica.replica_retry_budget(), Some(Duration::ZERO));
        assert_eq!(ConnectOptions::new("app.db").replica_retry_budget(), None);
    }
}