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#[derive(Clone, Debug, PartialEq)]
62pub enum Filter {
63    All,
64    Cmp { column: usize, op: Op, value: Value },
65    In { column: usize, values: Vec<Value> },
66    Null { column: usize, is_null: bool },
67    StartsWith { column: usize, prefix: String },
68    And(Vec<Filter>),
69    Or(Vec<Filter>),
70}
71
72#[derive(Clone, Debug)]
73pub struct Insert<'a> {
74    pub table: &'a Arc<TableDef>,
75    /// One value per column, in column order. Defaults are already applied.
76    pub values: Vec<Value>,
77}
78
79#[derive(Clone, Debug)]
80pub struct Select<'a> {
81    pub table: &'a Arc<TableDef>,
82    pub filter: Filter,
83    pub order: Vec<(usize, Order)>,
84    pub limit: Option<u64>,
85    pub offset: Option<u64>,
86}
87
88#[derive(Clone, Debug)]
89pub struct Update<'a> {
90    pub table: &'a Arc<TableDef>,
91    pub filter: Filter,
92    pub set: Vec<(usize, Value)>,
93}
94
95#[derive(Clone, Debug)]
96pub struct Delete<'a> {
97    pub table: &'a Arc<TableDef>,
98    pub filter: Filter,
99}
100
101/// The fast path for session lookup. SQL adapters answer it with one JOIN.
102#[derive(Clone, Debug)]
103pub struct SessionWithUser<'a> {
104    pub session: &'a Arc<TableDef>,
105    pub user: &'a Arc<TableDef>,
106    pub token_hash: &'a Hash,
107}
108
109/// CRUD over dynamic rows. Implemented by adapters and by their transactions.
110pub trait Queries: Send + Sync {
111    fn insert(&self, q: Insert<'_>) -> impl Future<Output = DbResult<Row>> + Send;
112    fn find_one(&self, q: Select<'_>) -> impl Future<Output = DbResult<Option<Row>>> + Send;
113    fn find_many(&self, q: Select<'_>) -> impl Future<Output = DbResult<Vec<Row>>> + Send;
114    fn update(&self, q: Update<'_>) -> impl Future<Output = DbResult<u64>> + Send;
115    fn delete(&self, q: Delete<'_>) -> impl Future<Output = DbResult<u64>> + Send;
116    fn count(&self, q: Select<'_>) -> impl Future<Output = DbResult<u64>> + Send;
117}
118
119pub trait Transaction: Queries + 'static {
120    fn commit(self) -> impl Future<Output = DbResult<()>> + Send;
121    fn rollback(self) -> impl Future<Output = DbResult<()>> + Send;
122}
123
124pub trait Adapter: Queries + 'static {
125    type Tx: Transaction;
126
127    fn begin(&self) -> impl Future<Output = DbResult<Self::Tx>> + Send;
128
129    /// Reads the live schema for the migrator. Adapters without DDL return `Unsupported`.
130    fn introspect(&self) -> impl Future<Output = DbResult<LiveSchema>> + Send;
131
132    /// Applies a migration plan computed by the migrator.
133    fn apply(&self, plan: &MigrationPlan) -> impl Future<Output = DbResult<()>> + Send;
134
135    /// Renders a plan as SQL for `fastauth generate`. Non-SQL adapters return `Unsupported`.
136    fn render_sql(&self, plan: &MigrationPlan) -> DbResult<String> {
137        let _ = plan;
138        Err(DbError::Unsupported("SQL rendering"))
139    }
140
141    /// Session plus user in one call. The default does two lookups; SQL adapters override.
142    fn session_with_user(
143        &self,
144        q: SessionWithUser<'_>,
145    ) -> impl Future<Output = DbResult<Option<(Row, Row)>>> + Send {
146        async move {
147            let session_hash = q
148                .session
149                .position("token_hash")
150                .ok_or_else(|| DbError::Schema("session.token_hash missing".into()))?;
151            let select = Select {
152                table: q.session,
153                filter: Filter::Cmp {
154                    column: session_hash,
155                    op: Op::Eq,
156                    value: Value::Bytes(q.token_hash.as_bytes().to_vec()),
157                },
158                order: Vec::new(),
159                limit: Some(1),
160                offset: None,
161            };
162            let Some(session) = self.find_one(select).await? else {
163                return Ok(None);
164            };
165            let user_id = session
166                .value("user_id")
167                .cloned()
168                .ok_or_else(|| DbError::Schema("session.user_id missing".into()))?;
169            let user_pk = q
170                .user
171                .position("id")
172                .ok_or_else(|| DbError::Schema("user.id missing".into()))?;
173            let select = Select {
174                table: q.user,
175                filter: Filter::Cmp {
176                    column: user_pk,
177                    op: Op::Eq,
178                    value: user_id,
179                },
180                order: Vec::new(),
181                limit: Some(1),
182                offset: None,
183            };
184            Ok(self.find_one(select).await?.map(|user| (session, user)))
185        }
186    }
187}