Skip to main content

fastauth_core/
adapter.rs

1//! The database contract. See `docs/06-database.md`.
2
3use std::future::Future;
4use std::sync::Arc;
5
6use crate::crypto::Hash;
7use crate::migrate::{LiveSchema, MigrationPlan};
8use crate::schema::TableDef;
9use crate::value::{Row, Value};
10
11pub type DbResult<T> = Result<T, DbError>;
12
13#[derive(Debug, thiserror::Error)]
14pub enum DbError {
15    /// A unique constraint failed. Adapters must map their driver's error to this, so
16    /// sign-up can answer "user already exists" instead of a 500.
17    #[error("unique constraint violated on `{table}`{}", column.as_deref().map(|c| format!(".{c}")).unwrap_or_default())]
18    UniqueViolation {
19        table: String,
20        column: Option<String>,
21    },
22    #[error("the adapter does not support {0}")]
23    Unsupported(&'static str),
24    #[error("schema mismatch: {0}")]
25    Schema(String),
26    #[error("decode: {0}")]
27    Decode(#[from] crate::value::DecodeError),
28    #[error(transparent)]
29    Other(Box<dyn std::error::Error + Send + Sync>),
30}
31
32impl DbError {
33    pub fn other(err: impl std::error::Error + Send + Sync + 'static) -> Self {
34        DbError::Other(Box::new(err))
35    }
36}
37
38impl From<DbError> for crate::AuthError {
39    fn from(err: DbError) -> Self {
40        crate::AuthError::internal(err)
41    }
42}
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum Op {
46    Eq,
47    Ne,
48    Lt,
49    Lte,
50    Gt,
51    Gte,
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum Order {
56    Asc,
57    Desc,
58}
59
60/// A resolved filter: columns are positions in the query's table.
61///
62/// The text matches (`StartsWith`, `Contains`, `EndsWith`) are case-sensitive and match
63/// their string literally: `%`, `_` and other pattern characters are not wildcards. Adapters
64/// answer a variant they don't know with [`DbError::Unsupported`].
65#[derive(Clone, Debug, PartialEq)]
66#[non_exhaustive]
67pub enum Filter {
68    All,
69    Cmp { column: usize, op: Op, value: Value },
70    In { column: usize, values: Vec<Value> },
71    Null { column: usize, is_null: bool },
72    StartsWith { column: usize, prefix: String },
73    Contains { column: usize, substring: String },
74    EndsWith { column: usize, suffix: String },
75    And(Vec<Filter>),
76    Or(Vec<Filter>),
77}
78
79#[derive(Clone, Debug)]
80pub struct Insert<'a> {
81    pub table: &'a Arc<TableDef>,
82    /// One value per column, in column order. Defaults are already applied.
83    pub values: Vec<Value>,
84}
85
86#[derive(Clone, Debug)]
87pub struct Select<'a> {
88    pub table: &'a Arc<TableDef>,
89    pub filter: Filter,
90    pub order: Vec<(usize, Order)>,
91    pub limit: Option<u64>,
92    pub offset: Option<u64>,
93}
94
95#[derive(Clone, Debug)]
96pub struct Update<'a> {
97    pub table: &'a Arc<TableDef>,
98    pub filter: Filter,
99    pub set: Vec<(usize, Value)>,
100}
101
102#[derive(Clone, Debug)]
103pub struct Delete<'a> {
104    pub table: &'a Arc<TableDef>,
105    pub filter: Filter,
106}
107
108/// The fast path for session lookup. SQL adapters answer it with one JOIN.
109#[derive(Clone, Debug)]
110pub struct SessionWithUser<'a> {
111    pub session: &'a Arc<TableDef>,
112    pub user: &'a Arc<TableDef>,
113    pub token_hash: &'a Hash,
114}
115
116/// CRUD over dynamic rows. Implemented by adapters and by their transactions.
117pub trait Queries: Send + Sync {
118    fn insert(&self, q: Insert<'_>) -> impl Future<Output = DbResult<Row>> + Send;
119    fn find_one(&self, q: Select<'_>) -> impl Future<Output = DbResult<Option<Row>>> + Send;
120    fn find_many(&self, q: Select<'_>) -> impl Future<Output = DbResult<Vec<Row>>> + Send;
121    fn update(&self, q: Update<'_>) -> impl Future<Output = DbResult<u64>> + Send;
122    fn delete(&self, q: Delete<'_>) -> impl Future<Output = DbResult<u64>> + Send;
123    fn count(&self, q: Select<'_>) -> impl Future<Output = DbResult<u64>> + Send;
124}
125
126pub trait Transaction: Queries + 'static {
127    fn commit(self) -> impl Future<Output = DbResult<()>> + Send;
128    fn rollback(self) -> impl Future<Output = DbResult<()>> + Send;
129}
130
131pub trait Adapter: Queries + 'static {
132    type Tx: Transaction;
133
134    fn begin(&self) -> impl Future<Output = DbResult<Self::Tx>> + Send;
135
136    /// Reads the live schema for the migrator. Adapters without DDL return `Unsupported`.
137    fn introspect(&self) -> impl Future<Output = DbResult<LiveSchema>> + Send;
138
139    /// Applies a migration plan computed by the migrator.
140    fn apply(&self, plan: &MigrationPlan) -> impl Future<Output = DbResult<()>> + Send;
141
142    /// Renders a plan as SQL for `fastauth generate`. Non-SQL adapters return `Unsupported`.
143    fn render_sql(&self, plan: &MigrationPlan) -> DbResult<String> {
144        let _ = plan;
145        Err(DbError::Unsupported("SQL rendering"))
146    }
147
148    /// Session plus user in one call. The default does two lookups; SQL adapters override.
149    fn session_with_user(
150        &self,
151        q: SessionWithUser<'_>,
152    ) -> impl Future<Output = DbResult<Option<(Row, Row)>>> + Send {
153        async move {
154            let session_hash = q
155                .session
156                .position("token_hash")
157                .ok_or_else(|| DbError::Schema("session.token_hash missing".into()))?;
158            let select = Select {
159                table: q.session,
160                filter: Filter::Cmp {
161                    column: session_hash,
162                    op: Op::Eq,
163                    value: Value::Bytes(q.token_hash.as_bytes().to_vec()),
164                },
165                order: Vec::new(),
166                limit: Some(1),
167                offset: None,
168            };
169            let Some(session) = self.find_one(select).await? else {
170                return Ok(None);
171            };
172            let user_id = session
173                .value("user_id")
174                .cloned()
175                .ok_or_else(|| DbError::Schema("session.user_id missing".into()))?;
176            let user_pk = q
177                .user
178                .position("id")
179                .ok_or_else(|| DbError::Schema("user.id missing".into()))?;
180            let select = Select {
181                table: q.user,
182                filter: Filter::Cmp {
183                    column: user_pk,
184                    op: Op::Eq,
185                    value: user_id,
186                },
187                order: Vec::new(),
188                limit: Some(1),
189                offset: None,
190            };
191            Ok(self.find_one(select).await?.map(|user| (session, user)))
192        }
193    }
194}