Skip to main content

fastauth_sqlx/
lib.rs

1//! The sqlx adapter for [fastauth](https://github.com/lassejlv/fastauth): Postgres and SQLite,
2//! with migrations. See `docs/06-database.md`.
3//!
4//! ```no_run
5//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
6//! use fastauth_sqlx::{Sqlx, SqlitePool};
7//!
8//! let pool = SqlitePool::connect("sqlite://acme.db?mode=rwc").await?;
9//! let db = Sqlx::new(pool).table_prefix("fa_"); // Sqlx<Sqlite>
10//! # let _ = db;
11//! # Ok(())
12//! # }
13//! ```
14
15mod driver;
16#[cfg(feature = "postgres")]
17mod postgres;
18mod render;
19#[cfg(feature = "sqlite")]
20mod sqlite;
21mod tx;
22
23use std::collections::HashSet;
24use std::sync::Arc;
25
26use fastauth_core::adapter::{
27    Adapter, DbError, DbResult, Delete, Filter, Insert, Queries, Select, SessionWithUser,
28    Transaction, Update,
29};
30use fastauth_core::migrate::{LiveSchema, MigrationPlan, index_name};
31use fastauth_core::schema::{ColumnType, TableDef};
32use fastauth_core::value::{DecodeError, Row, Value};
33use sqlx::pool::PoolConnection;
34use sqlx_core::transaction::TransactionManager;
35use tokio::sync::{Mutex, MutexGuard};
36
37pub use sqlx;
38pub use sqlx::Pool;
39#[cfg(feature = "postgres")]
40pub use sqlx::{PgPool, Postgres};
41#[cfg(feature = "sqlite")]
42pub use sqlx::{Sqlite, SqlitePool};
43
44use crate::driver::stored_type;
45use crate::render::{Names, Sql, Statement};
46pub use crate::tx::{InTx, SharedTx};
47
48/// A database this crate supports: [`Postgres`] or [`Sqlite`], each behind the feature of
49/// the same name. Sealed.
50pub trait Dialect: driver::Driver {}
51
52impl<DB: driver::Driver> Dialect for DB {}
53
54/// The fastauth adapter over a sqlx pool. `Sqlx::new(pool)` infers the database from the
55/// pool: a `PgPool` gives `Sqlx<Postgres>`, a `SqlitePool` gives `Sqlx<Sqlite>`.
56///
57/// Query text is rendered once per query shape and cached; values are always bind
58/// parameters. Clones share the pool and the cache.
59pub struct Sqlx<DB: Dialect> {
60    pool: Pool<DB>,
61    sql: Arc<Sql>,
62    /// The app transaction this copy is bound to by `InTx::in_tx`: every query runs on it,
63    /// and `begin` opens a savepoint in it.
64    tx: Option<SharedConn<DB>>,
65}
66
67type SharedConn<DB> = Arc<Mutex<sqlx::Transaction<'static, DB>>>;
68
69impl<DB: Dialect> Clone for Sqlx<DB> {
70    fn clone(&self) -> Self {
71        Self {
72            pool: self.pool.clone(),
73            sql: self.sql.clone(),
74            tx: self.tx.clone(),
75        }
76    }
77}
78
79impl<DB: Dialect> std::fmt::Debug for Sqlx<DB> {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.debug_struct("Sqlx")
82            .field("names", &self.sql.names)
83            .finish_non_exhaustive()
84    }
85}
86
87impl<DB: Dialect> Sqlx<DB> {
88    /// Wraps a pool. Tables keep their plain names (`user`, `session`, ...).
89    pub fn new(pool: Pool<DB>) -> Self {
90        Self {
91            pool,
92            sql: Arc::new(Sql::new(Names::default())),
93            tx: None,
94        }
95    }
96
97    /// Prefixes every table name: `.table_prefix("fa_")` stores `fa_user`, `fa_session`, ...
98    pub fn table_prefix(self, prefix: impl Into<String>) -> Self {
99        let prefix = prefix.into();
100        self.with_names(|names| names.prefix = prefix)
101    }
102
103    /// Stores `table` under another name, e.g. `.rename("user", "accounts")` to keep an
104    /// existing users table name. The table prefix doesn't apply to a renamed table.
105    pub fn rename(self, table: impl Into<String>, to: impl Into<String>) -> Self {
106        let (table, to) = (table.into(), to.into());
107        self.with_names(|names| {
108            names.renames.insert(table, to);
109        })
110    }
111
112    /// The pool, for the app's own queries.
113    pub fn pool(&self) -> &Pool<DB> {
114        &self.pool
115    }
116
117    fn with_names(self, change: impl FnOnce(&mut Names)) -> Self {
118        let mut names = self.sql.names.clone();
119        change(&mut names);
120        Self {
121            pool: self.pool,
122            sql: Arc::new(Sql::new(names)),
123            tx: self.tx,
124        }
125    }
126
127    fn bind(&self, tx: SharedConn<DB>) -> Self {
128        Self {
129            pool: self.pool.clone(),
130            sql: self.sql.clone(),
131            tx: Some(tx),
132        }
133    }
134
135    async fn conn(&self) -> DbResult<Conn<'_, DB>> {
136        Ok(match &self.tx {
137            Some(tx) => Conn::Tx(tx.lock().await),
138            None => Conn::Pool(self.pool.acquire().await.map_err(DbError::other)?),
139        })
140    }
141}
142
143/// A connection for one query: from the pool, or the bound app transaction's.
144enum Conn<'a, DB: Dialect> {
145    Pool(PoolConnection<DB>),
146    Tx(MutexGuard<'a, sqlx::Transaction<'static, DB>>),
147}
148
149impl<DB: Dialect> std::ops::Deref for Conn<'_, DB> {
150    type Target = DB::Connection;
151
152    fn deref(&self) -> &DB::Connection {
153        match self {
154            Self::Pool(conn) => conn,
155            Self::Tx(tx) => tx,
156        }
157    }
158}
159
160impl<DB: Dialect> std::ops::DerefMut for Conn<'_, DB> {
161    fn deref_mut(&mut self) -> &mut DB::Connection {
162        match self {
163            Self::Pool(conn) => conn,
164            Self::Tx(tx) => tx,
165        }
166    }
167}
168
169#[cfg(feature = "postgres")]
170impl Sqlx<Postgres> {
171    /// The Postgres schema for fastauth's tables. Default: the connection's `search_path`.
172    /// The migrator creates the schema if it doesn't exist.
173    pub fn schema(self, schema: impl Into<String>) -> Self {
174        let schema = schema.into();
175        self.with_names(|names| names.schema = Some(schema))
176    }
177}
178
179/// A transaction from [`Adapter::begin`]: a new one on a pool connection, or a savepoint
180/// when the adapter is bound to an app transaction. Dropping it without `commit` rolls back.
181pub struct SqlxTx<DB: Dialect> {
182    kind: TxKind<DB>,
183    sql: Arc<Sql>,
184}
185
186enum TxKind<DB: Dialect> {
187    Owned(Mutex<sqlx::Transaction<'static, DB>>),
188    Savepoint(Savepoint<DB>),
189}
190
191struct Savepoint<DB: Dialect> {
192    tx: SharedConn<DB>,
193    open: bool,
194}
195
196impl<DB: Dialect> Drop for Savepoint<DB> {
197    fn drop(&mut self) {
198        if !self.open {
199            return;
200        }
201        if let Ok(mut tx) = self.tx.try_lock() {
202            DB::TransactionManager::start_rollback(&mut **tx);
203        }
204    }
205}
206
207impl<DB: Dialect> SqlxTx<DB> {
208    async fn lock(&self) -> MutexGuard<'_, sqlx::Transaction<'static, DB>> {
209        match &self.kind {
210            TxKind::Owned(tx) => tx.lock().await,
211            TxKind::Savepoint(savepoint) => savepoint.tx.lock().await,
212        }
213    }
214}
215
216fn db_error<DB: Dialect>(err: sqlx::Error, sql: &Sql, table: &TableDef) -> DbError {
217    match err.as_database_error() {
218        Some(db) if db.is_unique_violation() => DbError::UniqueViolation {
219            table: table.name.to_owned(),
220            column: DB::violated_column(db, &sql.names.physical(table.name), table),
221        },
222        _ => DbError::other(err),
223    }
224}
225
226fn decode<DB: Dialect>(table: &Arc<TableDef>, row: &DB::Row, offset: usize) -> DbResult<Row> {
227    let values = table
228        .columns
229        .iter()
230        .enumerate()
231        .map(|(i, column)| {
232            DB::decode(row, offset + i, stored_type(table, column.ty))
233                .map_err(|m| DecodeError::new(column.name, m))
234        })
235        .collect::<Result<_, _>>()?;
236    Ok(Row::new(table.clone(), values))
237}
238
239async fn fetch<DB: Dialect>(
240    conn: &mut DB::Connection,
241    sql: &Sql,
242    statement: Statement,
243    table: &TableDef,
244) -> DbResult<Vec<DB::Row>> {
245    DB::fetch_all(conn, statement.sql, statement.params)
246        .await
247        .map_err(|err| db_error::<DB>(err, sql, table))
248}
249
250async fn execute<DB: Dialect>(
251    conn: &mut DB::Connection,
252    sql: &Sql,
253    statement: Statement,
254    table: &TableDef,
255) -> DbResult<u64> {
256    DB::execute(conn, statement.sql, statement.params)
257        .await
258        .map_err(|err| db_error::<DB>(err, sql, table))
259}
260
261async fn insert<DB: Dialect>(conn: &mut DB::Connection, sql: &Sql, q: Insert<'_>) -> DbResult<Row> {
262    let table = q.table;
263    let rows = fetch::<DB>(conn, sql, sql.insert::<DB>(q), table).await?;
264    let row = rows
265        .first()
266        .ok_or_else(|| DbError::Schema(format!("insert into `{}` returned no row", table.name)))?;
267    decode::<DB>(table, row, 0)
268}
269
270async fn find_many<DB: Dialect>(
271    conn: &mut DB::Connection,
272    sql: &Sql,
273    q: Select<'_>,
274) -> DbResult<Vec<Row>> {
275    render::check_filter(&q.filter)?;
276    let table = q.table;
277    let rows = fetch::<DB>(conn, sql, sql.select::<DB>(q), table).await?;
278    rows.iter().map(|row| decode::<DB>(table, row, 0)).collect()
279}
280
281async fn find_one<DB: Dialect>(
282    conn: &mut DB::Connection,
283    sql: &Sql,
284    mut q: Select<'_>,
285) -> DbResult<Option<Row>> {
286    q.limit = Some(1);
287    Ok(find_many::<DB>(conn, sql, q).await?.pop())
288}
289
290async fn count<DB: Dialect>(
291    conn: &mut DB::Connection,
292    sql: &Sql,
293    table: &TableDef,
294    filter: Filter,
295) -> DbResult<u64> {
296    render::check_filter(&filter)?;
297    let rows = fetch::<DB>(conn, sql, sql.count::<DB>(table, filter), table).await?;
298    let value = rows
299        .first()
300        .map(|row| DB::decode(row, 0, ColumnType::Int))
301        .transpose()
302        .map_err(|m| DecodeError::new("count", m))?;
303    match value {
304        Some(Value::Int(n)) => Ok(n.unsigned_abs()),
305        other => Err(DbError::Schema(format!("COUNT(*) returned {other:?}"))),
306    }
307}
308
309async fn update<DB: Dialect>(conn: &mut DB::Connection, sql: &Sql, q: Update<'_>) -> DbResult<u64> {
310    if q.set.is_empty() {
311        return count::<DB>(conn, sql, q.table, q.filter).await;
312    }
313    render::check_filter(&q.filter)?;
314    let table = q.table;
315    execute::<DB>(conn, sql, sql.update::<DB>(q), table).await
316}
317
318async fn delete<DB: Dialect>(conn: &mut DB::Connection, sql: &Sql, q: Delete<'_>) -> DbResult<u64> {
319    render::check_filter(&q.filter)?;
320    let table = q.table;
321    execute::<DB>(conn, sql, sql.delete::<DB>(q), table).await
322}
323
324async fn session_with_user<DB: Dialect>(
325    conn: &mut DB::Connection,
326    sql: &Sql,
327    q: SessionWithUser<'_>,
328) -> DbResult<Option<(Row, Row)>> {
329    for (table, column) in [
330        (q.session, "token_hash"),
331        (q.session, "user_id"),
332        (q.user, "id"),
333    ] {
334        if table.position(column).is_none() {
335            return Err(DbError::Schema(format!(
336                "`{}.{column}` missing",
337                table.name
338            )));
339        }
340    }
341    let statement =
342        sql.session_with_user::<DB>(q.session, q.user, q.token_hash.as_bytes().to_vec());
343    let rows = fetch::<DB>(conn, sql, statement, q.session).await?;
344    let Some(row) = rows.first() else {
345        return Ok(None);
346    };
347    let session = decode::<DB>(q.session, row, 0)?;
348    let user = decode::<DB>(q.user, row, q.session.columns.len())?;
349    Ok(Some((session, user)))
350}
351
352impl<DB: Dialect> Queries for Sqlx<DB> {
353    async fn insert(&self, q: Insert<'_>) -> DbResult<Row> {
354        insert::<DB>(&mut *self.conn().await?, &self.sql, q).await
355    }
356
357    async fn find_one(&self, q: Select<'_>) -> DbResult<Option<Row>> {
358        find_one::<DB>(&mut *self.conn().await?, &self.sql, q).await
359    }
360
361    async fn find_many(&self, q: Select<'_>) -> DbResult<Vec<Row>> {
362        find_many::<DB>(&mut *self.conn().await?, &self.sql, q).await
363    }
364
365    async fn update(&self, q: Update<'_>) -> DbResult<u64> {
366        update::<DB>(&mut *self.conn().await?, &self.sql, q).await
367    }
368
369    async fn delete(&self, q: Delete<'_>) -> DbResult<u64> {
370        delete::<DB>(&mut *self.conn().await?, &self.sql, q).await
371    }
372
373    async fn count(&self, q: Select<'_>) -> DbResult<u64> {
374        count::<DB>(&mut *self.conn().await?, &self.sql, q.table, q.filter).await
375    }
376}
377
378impl<DB: Dialect> Queries for SqlxTx<DB> {
379    async fn insert(&self, q: Insert<'_>) -> DbResult<Row> {
380        insert::<DB>(&mut **self.lock().await, &self.sql, q).await
381    }
382
383    async fn find_one(&self, q: Select<'_>) -> DbResult<Option<Row>> {
384        find_one::<DB>(&mut **self.lock().await, &self.sql, q).await
385    }
386
387    async fn find_many(&self, q: Select<'_>) -> DbResult<Vec<Row>> {
388        find_many::<DB>(&mut **self.lock().await, &self.sql, q).await
389    }
390
391    async fn update(&self, q: Update<'_>) -> DbResult<u64> {
392        update::<DB>(&mut **self.lock().await, &self.sql, q).await
393    }
394
395    async fn delete(&self, q: Delete<'_>) -> DbResult<u64> {
396        delete::<DB>(&mut **self.lock().await, &self.sql, q).await
397    }
398
399    async fn count(&self, q: Select<'_>) -> DbResult<u64> {
400        count::<DB>(&mut **self.lock().await, &self.sql, q.table, q.filter).await
401    }
402}
403
404impl<DB: Dialect> Transaction for SqlxTx<DB> {
405    async fn commit(self) -> DbResult<()> {
406        match self.kind {
407            TxKind::Owned(tx) => tx.into_inner().commit().await.map_err(DbError::other),
408            TxKind::Savepoint(mut savepoint) => {
409                DB::TransactionManager::commit(&mut **savepoint.tx.lock().await)
410                    .await
411                    .map_err(DbError::other)?;
412                savepoint.open = false;
413                Ok(())
414            }
415        }
416    }
417
418    async fn rollback(self) -> DbResult<()> {
419        match self.kind {
420            TxKind::Owned(tx) => tx.into_inner().rollback().await.map_err(DbError::other),
421            TxKind::Savepoint(mut savepoint) => {
422                DB::TransactionManager::rollback(&mut **savepoint.tx.lock().await)
423                    .await
424                    .map_err(DbError::other)?;
425                savepoint.open = false;
426                Ok(())
427            }
428        }
429    }
430}
431
432impl<DB: Dialect> Adapter for Sqlx<DB> {
433    type Tx = SqlxTx<DB>;
434
435    async fn begin(&self) -> DbResult<SqlxTx<DB>> {
436        let kind = match &self.tx {
437            Some(tx) => {
438                DB::TransactionManager::begin(&mut **tx.lock().await, None)
439                    .await
440                    .map_err(DbError::other)?;
441                TxKind::Savepoint(Savepoint {
442                    tx: tx.clone(),
443                    open: true,
444                })
445            }
446            None => TxKind::Owned(Mutex::new(self.pool.begin().await.map_err(DbError::other)?)),
447        };
448        Ok(SqlxTx {
449            kind,
450            sql: self.sql.clone(),
451        })
452    }
453
454    async fn introspect(&self) -> DbResult<LiveSchema> {
455        let names = &self.sql.names;
456        let catalog = DB::introspect(&mut *self.conn().await?, names.schema.clone())
457            .await
458            .map_err(DbError::other)?;
459        let mut live = LiveSchema::default();
460        for (table, column) in catalog.columns {
461            if let Some(logical) = names.logical(&table) {
462                live.tables.entry(logical).or_default().insert(column);
463            }
464        }
465        for (table, column, storage) in catalog.id_storage {
466            if let Some(logical) = names.logical(&table) {
467                live.id_storage.insert((logical, column), storage);
468            }
469        }
470        let indexes: HashSet<(String, String)> = catalog.indexes.into_iter().collect();
471        for (table, columns) in &live.tables {
472            let physical = names.physical(table);
473            for column in columns {
474                let name = DB::ident(index_name(&physical, column));
475                if indexes.contains(&(physical.clone(), name)) {
476                    live.indexes.insert((table.clone(), column.clone()));
477                }
478            }
479        }
480        Ok(live)
481    }
482
483    async fn apply(&self, plan: &MigrationPlan) -> DbResult<()> {
484        let script = self.render_sql(plan)?;
485        if script.is_empty() {
486            return Ok(());
487        }
488        let tx = self.begin().await?;
489        DB::execute_script(&mut **tx.lock().await, script)
490            .await
491            .map_err(DbError::other)?;
492        tx.commit().await
493    }
494
495    fn render_sql(&self, plan: &MigrationPlan) -> DbResult<String> {
496        Ok(render::ddl::<DB>(&self.sql.names, plan)
497            .iter()
498            .map(|statement| format!("{statement};\n"))
499            .collect::<Vec<_>>()
500            .join("\n"))
501    }
502
503    async fn session_with_user(&self, q: SessionWithUser<'_>) -> DbResult<Option<(Row, Row)>> {
504        session_with_user::<DB>(&mut *self.conn().await?, &self.sql, q).await
505    }
506}