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