Skip to main content

renox_core/db/
conn.rs

1//! Renox's own handle on the database, so the same code runs on SQLite and
2//! PostgreSQL: [`Db`] (the pool), [`Transaction`], [`Row`] and raw SQL
3//! through [`sql()`].
4//!
5//! SQL written for Renox uses `?` placeholders. On PostgreSQL they become
6//! `$1`, `$2`, … before the query is sent (a `?` inside quotes or comments is
7//! left alone).
8
9#[cfg(any(feature = "postgres", test))]
10use std::borrow::Cow;
11use std::fmt;
12use std::sync::Arc;
13
14use cookie::Key;
15
16use sqlx::sqlite::{Sqlite, SqliteArguments, SqlitePool, SqliteRow};
17use sqlx::{AssertSqlSafe, Column, Row as _};
18
19use super::value::DbValue;
20use super::{DbError, ToDbValue};
21
22#[cfg(feature = "postgres")]
23use sqlx::postgres::{PgArguments, PgPool, PgRow, Postgres};
24
25/// Which database engine a [`Db`] talks to.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Dialect {
28    /// SQLite.
29    Sqlite,
30    /// PostgreSQL (the `postgres` feature).
31    Postgres,
32}
33
34impl fmt::Display for Dialect {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.write_str(match self {
37            Dialect::Sqlite => "sqlite",
38            Dialect::Postgres => "postgres",
39        })
40    }
41}
42
43/// The database pool. Take it in a handler with `State(db): State<Db>`.
44///
45/// Models, queries and [`sql()`] take `&db` (or `&mut tx` inside a
46/// [`Transaction`]). For something only sqlx can do, reach the underlying
47/// pool with [`Db::sqlite`] or `Db::postgres` (with the `postgres` feature).
48#[derive(Clone)]
49pub struct Db {
50    pool: Pool,
51    schema: SchemaEpoch,
52    /// Seals and opens `Encrypted` columns (`APP_KEY`, set at boot).
53    key: Option<Arc<Key>>,
54    /// Custom field definitions, by model (`custom_fields.rs`).
55    custom_fields: crate::custom_fields::Cache,
56}
57
58/// When this process last changed the schema (migrations ran).
59///
60/// A pooled connection keeps the schema it read, and prepares statements
61/// against it until it next steps one. sqlx takes a statement's columns from
62/// that first prepare, so after `ALTER TABLE users ADD COLUMN …` a
63/// `SELECT *` on an older connection gets one column more than sqlx expects
64/// and panics (sqlx-sqlite `row.rs`), or PostgreSQL refuses a cached plan.
65/// The pools made by [`super::connect`] drop connections opened before the
66/// last change instead of reusing them.
67#[derive(Clone, Default)]
68pub(crate) struct SchemaEpoch(std::sync::Arc<std::sync::Mutex<Option<std::time::Instant>>>);
69
70impl SchemaEpoch {
71    pub(crate) fn changed(&self) {
72        *self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(std::time::Instant::now());
73    }
74
75    /// Whether a connection of this age was opened before the last change.
76    pub(crate) fn is_stale(&self, age: std::time::Duration) -> bool {
77        self.0
78            .lock()
79            .unwrap_or_else(|e| e.into_inner())
80            .is_some_and(|at| age >= at.elapsed())
81    }
82}
83
84#[derive(Clone)]
85enum Pool {
86    Sqlite(SqlitePool),
87    #[cfg(feature = "postgres")]
88    Postgres(PgPool),
89}
90
91impl fmt::Debug for Db {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        f.debug_struct("Db")
94            .field("dialect", &self.dialect())
95            .finish_non_exhaustive()
96    }
97}
98
99impl From<SqlitePool> for Db {
100    fn from(pool: SqlitePool) -> Self {
101        Self::with_epoch(Pool::Sqlite(pool), SchemaEpoch::default())
102    }
103}
104
105#[cfg(feature = "postgres")]
106impl From<PgPool> for Db {
107    fn from(pool: PgPool) -> Self {
108        Self::with_epoch(Pool::Postgres(pool), SchemaEpoch::default())
109    }
110}
111
112impl Db {
113    fn with_epoch(pool: Pool, schema: SchemaEpoch) -> Self {
114        Self {
115            pool,
116            schema,
117            key: None,
118            custom_fields: Default::default(),
119        }
120    }
121
122    /// The key `Encrypted` columns are sealed and opened with (the app's
123    /// `APP_KEY`, set at boot).
124    pub(crate) fn with_key(mut self, key: Key) -> Self {
125        self.key = Some(Arc::new(key));
126        self
127    }
128
129    pub(crate) fn from_sqlite(pool: SqlitePool, schema: SchemaEpoch) -> Self {
130        Self::with_epoch(Pool::Sqlite(pool), schema)
131    }
132
133    #[cfg(feature = "postgres")]
134    pub(crate) fn from_postgres(pool: PgPool, schema: SchemaEpoch) -> Self {
135        Self::with_epoch(Pool::Postgres(pool), schema)
136    }
137
138    /// The `APP_KEY`-derived key, when this Db was made by an app.
139    pub(crate) fn seal_key(&self) -> Option<&Key> {
140        self.key.as_deref()
141    }
142
143    pub(crate) fn custom_fields_cache(&self) -> &crate::custom_fields::Cache {
144        &self.custom_fields
145    }
146
147    /// Records that the schema changed, so older pooled connections aren't
148    /// reused (see `SchemaEpoch`).
149    pub(crate) fn schema_changed(&self) {
150        self.schema.changed();
151    }
152
153    /// The engine this pool talks to.
154    pub fn dialect(&self) -> Dialect {
155        match self.pool {
156            Pool::Sqlite(_) => Dialect::Sqlite,
157            #[cfg(feature = "postgres")]
158            Pool::Postgres(_) => Dialect::Postgres,
159        }
160    }
161
162    /// The sqlx pool, when the database is SQLite.
163    pub fn sqlite(&self) -> Option<&SqlitePool> {
164        match &self.pool {
165            Pool::Sqlite(pool) => Some(pool),
166            #[cfg(feature = "postgres")]
167            Pool::Postgres(_) => None,
168        }
169    }
170
171    /// The sqlx pool, when the database is PostgreSQL.
172    #[cfg(feature = "postgres")]
173    pub fn postgres(&self) -> Option<&PgPool> {
174        match &self.pool {
175            Pool::Postgres(pool) => Some(pool),
176            Pool::Sqlite(_) => None,
177        }
178    }
179
180    /// Starts a transaction. Pass `&mut tx` wherever a `&db` goes, then
181    /// `tx.commit()`; dropping it without committing rolls it back.
182    pub async fn begin(&self) -> Result<Transaction, DbError> {
183        let inner = match &self.pool {
184            Pool::Sqlite(pool) => TxInner::Sqlite(pool.begin().await?),
185            #[cfg(feature = "postgres")]
186            Pool::Postgres(pool) => TxInner::Postgres(pool.begin().await?),
187        };
188        Ok(Transaction {
189            inner,
190            key: self.key.clone(),
191            savepoints: 0,
192        })
193    }
194
195    /// Runs `work` in a transaction: committed when it returns `Ok`, rolled
196    /// back when it returns `Err`.
197    ///
198    /// ```
199    /// # use renox::prelude::*;
200    /// # async fn demo(db: Db) -> Result {
201    /// let moved = db
202    ///     .transaction_retrying(3, |tx| {
203    ///         Box::pin(async move {
204    ///             renox::db::sql("UPDATE accounts SET balance = balance - 100 WHERE id = 1")
205    ///                 .execute(&mut *tx)
206    ///                 .await?;
207    ///             renox::db::sql("UPDATE accounts SET balance = balance + 100 WHERE id = 2")
208    ///                 .execute(&mut *tx)
209    ///                 .await?;
210    ///             Ok(100)
211    ///         })
212    ///     })
213    ///     .await?;
214    /// # let _: i64 = moved; Ok(()) }
215    /// ```
216    pub async fn transaction<T, F>(&self, work: F) -> crate::Result<T>
217    where
218        F: for<'t> FnMut(
219            &'t mut Transaction,
220        ) -> futures_util::future::BoxFuture<'t, crate::Result<T>>,
221    {
222        self.transaction_retrying(1, work).await
223    }
224
225    /// Like [`Db::transaction`], trying up to `attempts` times when another
226    /// transaction got in the way (SQLite busy, PostgreSQL serialization
227    /// failure or deadlock), with a short, growing pause in between. `work`
228    /// must be safe to run again.
229    pub async fn transaction_retrying<T, F>(&self, attempts: u32, mut work: F) -> crate::Result<T>
230    where
231        F: for<'t> FnMut(
232            &'t mut Transaction,
233        ) -> futures_util::future::BoxFuture<'t, crate::Result<T>>,
234    {
235        let attempts = attempts.max(1);
236        let mut attempt = 1;
237        loop {
238            let outcome = async {
239                let mut tx = self.begin().await?;
240                let value = work(&mut tx).await?;
241                tx.commit().await?;
242                Ok::<T, crate::Error>(value)
243            }
244            .await;
245            match outcome {
246                Err(err) if attempt < attempts && err.is_retryable() => {
247                    let pause = std::time::Duration::from_millis(20 * u64::from(attempt));
248                    tokio::time::sleep(pause).await;
249                    attempt += 1;
250                }
251                other => return other,
252            }
253        }
254    }
255
256    /// Runs `work` again (up to `attempts` times, with a short, growing
257    /// pause) while it fails because another transaction got in the way
258    /// (SQLite busy, PostgreSQL serialization failure or deadlock). `work`
259    /// opens and commits its own transaction, so unlike
260    /// [`Db::transaction_retrying`] it can borrow from the caller, and it can
261    /// roll back and still return a value (drop or `rollback` the
262    /// transaction instead of committing).
263    ///
264    /// ```
265    /// # use renox::prelude::*;
266    /// enum Transfer { Done, Short }
267    ///
268    /// # async fn demo(db: Db, amount: i64, from: i64, to: i64) -> Result {
269    /// let outcome = db
270    ///     .retrying(3, || async {
271    ///         let mut tx = db.begin().await?;
272    ///         let taken = renox::db::sql(
273    ///             "UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?",
274    ///         )
275    ///         .bind(amount) // borrowed from the caller
276    ///         .bind(from)
277    ///         .bind(amount)
278    ///         .execute(&mut tx)
279    ///         .await?;
280    ///         if taken == 0 {
281    ///             tx.rollback().await?;
282    ///             return Ok(Transfer::Short); // rolled back, with an answer
283    ///         }
284    ///         renox::db::sql("UPDATE accounts SET balance = balance + ? WHERE id = ?")
285    ///             .bind(amount)
286    ///             .bind(to)
287    ///             .execute(&mut tx)
288    ///             .await?;
289    ///         tx.commit().await?;
290    ///         Ok(Transfer::Done)
291    ///     })
292    ///     .await?;
293    /// # let _ = outcome; Ok(()) }
294    /// ```
295    pub fn retrying<'a, T, F, Fut>(
296        &'a self,
297        attempts: u32,
298        mut work: F,
299    ) -> impl Future<Output = crate::Result<T>> + Send + 'a
300    where
301        T: Send + 'a,
302        F: FnMut() -> Fut + Send + 'a,
303        Fut: Future<Output = crate::Result<T>> + Send + 'a,
304    {
305        let attempts = attempts.max(1);
306        async move {
307            let mut attempt = 1;
308            loop {
309                match work().await {
310                    Err(err) if attempt < attempts && err.is_retryable() => {
311                        let pause = std::time::Duration::from_millis(20 * u64::from(attempt));
312                        tokio::time::sleep(pause).await;
313                        attempt += 1;
314                    }
315                    other => return other,
316                }
317            }
318        }
319    }
320
321    /// A transaction that takes SQLite's write lock at once (`BEGIN
322    /// IMMEDIATE`), so what it reads can't change before it writes: the
323    /// SQLite counterpart of `lock_for_update`. Same as `begin` on PostgreSQL.
324    pub async fn begin_immediate(&self) -> Result<Transaction, DbError> {
325        let inner = match &self.pool {
326            Pool::Sqlite(pool) => TxInner::Sqlite(pool.begin_with("BEGIN IMMEDIATE").await?),
327            #[cfg(feature = "postgres")]
328            Pool::Postgres(pool) => TxInner::Postgres(pool.begin().await?),
329        };
330        Ok(Transaction {
331            inner,
332            key: self.key.clone(),
333            savepoints: 0,
334        })
335    }
336
337    /// Closes every connection; later queries fail.
338    pub async fn close(&self) {
339        match &self.pool {
340            Pool::Sqlite(pool) => pool.close().await,
341            #[cfg(feature = "postgres")]
342            Pool::Postgres(pool) => pool.close().await,
343        }
344    }
345}
346
347/// A database transaction, from [`Db::begin`].
348pub struct Transaction {
349    inner: TxInner,
350    key: Option<Arc<Key>>,
351    /// Savepoints open inside it (for their names).
352    savepoints: u32,
353}
354
355enum TxInner {
356    Sqlite(sqlx::Transaction<'static, Sqlite>),
357    #[cfg(feature = "postgres")]
358    Postgres(sqlx::Transaction<'static, Postgres>),
359}
360
361impl Transaction {
362    /// The engine this transaction runs on.
363    pub fn dialect(&self) -> Dialect {
364        match self.inner {
365            TxInner::Sqlite(_) => Dialect::Sqlite,
366            #[cfg(feature = "postgres")]
367            TxInner::Postgres(_) => Dialect::Postgres,
368        }
369    }
370
371    /// Commits the transaction.
372    pub async fn commit(self) -> Result<(), DbError> {
373        match self.inner {
374            TxInner::Sqlite(tx) => Ok(tx.commit().await?),
375            #[cfg(feature = "postgres")]
376            TxInner::Postgres(tx) => Ok(tx.commit().await?),
377        }
378    }
379
380    /// Rolls the transaction back (dropping it uncommitted does the same).
381    pub async fn rollback(self) -> Result<(), DbError> {
382        match self.inner {
383            TxInner::Sqlite(tx) => Ok(tx.rollback().await?),
384            #[cfg(feature = "postgres")]
385            TxInner::Postgres(tx) => Ok(tx.rollback().await?),
386        }
387    }
388
389    /// Runs `work` inside a savepoint (a transaction inside the
390    /// transaction): when it returns `Err`, only what it did is undone and
391    /// the transaction goes on; when it returns `Ok`, its changes stay, to
392    /// be committed (or rolled back) with the rest. Savepoints nest.
393    ///
394    /// ```
395    /// # use renox::prelude::*;
396    /// # async fn demo(db: Db) -> Result {
397    /// let mut tx = db.begin().await?;
398    /// renox::db::sql("INSERT INTO orders (total) VALUES (?)").bind(18_000).execute(&mut tx).await?;
399    /// // Optional: a voucher that may be used up already. If it is, the order stays.
400    /// let voucher = tx
401    ///     .savepoint(|tx| {
402    ///         Box::pin(async move {
403    ///             let used = renox::db::sql("UPDATE vouchers SET used = used + 1 WHERE code = ? AND used < max_uses")
404    ///                 .bind("KOPI10")
405    ///                 .execute(&mut *tx)
406    ///                 .await?;
407    ///             renox::abort_if(used == 0, StatusCode::CONFLICT, "used up")?;
408    ///             Ok(())
409    ///         })
410    ///     })
411    ///     .await;
412    /// tx.commit().await?;
413    /// # let _ = voucher; Ok(()) }
414    /// ```
415    ///
416    /// On PostgreSQL a failed statement stops the whole transaction until
417    /// it rolls back; inside a savepoint only the savepoint rolls back, so
418    /// the transaction can go on after an expected failure (a unique
419    /// violation you handle, say).
420    pub async fn savepoint<T, F>(&mut self, work: F) -> crate::Result<T>
421    where
422        F: for<'t> FnOnce(
423            &'t mut Transaction,
424        ) -> futures_util::future::BoxFuture<'t, crate::Result<T>>,
425    {
426        let name = format!("renox_savepoint_{}", self.savepoints + 1);
427        sql(format!("SAVEPOINT {name}")).execute(&mut *self).await?;
428        self.savepoints += 1;
429        let outcome = work(self).await;
430        self.savepoints -= 1;
431        match outcome {
432            Ok(value) => {
433                sql(format!("RELEASE SAVEPOINT {name}"))
434                    .execute(&mut *self)
435                    .await?;
436                Ok(value)
437            }
438            Err(err) => {
439                sql(format!("ROLLBACK TO SAVEPOINT {name}"))
440                    .execute(&mut *self)
441                    .await?;
442                sql(format!("RELEASE SAVEPOINT {name}"))
443                    .execute(&mut *self)
444                    .await?;
445                Err(err)
446            }
447        }
448    }
449}
450
451impl fmt::Debug for Transaction {
452    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453        f.debug_struct("Transaction")
454            .field("dialect", &self.dialect())
455            .finish_non_exhaustive()
456    }
457}
458
459/// Where a query runs: `&db` or `&mut tx`. Sealed: only those.
460///
461/// An executor is used up by one statement. A helper that runs several
462/// statements on whichever it is given turns it into a [`Conn`] first and
463/// [reborrows](Conn::reborrow) it for each one:
464///
465/// ```
466/// # use renox::prelude::*;
467/// use renox::db::{Executor, sql};
468///
469/// /// Records a movement and updates the level, on `&db` or in `&mut tx`.
470/// async fn record<'c>(db: impl Executor<'c>, product: i64, quantity: i64) -> Result {
471///     let mut conn = db.into_conn();
472///     sql("INSERT INTO movements (product_id, quantity) VALUES (?, ?)")
473///         .bind(product)
474///         .bind(quantity)
475///         .execute(conn.reborrow())
476///         .await?;
477///     sql("UPDATE levels SET quantity = quantity + ? WHERE product_id = ?")
478///         .bind(quantity)
479///         .bind(product)
480///         .execute(conn.reborrow())
481///         .await?;
482///     Ok(())
483/// }
484/// # async fn demo(db: &renox::db::Db) -> Result {
485/// record(db, 1, 5).await?;
486/// let mut tx = db.begin().await?;
487/// record(&mut tx, 1, -2).await?;
488/// tx.commit().await?;
489/// # Ok(()) }
490/// ```
491pub trait Executor<'c>: Send + executor::Sealed {
492    /// This executor as a [`Conn`], which can run several statements.
493    fn into_conn(self) -> Conn<'c>;
494}
495
496mod executor {
497    pub trait Sealed {}
498    impl Sealed for &super::Db {}
499    impl Sealed for &mut super::Transaction {}
500    impl Sealed for &mut crate::import::ImportTx<'_> {}
501    impl Sealed for super::Conn<'_> {}
502}
503
504/// A connection for several statements: the pool (`&db`) or a transaction
505/// (`&mut tx`), from [`Executor::into_conn`]. It is an `Executor` itself;
506/// give each statement [`Conn::reborrow`] to keep it for the next one.
507pub enum Conn<'c> {
508    /// Statements run on the pool, each on any free connection.
509    #[doc(hidden)]
510    Pool(&'c Db),
511    /// Statements run in the transaction.
512    #[doc(hidden)]
513    Tx(&'c mut Transaction),
514}
515
516impl<'c> Executor<'c> for &'c Db {
517    fn into_conn(self) -> Conn<'c> {
518        Conn::Pool(self)
519    }
520}
521
522impl<'c> Executor<'c> for &'c mut Transaction {
523    fn into_conn(self) -> Conn<'c> {
524        Conn::Tx(self)
525    }
526}
527
528impl<'c> Executor<'c> for Conn<'c> {
529    fn into_conn(self) -> Conn<'c> {
530        self
531    }
532}
533
534impl Conn<'_> {
535    /// The key for `Encrypted` columns of the database this runs on.
536    fn key(&self) -> Option<Arc<Key>> {
537        match self {
538            Conn::Pool(db) => db.key.clone(),
539            Conn::Tx(tx) => tx.key.clone(),
540        }
541    }
542
543    /// The same connection for one more statement (a model's `save`, a
544    /// query's `fetch_all`…), keeping this one for the next.
545    pub fn reborrow(&mut self) -> Conn<'_> {
546        match self {
547            Conn::Pool(db) => Conn::Pool(db),
548            Conn::Tx(tx) => Conn::Tx(tx),
549        }
550    }
551
552    /// Which engine the statements run on, for SQL that differs.
553    pub fn dialect(&self) -> Dialect {
554        match self {
555            Conn::Pool(db) => db.dialect(),
556            Conn::Tx(tx) => tx.dialect(),
557        }
558    }
559}
560
561/// Runs `$body` against whichever backend `$conn` is: `$build` makes the
562/// backend's query from `(sql, args)` and `$exec` is its sqlx executor.
563macro_rules! dispatch {
564    ($conn:expr, |$build:ident, $exec:ident| $body:expr) => {
565        match $conn {
566            Conn::Pool(db) => match &db.pool {
567                Pool::Sqlite(pool) => {
568                    #[allow(unused_variables)]
569                    let $build = sqlite_query;
570                    let $exec = pool;
571                    ($body).map_err(DbError::from)
572                }
573                #[cfg(feature = "postgres")]
574                Pool::Postgres(pool) => {
575                    #[allow(unused_variables)]
576                    let $build = postgres_query;
577                    let $exec = pool;
578                    ($body).map_err(DbError::from)
579                }
580            },
581            Conn::Tx(tx) => match &mut tx.inner {
582                TxInner::Sqlite(tx) => {
583                    #[allow(unused_variables)]
584                    let $build = sqlite_query;
585                    let $exec = &mut **tx;
586                    ($body).map_err(DbError::from)
587                }
588                #[cfg(feature = "postgres")]
589                TxInner::Postgres(tx) => {
590                    #[allow(unused_variables)]
591                    let $build = postgres_query;
592                    let $exec = &mut **tx;
593                    ($body).map_err(DbError::from)
594                }
595            },
596        }
597    };
598}
599
600/// Seals the values of `Encrypted` fields with the database's key.
601fn seal(key: Option<&Key>, args: Vec<DbValue>) -> Result<Vec<DbValue>, DbError> {
602    args.into_iter()
603        .map(|value| match value {
604            DbValue::Encrypted(plain) => match key {
605                Some(key) => Ok(DbValue::Text(super::encrypted::seal(key, &plain.0))),
606                None => Err(DbError::from(sqlx::Error::Encode(
607                    "an Encrypted value needs the app's Db (it has the APP_KEY); \
608                     this Db was made outside App"
609                        .into(),
610                ))),
611            },
612            other => Ok(other),
613        })
614        .collect()
615}
616
617fn sqlite_query(
618    sql: String,
619    args: Vec<DbValue>,
620) -> sqlx::query::Query<'static, Sqlite, SqliteArguments> {
621    args.into_iter().fold(
622        sqlx::query(AssertSqlSafe(sql)),
623        |query, value| match value.for_sqlite() {
624            DbValue::Integer(v) => query.bind(v),
625            DbValue::Real(v) => query.bind(v),
626            DbValue::Text(v) => query.bind(v),
627            DbValue::Blob(v) => query.bind(v),
628            _ => query.bind(None::<i64>),
629        },
630    )
631}
632
633#[cfg(feature = "postgres")]
634fn postgres_query(
635    sql: String,
636    args: Vec<DbValue>,
637) -> sqlx::query::Query<'static, Postgres, PgArguments> {
638    let sql = numbered_placeholders(&sql).into_owned();
639    args.into_iter().fold(
640        sqlx::query(AssertSqlSafe(sql)),
641        |query, value| match value {
642            DbValue::Null => query.bind(UntypedNull),
643            DbValue::Integer(v) => query.bind(v),
644            DbValue::Real(v) => query.bind(v),
645            DbValue::Text(v) => query.bind(v),
646            DbValue::Blob(v) => query.bind(v),
647            DbValue::Bool(v) => query.bind(v),
648            DbValue::DateTime(v) => query.bind(v),
649            DbValue::NaiveDateTime(v) => query.bind(v),
650            DbValue::Date(v) => query.bind(v),
651            DbValue::Time(v) => query.bind(v),
652            DbValue::Json(v) => query.bind(sqlx::types::Json(v)),
653            #[cfg(feature = "uuid")]
654            DbValue::Uuid(v) => query.bind(v),
655            // Sealed into `Text` before the statement is built.
656            DbValue::Encrypted(_) => query.bind(UntypedNull),
657        },
658    )
659}
660
661/// A `NULL` parameter without a type, so PostgreSQL takes the type from
662/// where it's used (a `NULL` sent as `BIGINT` can't go into a `TIMESTAMPTZ`).
663#[cfg(feature = "postgres")]
664struct UntypedNull;
665
666#[cfg(feature = "postgres")]
667impl sqlx::Type<Postgres> for UntypedNull {
668    fn type_info() -> sqlx::postgres::PgTypeInfo {
669        // OID 0 means "unspecified" in the protocol.
670        sqlx::postgres::PgTypeInfo::with_oid(sqlx::postgres::types::Oid(0))
671    }
672}
673
674#[cfg(feature = "postgres")]
675impl sqlx::Encode<'_, Postgres> for UntypedNull {
676    fn encode_by_ref(
677        &self,
678        _buf: &mut sqlx::postgres::PgArgumentBuffer,
679    ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
680        Ok(sqlx::encode::IsNull::Yes)
681    }
682}
683
684/// Rewrites `?` placeholders as PostgreSQL's `$1`, `$2`, …, skipping quoted
685/// strings (`'…'`, `E'…'` with backslash escapes, dollar-quoted `$$…$$` and
686/// `$tag$…$tag$`), quoted identifiers and comments.
687#[cfg(any(feature = "postgres", test))]
688pub(crate) fn numbered_placeholders(sql: &str) -> Cow<'_, str> {
689    if !sql.contains('?') {
690        return Cow::Borrowed(sql);
691    }
692    // Every delimiter is ASCII, so byte offsets always fall between characters.
693    let bytes = sql.as_bytes();
694    let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
695    let mut out = String::with_capacity(sql.len() + 8);
696    let mut n = 0;
697    let mut copied = 0; // `sql[..copied]` is in `out`
698    let mut i = 0;
699    while i < bytes.len() {
700        let at = i;
701        let end = match bytes[i] {
702            quote @ (b'\'' | b'"') => {
703                // `E'…'` (or `e'…'`): a backslash escapes the next character.
704                let escapes = quote == b'\''
705                    && i > 0
706                    && matches!(bytes[i - 1], b'E' | b'e')
707                    && (i < 2 || !ident(bytes[i - 2]));
708                let mut j = i + 1;
709                // A doubled quote inside is an escaped quote: the loop ends at
710                // the first one and the next one opens a new run.
711                while j < bytes.len() && bytes[j] != quote {
712                    j += if escapes && bytes[j] == b'\\' { 2 } else { 1 };
713                }
714                j + 1
715            }
716            b'-' if bytes.get(i + 1) == Some(&b'-') => {
717                sql[i..].find('\n').map_or(bytes.len(), |nl| i + nl + 1)
718            }
719            b'/' if bytes.get(i + 1) == Some(&b'*') => sql[i + 2..]
720                .find("*/")
721                .map_or(bytes.len(), |e| i + 2 + e + 2),
722            b'$' if i == 0 || !ident(bytes[i - 1]) => {
723                // `$tag$` opens a dollar-quoted string (the tag may be empty
724                // and doesn't start with a digit, unlike `$1`), closed by the
725                // same `$tag$`.
726                let tag_len = bytes[i + 1..]
727                    .iter()
728                    .take_while(|b| b.is_ascii_alphanumeric() || **b == b'_')
729                    .count();
730                let starts_with_digit = bytes.get(i + 1).is_some_and(u8::is_ascii_digit);
731                if !starts_with_digit && bytes.get(i + 1 + tag_len) == Some(&b'$') {
732                    let tag = &sql[i..i + tag_len + 2];
733                    sql[i + tag.len()..]
734                        .find(tag)
735                        .map_or(bytes.len(), |e| i + tag.len() + e + tag.len())
736                } else {
737                    i + 1
738                }
739            }
740            b'?' => {
741                n += 1;
742                out.push_str(&sql[copied..i]);
743                out.push_str(&format!("${n}"));
744                copied = i + 1;
745                i + 1
746            }
747            _ => i + 1,
748        };
749        i = end.min(bytes.len()).max(at + 1);
750    }
751    out.push_str(&sql[copied..]);
752    Cow::Owned(out)
753}
754
755/// A raw SQL statement with `?` placeholders.
756///
757/// ```
758/// # use renox::prelude::*;
759/// # async fn demo(db: Db) -> Result {
760/// let rows = renox::db::sql("SELECT name FROM products WHERE price < ?")
761///     .bind(20_000)
762///     .fetch_all(&db)
763///     .await?;
764/// let name: String = rows[0].try_get("name")?;
765///
766/// let total: i64 = renox::db::sql("SELECT COUNT(*) FROM products").scalar(&db).await?;
767/// # let _ = (name, total); Ok(()) }
768/// ```
769pub fn sql(sql: impl Into<String>) -> Sql {
770    Sql {
771        sql: sql.into(),
772        args: Vec::new(),
773    }
774}
775
776/// A statement built by [`sql()`].
777#[derive(Debug, Clone)]
778#[must_use = "a statement does nothing until it is run"]
779pub struct Sql {
780    sql: String,
781    args: Vec<DbValue>,
782}
783
784impl Sql {
785    /// Binds the next `?`.
786    pub fn bind(mut self, value: impl ToDbValue) -> Self {
787        self.args.push(value.to_db_value());
788        self
789    }
790
791    /// Binds several values in order.
792    pub fn bind_all(mut self, values: impl IntoIterator<Item = DbValue>) -> Self {
793        self.args.extend(values);
794        self
795    }
796
797    /// Runs the statement and returns every row.
798    pub async fn fetch_all<'c>(self, db: impl Executor<'c>) -> Result<Vec<Row>, DbError> {
799        let Self { sql, args } = self;
800        super::query_log::record(&sql);
801        let conn = db.into_conn();
802        let key = conn.key();
803        let args = seal(key.as_deref(), args)?;
804        let rows: Vec<Row> = dispatch!(conn, |build, exec| build(sql, args)
805            .fetch_all(exec)
806            .await
807            .map(|rows| rows.into_iter().map(Row::from).collect()))?;
808        Ok(rows
809            .into_iter()
810            .map(|row| row.with_key(key.clone()))
811            .collect())
812    }
813
814    /// Runs the statement and returns the first row, if any.
815    pub async fn fetch_optional<'c>(self, db: impl Executor<'c>) -> Result<Option<Row>, DbError> {
816        let Self { sql, args } = self;
817        super::query_log::record(&sql);
818        let conn = db.into_conn();
819        let key = conn.key();
820        let args = seal(key.as_deref(), args)?;
821        let row: Option<Row> = dispatch!(conn, |build, exec| build(sql, args)
822            .fetch_optional(exec)
823            .await
824            .map(|row| row.map(Row::from)))?;
825        Ok(row.map(|row| row.with_key(key)))
826    }
827
828    /// The first row; an error if there is none.
829    pub async fn fetch_one<'c>(self, db: impl Executor<'c>) -> Result<Row, DbError> {
830        self.fetch_optional(db)
831            .await?
832            .ok_or_else(|| DbError::from(sqlx::Error::RowNotFound))
833    }
834
835    /// Runs the statement and returns the number of rows it changed.
836    pub async fn execute<'c>(self, db: impl Executor<'c>) -> Result<u64, DbError> {
837        let Self { sql, args } = self;
838        super::query_log::record(&sql);
839        let conn = db.into_conn();
840        let args = seal(conn.key().as_deref(), args)?;
841        dispatch!(conn, |build, exec| build(sql, args)
842            .execute(exec)
843            .await
844            .map(|done| done.rows_affected()))
845    }
846
847    /// Every row, read into `T`: a model, a `#[derive(FromRow)]` struct or a
848    /// tuple; see [`super::FromRow`].
849    pub async fn fetch_as<'c, T: super::FromRow>(
850        self,
851        db: impl Executor<'c>,
852    ) -> Result<Vec<T>, DbError> {
853        self.fetch_all(db).await?.iter().map(T::from_row).collect()
854    }
855
856    /// The first row read into `T`, or `None` if there is no row.
857    pub async fn fetch_optional_as<'c, T: super::FromRow>(
858        self,
859        db: impl Executor<'c>,
860    ) -> Result<Option<T>, DbError> {
861        self.fetch_optional(db)
862            .await?
863            .as_ref()
864            .map(T::from_row)
865            .transpose()
866    }
867
868    /// The first row read into `T`; an error if there is none.
869    pub async fn fetch_one_as<'c, T: super::FromRow>(
870        self,
871        db: impl Executor<'c>,
872    ) -> Result<T, DbError> {
873        T::from_row(&self.fetch_one(db).await?)
874    }
875
876    /// The first column of the first row; an error if there is no row.
877    pub async fn scalar<'c, T: FromDb>(self, db: impl Executor<'c>) -> Result<T, DbError> {
878        self.fetch_one(db).await?.try_get(0)
879    }
880
881    /// The first column of the first row, or `None` if there is no row.
882    pub async fn scalar_optional<'c, T: FromDb>(
883        self,
884        db: impl Executor<'c>,
885    ) -> Result<Option<T>, DbError> {
886        self.fetch_optional(db)
887            .await?
888            .map(|row| row.try_get(0))
889            .transpose()
890    }
891
892    /// The first column of every row.
893    pub async fn scalars<'c, T: FromDb>(self, db: impl Executor<'c>) -> Result<Vec<T>, DbError> {
894        self.fetch_all(db)
895            .await?
896            .iter()
897            .map(|row| row.try_get(0))
898            .collect()
899    }
900}
901
902/// Runs SQL that may hold several statements and no parameters, e.g. a
903/// migration file. Returns the number of rows changed.
904pub(crate) async fn script<'c>(db: impl Executor<'c>, sql: &str) -> Result<u64, DbError> {
905    let sql = sql.to_owned();
906    dispatch!(db.into_conn(), |build, exec| sqlx::raw_sql(AssertSqlSafe(
907        sql
908    ))
909    .execute(exec)
910    .await
911    .map(|done| done.rows_affected()))
912}
913
914/// One result row. Read columns by name or position with [`Row::try_get`].
915pub struct Row(pub(crate) RowInner, Option<Arc<Key>>);
916
917pub(crate) enum RowInner {
918    Sqlite(SqliteRow),
919    #[cfg(feature = "postgres")]
920    Postgres(PgRow),
921}
922
923impl From<SqliteRow> for Row {
924    fn from(row: SqliteRow) -> Self {
925        Self(RowInner::Sqlite(row), None)
926    }
927}
928
929#[cfg(feature = "postgres")]
930impl From<PgRow> for Row {
931    fn from(row: PgRow) -> Self {
932        Self(RowInner::Postgres(row), None)
933    }
934}
935
936impl Row {
937    fn with_key(mut self, key: Option<Arc<Key>>) -> Self {
938        self.1 = key;
939        self
940    }
941
942    /// A column's value, by name (`"name"`) or position (`0`).
943    pub fn try_get<T: FromDb>(&self, index: impl RowIndex) -> Result<T, DbError> {
944        super::encrypted::reading(self.1.as_ref(), || match &self.0 {
945            RowInner::Sqlite(row) => Ok(row.try_get(index)?),
946            #[cfg(feature = "postgres")]
947            RowInner::Postgres(row) => Ok(row.try_get(index)?),
948        })
949    }
950
951    /// A column's value as JSON, whatever its type; `null` when it can't be
952    /// read as a number, boolean, text, date, time, timestamp or JSON.
953    pub(crate) fn json(&self, column: &str) -> serde_json::Value {
954        use serde_json::Value;
955        if let Ok(v) = self.try_get::<Option<i64>>(column) {
956            return v.map_or(Value::Null, Value::from);
957        }
958        if let Ok(v) = self.try_get::<Option<i32>>(column) {
959            return v.map_or(Value::Null, Value::from);
960        }
961        // PostgreSQL's SMALLINT and REAL decode only as these.
962        if let Ok(v) = self.try_get::<Option<i16>>(column) {
963            return v.map_or(Value::Null, Value::from);
964        }
965        if let Ok(v) = self.try_get::<Option<f64>>(column) {
966            return v.map_or(Value::Null, Value::from);
967        }
968        if let Ok(v) = self.try_get::<Option<f32>>(column) {
969            return v.map_or(Value::Null, |n| Value::from(f64::from(n)));
970        }
971        if let Ok(v) = self.try_get::<Option<bool>>(column) {
972            return v.map_or(Value::Null, Value::from);
973        }
974        if let Ok(v) = self.try_get::<Option<chrono::DateTime<chrono::Utc>>>(column) {
975            return v.map_or(Value::Null, |d| Value::from(d.to_rfc3339()));
976        }
977        if let Ok(v) = self.try_get::<Option<chrono::NaiveDateTime>>(column) {
978            return v.map_or(Value::Null, |d| {
979                Value::from(d.format("%Y-%m-%dT%H:%M:%S").to_string())
980            });
981        }
982        if let Ok(v) = self.try_get::<Option<chrono::NaiveDate>>(column) {
983            return v.map_or(Value::Null, |d| Value::from(d.to_string()));
984        }
985        if let Ok(v) = self.try_get::<Option<String>>(column) {
986            return v.map_or(Value::Null, Value::from);
987        }
988        // After text, so SQLite text that looks like a time stays as written;
989        // PostgreSQL's TIME decodes only as this.
990        if let Ok(v) = self.try_get::<Option<chrono::NaiveTime>>(column) {
991            return v.map_or(Value::Null, |t| Value::from(t.to_string()));
992        }
993        if let Ok(v) = self.try_get::<Option<serde_json::Value>>(column) {
994            return v.unwrap_or(Value::Null);
995        }
996        Value::Null
997    }
998
999    /// The column names, in order.
1000    pub fn columns(&self) -> Vec<&str> {
1001        match &self.0 {
1002            RowInner::Sqlite(row) => row.columns().iter().map(Column::name).collect(),
1003            #[cfg(feature = "postgres")]
1004            RowInner::Postgres(row) => row.columns().iter().map(Column::name).collect(),
1005        }
1006    }
1007
1008    /// The sqlx row, when the database is SQLite.
1009    pub fn sqlite(&self) -> Option<&SqliteRow> {
1010        match &self.0 {
1011            RowInner::Sqlite(row) => Some(row),
1012            #[cfg(feature = "postgres")]
1013            RowInner::Postgres(_) => None,
1014        }
1015    }
1016
1017    /// The sqlx row, when the database is PostgreSQL.
1018    #[cfg(feature = "postgres")]
1019    pub fn postgres(&self) -> Option<&PgRow> {
1020        match &self.0 {
1021            RowInner::Postgres(row) => Some(row),
1022            RowInner::Sqlite(_) => None,
1023        }
1024    }
1025}
1026
1027impl fmt::Debug for Row {
1028    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1029        f.debug_struct("Row")
1030            .field("columns", &self.columns())
1031            .finish_non_exhaustive()
1032    }
1033}
1034
1035/// A Rust type that can be read from a column on every enabled database:
1036/// the integer and float types, `bool`, `String`, `Vec<u8>`, the chrono date
1037/// and time types, `Option<T>` of those, `Json<T>`, `Encrypted<T>`, `Ulid`,
1038/// `Uuid` (the `uuid` feature) and `#[derive(DbEnum)]` enums. Those are the
1039/// types Renox promises; the trait is implemented through sqlx's own
1040/// traits, so other types sqlx decodes work too, without that promise (see
1041/// docs/stability.md).
1042pub trait FromDb: for<'r> sqlx::Decode<'r, Sqlite> + sqlx::Type<Sqlite> + bounds::Postgres {}
1043
1044impl<T> FromDb for T where
1045    T: for<'r> sqlx::Decode<'r, Sqlite> + sqlx::Type<Sqlite> + bounds::Postgres
1046{
1047}
1048
1049/// A column name (`&str`) or position (`usize`).
1050pub trait RowIndex: sqlx::ColumnIndex<SqliteRow> + bounds::PostgresIndex {}
1051
1052impl<T> RowIndex for T where T: sqlx::ColumnIndex<SqliteRow> + bounds::PostgresIndex {}
1053
1054/// Extra bounds that only apply when the `postgres` feature is on.
1055#[doc(hidden)]
1056pub mod bounds {
1057    #[cfg(feature = "postgres")]
1058    mod on {
1059        use sqlx::postgres::PgRow;
1060
1061        pub trait Postgres:
1062            for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres>
1063        {
1064        }
1065        impl<T> Postgres for T where T: for<'r> sqlx::Decode<'r, sqlx::Postgres> + sqlx::Type<sqlx::Postgres>
1066        {}
1067
1068        pub trait PostgresIndex: sqlx::ColumnIndex<PgRow> {}
1069        impl<T: sqlx::ColumnIndex<PgRow>> PostgresIndex for T {}
1070    }
1071
1072    #[cfg(not(feature = "postgres"))]
1073    mod on {
1074        pub trait Postgres {}
1075        impl<T: ?Sized> Postgres for T {}
1076
1077        pub trait PostgresIndex {}
1078        impl<T: ?Sized> PostgresIndex for T {}
1079    }
1080
1081    pub use on::{Postgres, PostgresIndex};
1082}
1083
1084#[cfg(test)]
1085mod tests {
1086    use super::{numbered_placeholders, seal};
1087    use crate::db::DbValue;
1088
1089    #[test]
1090    fn numbers_placeholders_outside_quotes_and_comments() {
1091        assert_eq!(
1092            numbered_placeholders("SELECT * FROM t WHERE a = ? AND b IN (?, ?)"),
1093            "SELECT * FROM t WHERE a = $1 AND b IN ($2, $3)"
1094        );
1095        assert_eq!(
1096            numbered_placeholders("SELECT '?', \"a?\" -- why?\nFROM t /* ? */ WHERE x = ?"),
1097            "SELECT '?', \"a?\" -- why?\nFROM t /* ? */ WHERE x = $1"
1098        );
1099        assert_eq!(
1100            numbered_placeholders("SELECT 'it''s ?' WHERE y = ?"),
1101            "SELECT 'it''s ?' WHERE y = $1"
1102        );
1103        assert_eq!(numbered_placeholders("SELECT 1"), "SELECT 1");
1104    }
1105
1106    /// PostgreSQL's other string forms keep their `?` (#219).
1107    #[test]
1108    fn skips_dollar_quoted_and_escaped_strings() {
1109        assert_eq!(
1110            numbered_placeholders("SELECT $$why?$$, $fn$ a ? b $fn$ WHERE x = ?"),
1111            "SELECT $$why?$$, $fn$ a ? b $fn$ WHERE x = $1"
1112        );
1113        assert_eq!(
1114            numbered_placeholders(r"SELECT E'it\'s ?', e'\\' WHERE y = ? AND z = ?"),
1115            r"SELECT E'it\'s ?', e'\\' WHERE y = $1 AND z = $2"
1116        );
1117        // A plain string keeps its backslash; `$1` and `a$b` aren't quotes.
1118        assert_eq!(
1119            numbered_placeholders(r"SELECT '\', a$b$ FROM t WHERE c = ?"),
1120            r"SELECT '\', a$b$ FROM t WHERE c = $1"
1121        );
1122        assert_eq!(
1123            numbered_placeholders("SELECT 'é?' WHERE ü = ?"),
1124            "SELECT 'é?' WHERE ü = $1"
1125        );
1126    }
1127
1128    /// Unterminated quotes, comments and dollar quotes swallow the rest; a
1129    /// `$` at the very end or before a digit is no quote (#254).
1130    #[test]
1131    fn placeholders_after_unfinished_quotes_stay() {
1132        assert_eq!(numbered_placeholders("SELECT 'open ?"), "SELECT 'open ?");
1133        assert_eq!(numbered_placeholders("SELECT 1 -- ?"), "SELECT 1 -- ?");
1134        assert_eq!(numbered_placeholders("SELECT 1 /* ?"), "SELECT 1 /* ?");
1135        assert_eq!(numbered_placeholders("SELECT $tag$ ?"), "SELECT $tag$ ?");
1136        assert_eq!(numbered_placeholders("SELECT ? || $"), "SELECT $1 || $");
1137        // A `$1` doesn't open a quote, so the `?` after it is still seen.
1138        assert!(numbered_placeholders("SELECT $1, ?").ends_with(", $1"));
1139        assert_eq!(numbered_placeholders("?"), "$1");
1140    }
1141
1142    /// `retrying` and `transaction_retrying` try again after a busy error,
1143    /// stop at the last attempt, and return other errors at once.
1144    #[tokio::test]
1145    async fn retrying_follows_the_error_kind() {
1146        use std::sync::Arc;
1147        use std::sync::atomic::{AtomicU32, Ordering};
1148
1149        use crate::db::DbError;
1150        use crate::db::error::fake;
1151
1152        fn busy() -> crate::Error {
1153            crate::Error::from(DbError::from(fake::coded(Some("5"))))
1154        }
1155        let db = super::super::connect(&crate::Config::default())
1156            .await
1157            .unwrap();
1158
1159        let tries = Arc::new(AtomicU32::new(0));
1160        let counter = tries.clone();
1161        let value = db
1162            .retrying(3, move || {
1163                let counter = counter.clone();
1164                async move {
1165                    match counter.fetch_add(1, Ordering::SeqCst) {
1166                        0 | 1 => Err(busy()),
1167                        _ => Ok("done"),
1168                    }
1169                }
1170            })
1171            .await
1172            .unwrap();
1173        assert_eq!((value, tries.load(Ordering::SeqCst)), ("done", 3));
1174
1175        let tries = Arc::new(AtomicU32::new(0));
1176        let counter = tries.clone();
1177        let err = db
1178            .retrying(2, move || {
1179                counter.fetch_add(1, Ordering::SeqCst);
1180                async { Err::<(), _>(busy()) }
1181            })
1182            .await
1183            .unwrap_err();
1184        assert!(err.is_retryable());
1185        assert_eq!(
1186            tries.load(Ordering::SeqCst),
1187            2,
1188            "gives up at the last attempt"
1189        );
1190
1191        let tries = Arc::new(AtomicU32::new(0));
1192        let counter = tries.clone();
1193        let err = db
1194            .retrying(5, move || {
1195                counter.fetch_add(1, Ordering::SeqCst);
1196                async { Err::<(), _>(crate::Error::NotFound) }
1197            })
1198            .await
1199            .unwrap_err();
1200        assert!(matches!(err, crate::Error::NotFound));
1201        assert_eq!(tries.load(Ordering::SeqCst), 1, "not retried");
1202
1203        let tries = Arc::new(AtomicU32::new(0));
1204        let counter = tries.clone();
1205        let value = db
1206            .transaction_retrying(3, move |tx| {
1207                let first = counter.fetch_add(1, Ordering::SeqCst) == 0;
1208                Box::pin(async move {
1209                    let one: i64 = super::sql("SELECT CAST(1 AS BIGINT)").scalar(tx).await?;
1210                    if first { Err(busy()) } else { Ok(one) }
1211                })
1212            })
1213            .await
1214            .unwrap();
1215        assert_eq!((value, tries.load(Ordering::SeqCst)), (1, 2));
1216    }
1217
1218    // #254: an Encrypted value on a Db made outside App has no key to seal with.
1219    #[test]
1220    fn sealing_needs_the_apps_key() {
1221        let err = seal(
1222            None,
1223            vec![DbValue::Encrypted(super::super::encrypted::Unsealed(
1224                "x".into(),
1225            ))],
1226        )
1227        .unwrap_err();
1228        assert!(
1229            err.to_string()
1230                .contains("an Encrypted value needs the app's Db"),
1231            "{err}"
1232        );
1233        // Plain values pass through untouched.
1234        assert!(matches!(
1235            seal(None, vec![DbValue::Integer(1)]).unwrap()[..],
1236            [DbValue::Integer(1)]
1237        ));
1238    }
1239}