Skip to main content

glacier/db/
mod.rs

1//! The database layer: connections, the ambient repo, transactions and raw
2//! SQL. Models and queries build on this (see `glacier::Model`).
3//!
4//! # The ambient repo
5//!
6//! Model calls don't take a connection argument. They use the **current**
7//! one: the app's repo during a request (`App::database`), whatever
8//! `db::with` set, or the transaction `db::transaction` opened. Pass one
9//! explicitly with `.on(..)` when you need to:
10//!
11//! ```no_run
12//! # use glacier::prelude::*;
13//! # #[derive(Model)] struct Post { id: i64, title: String }
14//! # async fn demo(replica: glacier::db::Repo) -> glacier::Result<()> {
15//! let post = Post::find(1).await?;                 // current repo
16//! let posts = Post::all().on(&replica).await?;     // explicit repo
17//! # Ok(()) }
18//! ```
19//!
20//! Note that task-locals don't cross `tokio::spawn`; wrap spawned work in
21//! `db::with`.
22
23pub mod assoc;
24mod cast;
25mod changeset;
26mod decimal;
27mod loaded;
28pub mod migration;
29mod multi;
30mod query;
31pub mod query_cache;
32pub(crate) mod record;
33mod sql;
34mod value;
35
36#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
37compile_error!("glacier needs at least one database feature: `postgres` or `sqlite`");
38
39use std::future::Future;
40use std::sync::Arc;
41use std::sync::atomic::{AtomicBool, Ordering};
42use tracing::Instrument;
43use tracing::field::Empty;
44
45use sqlx::{AssertSqlSafe, Row as _};
46use tokio::sync::Mutex;
47
48pub use assoc::{Association, BelongsTo, ForeignKey, HasMany, HasOne, Nested, ParentKey, Preload};
49pub use cast::Cast;
50pub(crate) use changeset::humanize;
51pub use changeset::{Changeset, Numericality, Save};
52pub use decimal::Decimal;
53pub use loaded::{LoadedRecords, Records};
54pub use multi::{Done, Failure, Multi, MultiError};
55pub use query::{Aggregable, Assign, Batches, Col, Expr, Grouped, Order, Query, Summable};
56pub use record::{Errors, IntoField, Record, accepted, field, normalized, normalized_option};
57pub use sql::{Dialect, Sql, quote_ident};
58/// A UUID, for `uuid` columns.
59pub use uuid::Uuid;
60pub use value::{Date, FromColumn, JsonValue, NaiveTimestamp, Timestamp, ToValue, Value};
61pub use value::{StoreSource, StoreTarget, store_get, store_set};
62
63use crate::config::Config;
64use crate::error::{Error, Result};
65
66/// How long a pooled Postgres connection may sit idle before it's pinged
67/// on its way out of the pool.
68const PING_AFTER_IDLE: std::time::Duration = std::time::Duration::from_secs(30);
69
70/// A pool of connections to one database, and optionally to a read
71/// replica of it (see [`Repo::with_replica`]).
72#[derive(Clone)]
73pub struct Repo {
74    pool: Pool,
75    replica: Option<Arc<Repo>>,
76    /// Its URL without credentials, to say which database a tool read.
77    name: Arc<str>,
78}
79
80#[derive(Clone)]
81enum Pool {
82    #[cfg(feature = "postgres")]
83    Postgres(sqlx::PgPool),
84    #[cfg(feature = "sqlite")]
85    Sqlite(sqlx::SqlitePool),
86}
87
88impl Repo {
89    /// Connects to `postgres://…` or `sqlite:…` URLs. SQLite files (and their
90    /// directories) are created if missing; `sqlite::memory:` gives a private
91    /// in-memory database.
92    pub async fn connect(url: &str) -> Result<Self> {
93        Self::connect_with(url, None).await
94    }
95
96    /// Connects using `database.url` and optional `database.pool_size`,
97    /// and to a read replica at `database.replica_url` (with
98    /// `database.replica_pool_size`) when one is set.
99    pub async fn from_config(config: &Config) -> Result<Self> {
100        let url: String = config.get("database.url")?;
101        let pool_size: Option<u32> = config.get_opt("database.pool_size")?;
102        let repo = Self::connect_with(&url, pool_size).await?;
103        match config.get_opt::<String>("database.replica_url")? {
104            Some(replica_url) => {
105                let pool_size: Option<u32> = config.get_opt("database.replica_pool_size")?;
106                Ok(repo.with_replica(Self::connect_with(&replica_url, pool_size).await?))
107            }
108            None => Ok(repo),
109        }
110    }
111
112    /// Connects to the named database `databases.<name>.url` (with
113    /// `pool_size`, and `replica_url` and `replica_pool_size` for a
114    /// replica), for `App::named_database`.
115    pub async fn from_config_named(config: &Config, name: &str) -> Result<Self> {
116        let key = |setting: &str| format!("databases.{name}.{setting}");
117        let url: String = config.get(&key("url"))?;
118        let pool_size: Option<u32> = config.get_opt(&key("pool_size"))?;
119        let repo = Self::connect_with(&url, pool_size).await?;
120        match config.get_opt::<String>(&key("replica_url"))? {
121            Some(replica_url) => {
122                let pool_size: Option<u32> = config.get_opt(&key("replica_pool_size"))?;
123                Ok(repo.with_replica(Self::connect_with(&replica_url, pool_size).await?))
124            }
125            None => Ok(repo),
126        }
127    }
128
129    /// Adds a read replica. Queries read from it in a request that doesn't
130    /// write (a `GET` or `HEAD`, unless this browser wrote in the last
131    /// two seconds), and in [`reading`] blocks; everything else, and every
132    /// read after a write, uses the primary.
133    pub fn with_replica(mut self, replica: Repo) -> Self {
134        assert_eq!(
135            self.dialect(),
136            replica.dialect(),
137            "a replica is the same kind of database as its primary"
138        );
139        self.replica = Some(Arc::new(Repo {
140            pool: replica.pool,
141            name: replica.name,
142            replica: None,
143        }));
144        self
145    }
146
147    /// Which database this is: its URL without user or password
148    /// (`postgres://db.internal/shop`, `sqlite://db/development.sqlite3`).
149    pub fn name(&self) -> &str {
150        &self.name
151    }
152
153    /// Whether reads can go to a replica.
154    pub fn has_replica(&self) -> bool {
155        self.replica.is_some()
156    }
157
158    async fn connect_with(url: &str, pool_size: Option<u32>) -> Result<Self> {
159        let pool = if url.starts_with("postgres://") || url.starts_with("postgresql://") {
160            Self::postgres(url, pool_size).await?
161        } else if url.starts_with("sqlite:") {
162            Self::sqlite(url, pool_size).await?
163        } else {
164            return Err(Error::internal(format!(
165                "unsupported database URL `{url}`; expected postgres:// or sqlite:"
166            )));
167        };
168        Ok(Self {
169            pool,
170            replica: None,
171            name: without_credentials(url).into(),
172        })
173    }
174
175    #[cfg(feature = "postgres")]
176    async fn postgres(url: &str, pool_size: Option<u32>) -> Result<Pool> {
177        use std::str::FromStr;
178
179        let mut options = sqlx::postgres::PgConnectOptions::from_str(url)?;
180        // Without a user in the URL or `PGUSER`, connect as the OS user, as
181        // `psql` and Rails do.
182        if !has_user(url)
183            && std::env::var_os("PGUSER").is_none()
184            && let Some(user) = std::env::var("USER").ok().filter(|u| !u.is_empty())
185        {
186            options = options.username(&user);
187        }
188        let pool = sqlx::postgres::PgPoolOptions::new()
189            .max_connections(pool_size.unwrap_or(10))
190            // Pinging every connection before every query costs a round
191            // trip each time (a third of the time in a query-heavy
192            // request). Only one that has sat idle, which a firewall or
193            // proxy may have dropped, is checked; a read that still meets
194            // a dead connection is retried (see `run_all`).
195            .test_before_acquire(false)
196            .before_acquire(|conn, meta| {
197                Box::pin(async move {
198                    if meta.idle_for >= PING_AFTER_IDLE {
199                        sqlx::Connection::ping(conn).await?;
200                    }
201                    Ok(true)
202                })
203            })
204            .connect_with(options)
205            .await?;
206        Ok(Pool::Postgres(pool))
207    }
208
209    #[cfg(not(feature = "postgres"))]
210    async fn postgres(_url: &str, _pool_size: Option<u32>) -> Result<Pool> {
211        Err(Error::internal(
212            "Postgres support needs glacier's `postgres` feature",
213        ))
214    }
215
216    #[cfg(feature = "sqlite")]
217    async fn sqlite(url: &str, pool_size: Option<u32>) -> Result<Pool> {
218        use std::path::Path;
219        use std::str::FromStr;
220
221        use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
222
223        let memory = url.contains(":memory:") || url.contains("mode=memory");
224        if !memory {
225            let path = url
226                .trim_start_matches("sqlite://")
227                .trim_start_matches("sqlite:");
228            let path = path.split('?').next().unwrap_or(path);
229            if let Some(dir) = Path::new(path)
230                .parent()
231                .filter(|d| !d.as_os_str().is_empty())
232            {
233                std::fs::create_dir_all(dir)?;
234            }
235        }
236        let options = SqliteConnectOptions::from_str(url)?
237            .create_if_missing(true)
238            .foreign_keys(true);
239        let pool = if memory {
240            // Each connection to `:memory:` is a separate database, so keep
241            // exactly one connection alive for the pool's lifetime.
242            SqlitePoolOptions::new()
243                .max_connections(1)
244                .min_connections(1)
245                .idle_timeout(None)
246                .max_lifetime(None)
247        } else {
248            SqlitePoolOptions::new().max_connections(pool_size.unwrap_or(5))
249        };
250        Ok(Pool::Sqlite(pool.connect_with(options).await?))
251    }
252
253    #[cfg(not(feature = "sqlite"))]
254    async fn sqlite(_url: &str, _pool_size: Option<u32>) -> Result<Pool> {
255        Err(Error::internal(
256            "SQLite support needs glacier's `sqlite` feature",
257        ))
258    }
259
260    /// The underlying sqlx pool when this is a Postgres database, to share
261    /// it with other libraries: raw sqlx, or SeaORM 2 (built on the same
262    /// sqlx 0.9) through `SqlxPostgresConnector::from_sqlx_postgres_pool`.
263    /// Use [`glacier::sqlx`](crate::sqlx) so the versions match.
264    ///
265    /// Queries made through it don't join Glacier's ambient transactions.
266    #[cfg(feature = "postgres")]
267    pub fn postgres_pool(&self) -> Option<&sqlx::PgPool> {
268        match &self.pool {
269            Pool::Postgres(pool) => Some(pool),
270            #[allow(unreachable_patterns)]
271            _ => None,
272        }
273    }
274
275    /// The underlying sqlx pool when this is a SQLite database; see
276    /// [`Repo::postgres_pool`].
277    #[cfg(feature = "sqlite")]
278    pub fn sqlite_pool(&self) -> Option<&sqlx::SqlitePool> {
279        match &self.pool {
280            Pool::Sqlite(pool) => Some(pool),
281            #[allow(unreachable_patterns)]
282            _ => None,
283        }
284    }
285
286    /// Closes every connection; later queries fail. For a clean shutdown,
287    /// once the app has stopped serving.
288    pub async fn close(&self) {
289        match &self.pool {
290            #[cfg(feature = "postgres")]
291            Pool::Postgres(pool) => pool.close().await,
292            #[cfg(feature = "sqlite")]
293            Pool::Sqlite(pool) => pool.close().await,
294        }
295        if let Some(replica) = &self.replica {
296            Box::pin(replica.close()).await;
297        }
298    }
299
300    pub fn dialect(&self) -> Dialect {
301        match self.pool {
302            #[cfg(feature = "postgres")]
303            Pool::Postgres(_) => Dialect::Postgres,
304            #[cfg(feature = "sqlite")]
305            Pool::Sqlite(_) => Dialect::Sqlite,
306        }
307    }
308
309    /// Starts an explicit transaction. Most code should prefer
310    /// `db::transaction`, which makes it ambient.
311    pub async fn begin(&self) -> Result<Transaction> {
312        let inner = match &self.pool {
313            #[cfg(feature = "postgres")]
314            Pool::Postgres(pool) => TxInner::Postgres(pool.begin().await?),
315            #[cfg(feature = "sqlite")]
316            Pool::Sqlite(pool) => TxInner::Sqlite(pool.begin().await?),
317        };
318        Ok(Transaction {
319            inner: Arc::new(Mutex::new(Some(inner))),
320            dialect: self.dialect(),
321            name: self.name.clone(),
322        })
323    }
324}
325
326/// An open transaction. Cloning shares it. Dropping the last clone without
327/// committing rolls it back.
328#[derive(Clone)]
329pub struct Transaction {
330    inner: Arc<Mutex<Option<TxInner>>>,
331    dialect: Dialect,
332    /// The repo's name, keying the query cache.
333    name: Arc<str>,
334}
335
336enum TxInner {
337    #[cfg(feature = "postgres")]
338    Postgres(sqlx::Transaction<'static, sqlx::Postgres>),
339    #[cfg(feature = "sqlite")]
340    Sqlite(sqlx::Transaction<'static, sqlx::Sqlite>),
341}
342
343impl Transaction {
344    pub async fn commit(&self) -> Result<()> {
345        query_cache::clear();
346        match self.inner.lock().await.take() {
347            #[cfg(feature = "postgres")]
348            Some(TxInner::Postgres(tx)) => tx.commit().await?,
349            #[cfg(feature = "sqlite")]
350            Some(TxInner::Sqlite(tx)) => tx.commit().await?,
351            None => return Err(Error::internal("transaction already finished")),
352        }
353        Ok(())
354    }
355
356    pub async fn rollback(&self) -> Result<()> {
357        // What was read inside may have been undone.
358        query_cache::clear();
359        match self.inner.lock().await.take() {
360            #[cfg(feature = "postgres")]
361            Some(TxInner::Postgres(tx)) => tx.rollback().await?,
362            #[cfg(feature = "sqlite")]
363            Some(TxInner::Sqlite(tx)) => tx.rollback().await?,
364            None => {}
365        }
366        Ok(())
367    }
368}
369
370/// Somewhere to run queries: a repo or a transaction. Built implicitly from
371/// `&Repo` or `&Transaction` by `.on(..)`.
372#[derive(Clone)]
373pub struct Connection(Conn, Arc<Role>);
374
375/// Where a connection's reads go, shared by its clones.
376struct Role {
377    /// Reads may use the repo's replica. A write turns it off.
378    replica: AtomicBool,
379    /// Something was written: shared with the scopes `reading` and
380    /// `writing` open inside this one, so a request knows it wrote.
381    wrote: Arc<AtomicBool>,
382}
383
384impl Role {
385    fn new(replica: bool) -> Arc<Self> {
386        Arc::new(Self {
387            replica: AtomicBool::new(replica),
388            wrote: Arc::new(AtomicBool::new(false)),
389        })
390    }
391}
392
393#[derive(Clone)]
394enum Conn {
395    Repo(Repo),
396    Tx(Transaction),
397    /// A request's own connection, taken from the pool at its first query
398    /// and kept until the request ends, as Rails checks one out per
399    /// request: one pool checkout per request, not per query.
400    Held(Held),
401}
402
403#[derive(Clone)]
404struct Held {
405    repo: Repo,
406    slot: Arc<Mutex<Option<HeldConn>>>,
407}
408
409enum HeldConn {
410    #[cfg(feature = "postgres")]
411    Postgres(sqlx::pool::PoolConnection<sqlx::Postgres>),
412    #[cfg(feature = "sqlite")]
413    Sqlite(sqlx::pool::PoolConnection<sqlx::Sqlite>),
414}
415
416impl Held {
417    fn new(repo: &Repo) -> Self {
418        Self {
419            repo: repo.clone(),
420            slot: Arc::new(Mutex::new(None)),
421        }
422    }
423
424    async fn acquire(&self) -> std::result::Result<HeldConn, sqlx::Error> {
425        Ok(match &self.repo.pool {
426            #[cfg(feature = "postgres")]
427            Pool::Postgres(pool) => HeldConn::Postgres(pool.acquire().await?),
428            #[cfg(feature = "sqlite")]
429            Pool::Sqlite(pool) => HeldConn::Sqlite(pool.acquire().await?),
430        })
431    }
432
433    /// A transaction on the held connection, if the request has one, so a
434    /// request never waits on the pool for a second connection while
435    /// holding a first. It goes back to the pool when the transaction ends.
436    async fn begin(&self) -> Result<Transaction> {
437        let held = self.slot.lock().await.take();
438        let inner = match held {
439            #[cfg(feature = "postgres")]
440            Some(HeldConn::Postgres(conn)) => {
441                TxInner::Postgres(sqlx::Transaction::begin(conn, None).await?)
442            }
443            #[cfg(feature = "sqlite")]
444            Some(HeldConn::Sqlite(conn)) => {
445                TxInner::Sqlite(sqlx::Transaction::begin(conn, None).await?)
446            }
447            None => return self.repo.begin().await,
448        };
449        Ok(Transaction {
450            inner: Arc::new(Mutex::new(Some(inner))),
451            dialect: self.repo.dialect(),
452            name: self.repo.name.clone(),
453        })
454    }
455}
456
457impl From<&Repo> for Connection {
458    fn from(repo: &Repo) -> Self {
459        Connection(Conn::Repo(repo.clone()), Role::new(false))
460    }
461}
462
463impl From<&Transaction> for Connection {
464    fn from(tx: &Transaction) -> Self {
465        Connection(Conn::Tx(tx.clone()), Role::new(false))
466    }
467}
468
469tokio::task_local! {
470    static CURRENT: Connection;
471    /// Named databases' connections (`App::named_database`, `with_named`).
472    static NAMED: Arc<Vec<(String, Connection)>>;
473}
474
475/// The ambient connection to `database` (a model's `DATABASE`), or to the
476/// app's own database for `None`.
477pub fn current_in(database: Option<&str>) -> Result<Connection> {
478    let Some(name) = database else {
479        return current();
480    };
481    NAMED
482        .try_with(|named| {
483            named
484                .iter()
485                .find(|(n, _)| n == name)
486                .map(|(_, conn)| conn.clone())
487        })
488        .ok()
489        .flatten()
490        .ok_or_else(|| {
491            Error::internal(format!(
492                "no `{name}` database here: register it with \
493                 App::named_database(\"{name}\", repo), or wrap the code in \
494                 glacier::db::with_named(\"{name}\", &repo, ..)"
495            ))
496        })
497}
498
499/// Whether the named database has an ambient connection.
500pub(crate) fn has_named(name: &str) -> bool {
501    NAMED
502        .try_with(|named| named.iter().any(|(n, _)| n == name))
503        .unwrap_or(false)
504}
505
506/// Runs `fut` with these named connections added to (or replacing) the
507/// ambient ones.
508pub(crate) async fn scope_named<F: Future>(
509    connections: Vec<(String, Connection)>,
510    fut: F,
511) -> F::Output {
512    if connections.is_empty() {
513        return fut.await;
514    }
515    let mut named = NAMED.try_with(|n| (**n).clone()).unwrap_or_default();
516    for (name, conn) in connections {
517        named.retain(|(n, _)| *n != name);
518        named.push((name, conn));
519    }
520    NAMED.scope(Arc::new(named), fut).await
521}
522
523/// Runs `fut` with `repo` as the ambient `name` database, for models
524/// declared with `database: :name`: in a job, a script or a test.
525pub async fn with_named<F: Future>(name: &str, repo: &Repo, fut: F) -> F::Output {
526    scope_named(vec![(name.to_owned(), Connection::from(repo))], fut).await
527}
528
529/// [`sandbox`] for a named database: `fut` runs in a transaction on it
530/// that is always rolled back.
531pub async fn sandbox_named<F: Future>(name: &str, repo: &Repo, fut: F) -> Result<F::Output> {
532    let tx = repo.begin().await?;
533    let output = scope_named(vec![(name.to_owned(), Connection::from(&tx))], fut).await;
534    tx.rollback().await?;
535    Ok(output)
536}
537
538/// The ambient connection, or an error explaining how to provide one.
539pub fn current() -> Result<Connection> {
540    CURRENT.try_with(Connection::clone).map_err(|_| {
541        Error::internal(
542            "no database connection here: register one with App::database(repo), \
543             wrap the code in glacier::db::with(&repo, ..), or call .on(&repo)",
544        )
545    })
546}
547
548pub(crate) fn scope<F: Future>(conn: Connection, fut: F) -> impl Future<Output = F::Output> {
549    CURRENT.scope(conn, fut)
550}
551
552/// Whether an ambient connection is set.
553pub fn active() -> bool {
554    CURRENT.try_with(|_| ()).is_ok()
555}
556
557/// Runs `fut` with `repo` as the ambient connection, e.g. in a background
558/// job, a script or a spawned task.
559pub async fn with<F: Future>(repo: &Repo, fut: F) -> F::Output {
560    CURRENT.scope(Connection::from(repo), fut).await
561}
562
563/// Runs `fut` with its queries reading from the repo's replica, as Rails'
564/// `connected_to(role: :reading)`: for a report or a background job that
565/// can show slightly old data. A write inside still goes to the primary,
566/// and reads after it follow. Without a replica, or inside a
567/// transaction, it changes nothing.
568pub async fn reading<F: Future>(fut: F) -> F::Output {
569    in_role(true, fut).await
570}
571
572/// Runs `fut` with every query on the primary, in a request that would
573/// otherwise read from the replica: for a read that must see the latest
574/// writes.
575pub async fn writing<F: Future>(fut: F) -> F::Output {
576    in_role(false, fut).await
577}
578
579async fn in_role<F: Future>(replica: bool, fut: F) -> F::Output {
580    let with_role = |conn: &Connection| {
581        let role = Arc::new(Role {
582            replica: AtomicBool::new(replica),
583            wrote: conn.1.wrote.clone(),
584        });
585        Connection(conn.0.clone(), role)
586    };
587    let named: Vec<(String, Connection)> = NAMED
588        .try_with(|named| {
589            named
590                .iter()
591                .map(|(name, conn)| (name.clone(), with_role(conn)))
592                .collect()
593        })
594        .unwrap_or_default();
595    let fut = scope_named(named, fut);
596    match current() {
597        Ok(conn) => CURRENT.scope(with_role(&conn), fut).await,
598        Err(_) => fut.await,
599    }
600}
601
602/// How long after a write a browser's requests read from the primary, so
603/// they see what they wrote before the replica catches up.
604pub(crate) const REPLICA_DELAY_SECONDS: i64 = 2;
605
606/// The cookie holding when this browser last wrote (Unix seconds).
607pub(crate) const LAST_WRITE_COOKIE: &str = "_glacier_last_write";
608
609/// A request's connection: on the replica when it may read from one.
610pub(crate) fn request_connection(repo: &Repo, replica: bool) -> Connection {
611    Connection(
612        Conn::Held(Held::new(repo)),
613        Role::new(replica && repo.has_replica()),
614    )
615}
616
617/// Runs `fut` inside a transaction that every model call within it joins.
618/// It commits if `fut` returns `Ok` and rolls back on `Err` (or a panic).
619/// A nested call joins the outer transaction.
620///
621/// ```no_run
622/// # use glacier::prelude::*;
623/// # use glacier::db;
624/// # async fn demo() -> glacier::Result<()> {
625/// db::transaction(async {
626///     // ... several writes that must succeed or fail together
627///     Ok(())
628/// })
629/// .await?;
630/// # Ok(()) }
631/// ```
632pub async fn transaction<T, F>(fut: F) -> Result<T>
633where
634    F: Future<Output = Result<T>>,
635{
636    transaction_in(None, fut).await
637}
638
639/// [`transaction`] on a named database (`Some("analytics")`), or the
640/// app's own for `None`. A transaction covers one database.
641pub async fn transaction_in<T, F>(database: Option<&str>, fut: F) -> Result<T>
642where
643    F: Future<Output = Result<T>>,
644{
645    let conn = current_in(database)?;
646    let tx = match &conn.0 {
647        Conn::Tx(_) => return fut.await,
648        Conn::Repo(repo) => repo.begin().await?,
649        Conn::Held(held) => held.begin().await?,
650    };
651    let inside = Connection(Conn::Tx(tx.clone()), conn.1.clone());
652    let result = match database {
653        None => CURRENT.scope(inside, fut).await,
654        Some(name) => scope_named(vec![(name.to_owned(), inside)], fut).await,
655    };
656    match result {
657        Ok(value) => {
658            tx.commit().await?;
659            Ok(value)
660        }
661        Err(err) => {
662            tx.rollback().await?;
663            Err(err)
664        }
665    }
666}
667
668/// Like [`transaction`], but inside an open transaction the work gets its
669/// own savepoint, so an error undoes just this work and the enclosing
670/// transaction carries on.
671pub async fn savepoint<T, F>(fut: F) -> Result<T>
672where
673    F: Future<Output = Result<T>>,
674{
675    savepoint_in(None, fut).await
676}
677
678/// [`savepoint`] on a named database, or the app's own for `None`.
679pub async fn savepoint_in<T, F>(database: Option<&str>, fut: F) -> Result<T>
680where
681    F: Future<Output = Result<T>>,
682{
683    static SAVEPOINTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
684    let conn = current_in(database)?;
685    if !conn.in_transaction() {
686        return transaction_in(database, fut).await;
687    }
688    let name = format!(
689        "glacier_nested_{}",
690        SAVEPOINTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
691    );
692    conn.execute(Sql::new().push(&format!("SAVEPOINT {name}")))
693        .await?;
694    let result = fut.await;
695    let finish = if result.is_ok() {
696        format!("RELEASE SAVEPOINT {name}")
697    } else {
698        format!("ROLLBACK TO SAVEPOINT {name}")
699    };
700    conn.execute(Sql::new().push(&finish)).await?;
701    result
702}
703
704/// Runs `fut` in a transaction that is always rolled back, for tests: every
705/// write, including those made by requests through `TestClient`, disappears
706/// afterwards.
707pub async fn sandbox<F: Future>(repo: &Repo, fut: F) -> Result<F::Output> {
708    let tx = repo.begin().await?;
709    let output = CURRENT.scope(Connection::from(&tx), fut).await;
710    tx.rollback().await?;
711    Ok(output)
712}
713
714/// A row from a query, read by column name.
715pub struct Row(RowInner);
716
717enum RowInner {
718    #[cfg(feature = "postgres")]
719    Postgres(sqlx::postgres::PgRow),
720    #[cfg(feature = "sqlite")]
721    Sqlite(sqlx::sqlite::SqliteRow),
722}
723
724/// One column of a row as JSON, whatever its type: the first decoding
725/// that works, `null` for NULL.
726macro_rules! column_json {
727    ($row:expr, $i:expr) => {{
728        use sqlx::ValueRef as _;
729        let row = $row;
730        match row.try_get_raw($i) {
731            Ok(raw) if raw.is_null() => serde_json::Value::Null,
732            _ => {
733                // Integers before booleans: SQLite reads an integer as a
734                // bool too. (Postgres is strict, so its booleans stay bools.)
735                if let Ok(v) = row.try_get::<i64, _>($i) {
736                    v.into()
737                } else if let Ok(v) = row.try_get::<i32, _>($i) {
738                    v.into()
739                } else if let Ok(v) = row.try_get::<i16, _>($i) {
740                    v.into()
741                } else if let Ok(v) = row.try_get::<bool, _>($i) {
742                    serde_json::Value::Bool(v)
743                } else if let Ok(v) = row.try_get::<f64, _>($i) {
744                    v.into()
745                // Text before decimals: SQLite's decimal decoder takes any
746                // text. (Postgres numerics aren't text, so they get here.)
747                } else if let Ok(v) = row.try_get::<String, _>($i) {
748                    v.into()
749                } else if let Ok(v) = row.try_get::<Decimal, _>($i) {
750                    serde_json::Value::String(v.to_string())
751                } else if let Ok(v) = row.try_get::<chrono::DateTime<chrono::Utc>, _>($i) {
752                    v.to_rfc3339().into()
753                } else if let Ok(v) = row.try_get::<chrono::NaiveDateTime, _>($i) {
754                    v.to_string().into()
755                } else if let Ok(v) = row.try_get::<chrono::NaiveDate, _>($i) {
756                    v.to_string().into()
757                } else if let Ok(v) = row.try_get::<sqlx::types::Json<serde_json::Value>, _>($i) {
758                    v.0
759                } else if let Ok(v) = row.try_get::<uuid::Uuid, _>($i) {
760                    v.to_string().into()
761                } else {
762                    serde_json::Value::String("<unreadable>".into())
763                }
764            }
765        }
766    }};
767}
768
769impl Row {
770    /// The row as a JSON object, column by column: for tools that show rows
771    /// of any query (`glacier`'s read-only query).
772    pub fn to_json(&self) -> serde_json::Value {
773        use sqlx::Column as _;
774        let mut object = serde_json::Map::new();
775        match &self.0 {
776            #[cfg(feature = "postgres")]
777            RowInner::Postgres(row) => {
778                for (i, column) in row.columns().iter().enumerate() {
779                    object.insert(column.name().to_owned(), column_json!(row, i));
780                }
781            }
782            #[cfg(feature = "sqlite")]
783            RowInner::Sqlite(row) => {
784                for (i, column) in row.columns().iter().enumerate() {
785                    object.insert(column.name().to_owned(), column_json!(row, i));
786                }
787            }
788        }
789        serde_json::Value::Object(object)
790    }
791
792    pub fn get<T: FromColumn>(&self, column: &str) -> Result<T> {
793        let result = match &self.0 {
794            #[cfg(feature = "postgres")]
795            RowInner::Postgres(row) => row.try_get(column),
796            #[cfg(feature = "sqlite")]
797            RowInner::Sqlite(row) => row.try_get(column),
798        };
799        result.map_err(|e| Error::internal(format!("reading column `{column}`: {e}")))
800    }
801
802    /// The row's first column, whatever its name.
803    pub fn first<T: FromColumn>(&self) -> Result<T> {
804        let result = match &self.0 {
805            #[cfg(feature = "postgres")]
806            RowInner::Postgres(row) => row.try_get(0usize),
807            #[cfg(feature = "sqlite")]
808            RowInner::Sqlite(row) => row.try_get(0usize),
809        };
810        result.map_err(|e| Error::internal(format!("reading the first column: {e}")))
811    }
812}
813
814macro_rules! bind_all {
815    ($query:expr, $values:expr, $list:ident) => {{
816        let mut query = $query;
817        for value in $values {
818            query = match value {
819                Value::Null => unreachable!("NULL is rendered inline"),
820                Value::List(items) => bind_list!($list, query, items),
821                Value::Bool(v) => query.bind(v),
822                Value::Int(v) => query.bind(v),
823                Value::Float(v) => query.bind(v),
824                Value::Text(v) => query.bind(v),
825                Value::Bytes(v) => query.bind(v),
826                Value::Json(v) => query.bind(sqlx::types::Json(v)),
827                Value::Decimal(v) => query.bind(v),
828                Value::Uuid(v) => query.bind(v),
829                Value::Timestamp(v) => bind_timestamp!($list, query, v),
830                Value::Date(v) => query.bind(v),
831            };
832        }
833        query
834    }};
835}
836
837/// Binds a timestamp: as a timestamp on Postgres, and on SQLite as the
838/// text Rails writes (`2026-09-01 12:00:00.000000`, UTC), so the two
839/// frameworks' rows sort and compare alike.
840macro_rules! bind_timestamp {
841    (postgres, $query:expr, $value:expr) => {
842        $query.bind($value)
843    };
844    (sqlite, $query:expr, $value:expr) => {
845        $query.bind(sqlite_timestamp(&$value))
846    };
847}
848
849/// A timestamp as SQLite text, as Rails writes it.
850pub(crate) fn sqlite_timestamp(at: &Timestamp) -> String {
851    at.format("%Y-%m-%d %H:%M:%S%.6f").to_string()
852}
853
854/// Binds an `IN` list rendered as `= ANY($n)`: one Postgres array. SQLite
855/// lists are always rendered as separate values.
856macro_rules! bind_list {
857    (postgres, $query:expr, $items:expr) => {{
858        let items: Vec<Value> = $items;
859        match items.first() {
860            Some(Value::Int(_)) => $query.bind(
861                items
862                    .into_iter()
863                    .filter_map(|v| if let Value::Int(n) = v { Some(n) } else { None })
864                    .collect::<Vec<i64>>(),
865            ),
866            Some(Value::Uuid(_)) => $query.bind(
867                items
868                    .into_iter()
869                    .filter_map(|v| {
870                        if let Value::Uuid(u) = v {
871                            Some(u)
872                        } else {
873                            None
874                        }
875                    })
876                    .collect::<Vec<uuid::Uuid>>(),
877            ),
878            _ => $query.bind(
879                items
880                    .into_iter()
881                    .map(|v| v.to_text())
882                    .collect::<Vec<String>>(),
883            ),
884        }
885    }};
886    (sqlite, $query:expr, $items:expr) => {{
887        let _ = $items;
888        unreachable!("SQLite lists are rendered as separate values")
889    }};
890}
891
892/// Runs a statement on `conn` and returns its rows.
893macro_rules! run {
894    ($conn:expr, $sql:expr, |$query:ident, $executor:ident| $body:expr) => {{
895        let conn: &Connection = $conn;
896        let (text, values) = $sql;
897        match &conn.0 {
898            Conn::Repo(repo) => match &repo.pool {
899                #[cfg(feature = "postgres")]
900                Pool::Postgres(pool) => {
901                    let $query = bind_all!(
902                        sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)),
903                        values,
904                        postgres
905                    );
906                    let $executor = pool;
907                    $body
908                }
909                #[cfg(feature = "sqlite")]
910                Pool::Sqlite(pool) => {
911                    let $query = bind_all!(
912                        sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)),
913                        values,
914                        sqlite
915                    );
916                    let $executor = pool;
917                    $body
918                }
919            },
920            Conn::Tx(tx) => {
921                let mut guard = tx.inner.lock().await;
922                match guard.as_mut() {
923                    #[cfg(feature = "postgres")]
924                    Some(TxInner::Postgres(tx)) => {
925                        let $query = bind_all!(
926                            sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)),
927                            values,
928                            postgres
929                        );
930                        let $executor = &mut **tx;
931                        $body
932                    }
933                    #[cfg(feature = "sqlite")]
934                    Some(TxInner::Sqlite(tx)) => {
935                        let $query = bind_all!(
936                            sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)),
937                            values,
938                            sqlite
939                        );
940                        let $executor = &mut **tx;
941                        $body
942                    }
943                    None => Err(sqlx::Error::Protocol("transaction already finished".into())),
944                }
945            }
946            Conn::Held(held) => {
947                let mut guard = held.slot.lock().await;
948                let ready = match guard.as_ref() {
949                    Some(_) => Ok(()),
950                    None => held.acquire().await.map(|conn| {
951                        *guard = Some(conn);
952                    }),
953                };
954                match (ready, guard.as_mut()) {
955                    (Err(err), _) => Err(err),
956                    #[cfg(feature = "postgres")]
957                    (Ok(()), Some(HeldConn::Postgres(conn))) => {
958                        let $query = bind_all!(
959                            sqlx::query::<sqlx::Postgres>(AssertSqlSafe(text)),
960                            values,
961                            postgres
962                        );
963                        let $executor = &mut **conn;
964                        $body
965                    }
966                    #[cfg(feature = "sqlite")]
967                    (Ok(()), Some(HeldConn::Sqlite(conn))) => {
968                        let $query = bind_all!(
969                            sqlx::query::<sqlx::Sqlite>(AssertSqlSafe(text)),
970                            values,
971                            sqlite
972                        );
973                        let $executor = &mut **conn;
974                        $body
975                    }
976                    (Ok(()), None) => unreachable!("just acquired"),
977                }
978            }
979        }
980    }};
981}
982
983impl Connection {
984    pub fn dialect(&self) -> Dialect {
985        match &self.0 {
986            Conn::Repo(repo) => repo.dialect(),
987            Conn::Held(held) => held.repo.dialect(),
988            Conn::Tx(tx) => tx.dialect,
989        }
990    }
991
992    pub(crate) fn in_transaction(&self) -> bool {
993        matches!(self.0, Conn::Tx(_))
994    }
995
996    /// Whether anything was written through this connection (or the
997    /// `reading` and `writing` scopes inside it).
998    pub(crate) fn wrote(&self) -> bool {
999        self.1.wrote.load(Ordering::Relaxed)
1000    }
1001
1002    /// The replica to read from, while this connection may use one.
1003    fn replica(&self) -> Option<Connection> {
1004        match &self.0 {
1005            Conn::Repo(repo) | Conn::Held(Held { repo, .. })
1006                if self.1.replica.load(Ordering::Relaxed) =>
1007            {
1008                let replica = repo.replica.as_deref()?.clone();
1009                Some(Connection(Conn::Repo(replica), self.1.clone()))
1010            }
1011            _ => None,
1012        }
1013    }
1014
1015    /// A write: reads go to the primary from now on, and the request's
1016    /// query cache empties.
1017    fn wrote_now(&self) {
1018        self.1.replica.store(false, Ordering::Relaxed);
1019        self.1.wrote.store(true, Ordering::Relaxed);
1020        query_cache::clear();
1021    }
1022
1023    /// Which database this is, for the query cache's keys.
1024    fn database_name(&self) -> &str {
1025        match &self.0 {
1026            Conn::Repo(repo) | Conn::Held(Held { repo, .. }) => &repo.name,
1027            Conn::Tx(tx) => &tx.name,
1028        }
1029    }
1030
1031    /// Runs a query that only reads: from the request's query cache when
1032    /// it ran before, else on the replica when there is one to use,
1033    /// otherwise as [`fetch_all`](Self::fetch_all).
1034    pub(crate) async fn read_all(
1035        &self,
1036        sql: &Sql,
1037    ) -> std::result::Result<query_cache::Rows, sqlx::Error> {
1038        let rendered = sql.render(self.dialect());
1039        let key = (query_cache::active() && is_cacheable(&rendered.0))
1040            .then(|| format!("{}\0{}\0{:?}", self.database_name(), rendered.0, rendered.1));
1041        if let Some(rows) = key.as_deref().and_then(query_cache::get) {
1042            tracing::debug!(target: "glacier", "CACHE {}", rendered.0);
1043            return Ok(rows);
1044        }
1045        let rows: query_cache::Rows = match self.replica() {
1046            Some(replica) => replica.run_all(rendered).await?,
1047            None => {
1048                if !is_select(&rendered.0) {
1049                    self.wrote_now();
1050                }
1051                self.run_all(rendered).await?
1052            }
1053        }
1054        .into();
1055        if let Some(key) = key {
1056            query_cache::put(key, rows.clone());
1057        }
1058        Ok(rows)
1059    }
1060
1061    /// Runs a statement on the primary and returns its rows. Anything but
1062    /// a `SELECT` counts as a write.
1063    pub(crate) async fn fetch_all(&self, sql: &Sql) -> std::result::Result<Vec<Row>, sqlx::Error> {
1064        let rendered = sql.render(self.dialect());
1065        if !is_select(&rendered.0) {
1066            self.wrote_now();
1067        }
1068        self.run_all(rendered).await
1069    }
1070
1071    async fn run_all(
1072        &self,
1073        (text, values): (String, Vec<Value>),
1074    ) -> std::result::Result<Vec<Row>, sqlx::Error> {
1075        // Connections aren't pinged before each query (a round trip each),
1076        // so one may have died since it was last used: a read outside a
1077        // transaction is tried once more on a fresh connection, as Rails
1078        // reconnects. A write isn't: it may have happened.
1079        let retry = matches!(self.0, Conn::Repo(_) | Conn::Held(_)) && is_select(&text);
1080        let again = retry.then(|| (text.clone(), values.clone()));
1081        let rows = self.run_once((text, values)).await;
1082        match (rows, again) {
1083            (Err(err), Some(again)) if is_lost_connection(&err) => {
1084                tracing::warn!(target: "glacier", "database connection lost ({err}); retrying the query");
1085                if let Conn::Held(held) = &self.0 {
1086                    // Don't reuse the dead connection: the retry takes a new one.
1087                    held.slot.lock().await.take();
1088                }
1089                self.run_once(again).await
1090            }
1091            (rows, _) => rows,
1092        }
1093    }
1094
1095    async fn run_once(
1096        &self,
1097        (text, values): (String, Vec<Value>),
1098    ) -> std::result::Result<Vec<Row>, sqlx::Error> {
1099        let span = query_span(self.dialect(), &text);
1100        let rows: std::result::Result<Vec<Row>, sqlx::Error> =
1101            run!(self, (text, values), |query, executor| {
1102                query
1103                    .fetch_all(executor)
1104                    .instrument(span.clone())
1105                    .await
1106                    .map(|rows| rows.into_iter().map(Row::from).collect())
1107            });
1108        finish_query(&span, rows.as_ref().map(Vec::len));
1109        rows
1110    }
1111
1112    pub(crate) async fn execute(&self, sql: &Sql) -> std::result::Result<u64, sqlx::Error> {
1113        self.wrote_now();
1114        let (text, values) = sql.render(self.dialect());
1115        let span = query_span(self.dialect(), &text);
1116        let done: std::result::Result<u64, sqlx::Error> =
1117            run!(self, (text, values), |query, executor| {
1118                query
1119                    .execute(executor)
1120                    .instrument(span.clone())
1121                    .await
1122                    .map(|done| done.rows_affected())
1123            });
1124        finish_query(&span, done.as_ref().map(|n| *n as usize));
1125        done
1126    }
1127}
1128
1129/// Whether `err` means the connection itself failed (it closed, or the
1130/// server ended the session), rather than the statement.
1131fn is_lost_connection(err: &sqlx::Error) -> bool {
1132    match err {
1133        sqlx::Error::Io(_) => true,
1134        // 08xxx: connection exception; 57P01–57P03: the server shut the
1135        // session down.
1136        sqlx::Error::Database(db) => db
1137            .code()
1138            .is_some_and(|code| code.starts_with("08") || code.starts_with("57P0")),
1139        _ => false,
1140    }
1141}
1142
1143/// Whether `text` is a plain `SELECT` (or a `WITH` leading to one).
1144/// Whether a read may be kept in the query cache: a `SELECT` that takes
1145/// no locks.
1146fn is_cacheable(text: &str) -> bool {
1147    let lower = text.to_ascii_lowercase();
1148    is_select(text)
1149        && !lower.contains(" for update")
1150        && !lower.contains(" for share")
1151        && !lower.contains(" for no key update")
1152        && !lower.contains(" for key share")
1153}
1154
1155fn is_select(text: &str) -> bool {
1156    let start = text.trim_start();
1157    let word = start.split_whitespace().next().unwrap_or_default();
1158    word.eq_ignore_ascii_case("select")
1159        || (word.eq_ignore_ascii_case("with")
1160            && !["insert", "update", "delete"]
1161                .iter()
1162                .any(|w| start.to_ascii_lowercase().contains(w)))
1163}
1164
1165/// A statement's span, per OpenTelemetry's database conventions. The SQL
1166/// has placeholders (`$1`, `?1`), never the values bound to them, so no
1167/// user data reaches traces.
1168fn query_span(dialect: Dialect, text: &str) -> tracing::Span {
1169    record_query(text);
1170    let operation = text
1171        .split_whitespace()
1172        .next()
1173        .unwrap_or_default()
1174        .to_ascii_uppercase();
1175    tracing::info_span!(
1176        target: "glacier",
1177        "glacier.db.query",
1178        otel.name = %operation,
1179        otel.kind = "client",
1180        otel.status_code = Empty,
1181        db.system.name = match dialect {
1182            Dialect::Postgres => "postgresql",
1183            Dialect::Sqlite => "sqlite",
1184        },
1185        db.operation.name = %operation,
1186        db.query.text = %text,
1187        db.response.returned_rows = Empty,
1188        error.message = Empty,
1189    )
1190}
1191
1192fn finish_query(span: &tracing::Span, rows: std::result::Result<usize, &sqlx::Error>) {
1193    match rows {
1194        Ok(rows) => {
1195            span.record(
1196                "db.response.returned_rows",
1197                i64::try_from(rows).unwrap_or(i64::MAX),
1198            );
1199        }
1200        Err(err) => {
1201            span.record("otel.status_code", "ERROR");
1202            span.record("error.message", tracing::field::display(err));
1203        }
1204    }
1205}
1206
1207tokio::task_local! {
1208    /// The statements run in this scope, when something is listening.
1209    static QUERY_LOG: Arc<std::sync::Mutex<Vec<String>>>;
1210}
1211
1212fn record_query(text: &str) {
1213    let _ = QUERY_LOG.try_with(|log| {
1214        log.lock()
1215            .unwrap_or_else(|e| e.into_inner())
1216            .push(text.to_owned());
1217    });
1218}
1219
1220/// Runs `fut`, collecting the SQL of every statement it runs (with
1221/// placeholders, never values).
1222pub(crate) async fn logging_queries<F: Future>(fut: F) -> (F::Output, Vec<String>) {
1223    let log = Arc::new(std::sync::Mutex::new(Vec::new()));
1224    let output = QUERY_LOG.scope(log.clone(), fut).await;
1225    let queries = std::mem::take(&mut *log.lock().unwrap_or_else(|e| e.into_inner()));
1226    (output, queries)
1227}
1228
1229tokio::task_local! {
1230    /// Set in development requests, for checks too slow for production.
1231    static DEVELOPMENT: ();
1232}
1233
1234/// Runs `fut` with development's checks on.
1235pub(crate) async fn development_checks<F: Future>(fut: F) -> F::Output {
1236    DEVELOPMENT.scope((), fut).await
1237}
1238
1239/// In development, warns once per table and column when cursor pagination
1240/// orders by a column that no index starts with: each page would read the
1241/// whole table.
1242pub(crate) async fn warn_unindexed(conn: &Connection, table: &'static str, column: &'static str) {
1243    static CHECKED: std::sync::Mutex<Vec<(&'static str, &'static str)>> =
1244        std::sync::Mutex::new(Vec::new());
1245    if DEVELOPMENT.try_with(|()| ()).is_err() {
1246        return;
1247    }
1248    {
1249        let mut checked = CHECKED.lock().unwrap_or_else(|e| e.into_inner());
1250        if checked.contains(&(table, column)) {
1251            return;
1252        }
1253        checked.push((table, column));
1254    }
1255    let mut sql = Sql::new();
1256    match conn.dialect() {
1257        Dialect::Sqlite => {
1258            sql.push("SELECT 1 AS found FROM pragma_index_list(")
1259                .push_value(Value::Text(table.to_owned()))
1260                .push(") l JOIN pragma_index_info(l.name) i WHERE i.seqno = 0 AND i.name = ")
1261                .push_value(Value::Text(column.to_owned()));
1262        }
1263        Dialect::Postgres => {
1264            sql.push(
1265                "SELECT 1 AS found FROM pg_index x JOIN pg_class t ON t.oid = x.indrelid \
1266                 JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = x.indkey[0] \
1267                 WHERE t.relnamespace = current_schema()::regnamespace AND t.relname = ",
1268            )
1269            .push_value(Value::Text(table.to_owned()))
1270            .push(" AND a.attname = ")
1271            .push_value(Value::Text(column.to_owned()));
1272        }
1273    }
1274    if let Ok(rows) = conn.fetch_all(&sql).await
1275        && rows.is_empty()
1276    {
1277        tracing::warn!(
1278            target: "glacier",
1279            "cursor pagination on `{table}` orders by `{column}`, which no index starts \
1280             with, so every page reads the whole table; add one in a migration: \
1281             add_index :{table}, [:{column}, :id]"
1282        );
1283    }
1284}
1285
1286/// How many times one `SELECT` runs in a request before it's reported as
1287/// an N+1 query.
1288pub(crate) const REPEATED_QUERY_THRESHOLD: usize = 3;
1289
1290/// The `SELECT`s run at least `at_least` times, with their counts, in
1291/// the order first run: a query in a loop that one query could replace.
1292pub(crate) fn repeated_selects(queries: &[String], at_least: usize) -> Vec<(String, usize)> {
1293    let mut counts: Vec<(String, usize)> = Vec::new();
1294    for query in queries.iter().filter(|q| is_select(q)) {
1295        match counts.iter_mut().find(|(q, _)| q == query) {
1296            Some((_, n)) => *n += 1,
1297            None => counts.push((query.clone(), 1)),
1298        }
1299    }
1300    counts.retain(|(_, n)| *n >= at_least);
1301    counts
1302}
1303
1304#[cfg(feature = "postgres")]
1305impl From<sqlx::postgres::PgRow> for Row {
1306    fn from(row: sqlx::postgres::PgRow) -> Self {
1307        Row(RowInner::Postgres(row))
1308    }
1309}
1310
1311#[cfg(feature = "sqlite")]
1312impl From<sqlx::sqlite::SqliteRow> for Row {
1313    fn from(row: sqlx::sqlite::SqliteRow) -> Self {
1314        Row(RowInner::Sqlite(row))
1315    }
1316}
1317
1318/// Raw SQL with portable `?` placeholders, for what the query builder
1319/// doesn't cover.
1320///
1321/// ```no_run
1322/// # async fn demo() -> glacier::Result<()> {
1323/// let rows = glacier::db::sql("SELECT title FROM posts WHERE id > ?")
1324///     .bind(10)
1325///     .fetch_all()
1326///     .await?;
1327/// let title: String = rows[0].get("title")?;
1328/// # Ok(()) }
1329/// ```
1330pub fn sql(text: &str) -> RawQuery {
1331    RawQuery {
1332        text: text.to_owned(),
1333        values: Vec::new(),
1334        conn: None,
1335    }
1336}
1337
1338pub struct RawQuery {
1339    text: String,
1340    values: Vec<Value>,
1341    conn: Option<Connection>,
1342}
1343
1344impl RawQuery {
1345    pub fn bind(mut self, value: impl ToValue) -> Self {
1346        self.values.push(value.to_value());
1347        self
1348    }
1349
1350    pub fn on(mut self, conn: impl Into<Connection>) -> Self {
1351        self.conn = Some(conn.into());
1352        self
1353    }
1354
1355    fn statement(&self) -> Result<(Connection, Sql)> {
1356        let conn = match &self.conn {
1357            Some(conn) => conn.clone(),
1358            None => current()?,
1359        };
1360        Ok((conn, Sql::raw(&self.text, self.values.clone())))
1361    }
1362
1363    pub async fn fetch_all(self) -> Result<Vec<Row>> {
1364        let (conn, sql) = self.statement()?;
1365        Ok(conn.fetch_all(&sql).await?)
1366    }
1367
1368    /// The first column of every row, as Rails' `select_values`:
1369    /// `ids: Vec<i32> = Db.sql("SELECT id FROM …").values()!`.
1370    pub async fn values<T: FromColumn>(self) -> Result<Vec<T>> {
1371        self.fetch_all().await?.iter().map(Row::first).collect()
1372    }
1373
1374    /// The first column of the first row, `None` when there are no rows,
1375    /// as Rails' `select_value`: `Db.sql("SELECT count(*) …").value()!`.
1376    pub async fn value<T: FromColumn>(self) -> Result<Option<T>> {
1377        self.fetch_all().await?.first().map(Row::first).transpose()
1378    }
1379
1380    /// Runs the statement, returning the number of rows affected.
1381    pub async fn execute(self) -> Result<u64> {
1382        let (conn, sql) = self.statement()?;
1383        Ok(conn.execute(&sql).await?)
1384    }
1385}
1386
1387/// Whether a database URL names a user: `postgres://me@host/db`.
1388#[cfg_attr(not(feature = "postgres"), allow(dead_code))]
1389fn has_user(url: &str) -> bool {
1390    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
1391    let authority = rest.split(['/', '?']).next().unwrap_or(rest);
1392    authority.contains('@')
1393}
1394
1395#[cfg(test)]
1396mod url_tests {
1397    #[test]
1398    fn finds_users_in_urls() {
1399        assert!(super::has_user("postgres://me@localhost/db"));
1400        assert!(super::has_user(
1401            "postgres://me:secret@localhost:5432/db?sslmode=disable"
1402        ));
1403        assert!(!super::has_user("postgres://localhost/db"));
1404        assert!(!super::has_user("postgres://localhost/db?options=a@b"));
1405    }
1406}
1407
1408/// `url` without a user or password: `postgres://u:p@host/db` →
1409/// `postgres://host/db`.
1410fn without_credentials(url: &str) -> String {
1411    match (url.split_once("://"), url.rfind('@')) {
1412        (Some((scheme, _)), Some(at)) => format!("{scheme}://{}", &url[at + 1..]),
1413        _ => url.to_owned(),
1414    }
1415}
1416
1417#[cfg(test)]
1418mod name_tests {
1419    #[test]
1420    fn hides_credentials() {
1421        assert_eq!(
1422            super::without_credentials("postgres://me:secret@db.internal:5432/shop"),
1423            "postgres://db.internal:5432/shop"
1424        );
1425        assert_eq!(
1426            super::without_credentials("sqlite://db/development.sqlite3"),
1427            "sqlite://db/development.sqlite3"
1428        );
1429    }
1430}