1use 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 #[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#[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 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#[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#[derive(Clone, Debug)]
120pub struct SessionWithUserByToken<'a> {
121 pub session: &'a Arc<TableDef>,
122 pub user: &'a Arc<TableDef>,
123 pub token: &'a str,
124}
125
126async fn session_then_user<A: Adapter + ?Sized>(
128 adapter: &A,
129 session: &Arc<TableDef>,
130 user: &Arc<TableDef>,
131 column: &str,
132 value: Value,
133) -> DbResult<Option<(Row, Row)>> {
134 let position = session
135 .position(column)
136 .ok_or_else(|| DbError::Schema(format!("session.{column} missing")))?;
137 let select = Select {
138 table: session,
139 filter: Filter::Cmp {
140 column: position,
141 op: Op::Eq,
142 value,
143 },
144 order: Vec::new(),
145 limit: Some(1),
146 offset: None,
147 };
148 let Some(found) = adapter.find_one(select).await? else {
149 return Ok(None);
150 };
151 let user_id = found
152 .value("user_id")
153 .cloned()
154 .ok_or_else(|| DbError::Schema("session.user_id missing".into()))?;
155 let user_pk = user
156 .position("id")
157 .ok_or_else(|| DbError::Schema("user.id missing".into()))?;
158 let select = Select {
159 table: user,
160 filter: Filter::Cmp {
161 column: user_pk,
162 op: Op::Eq,
163 value: user_id,
164 },
165 order: Vec::new(),
166 limit: Some(1),
167 offset: None,
168 };
169 Ok(adapter.find_one(select).await?.map(|row| (found, row)))
170}
171
172pub trait Queries: Send + Sync {
174 fn insert(&self, q: Insert<'_>) -> impl Future<Output = DbResult<Row>> + Send;
175 fn find_one(&self, q: Select<'_>) -> impl Future<Output = DbResult<Option<Row>>> + Send;
176 fn find_many(&self, q: Select<'_>) -> impl Future<Output = DbResult<Vec<Row>>> + Send;
177 fn update(&self, q: Update<'_>) -> impl Future<Output = DbResult<u64>> + Send;
178 fn delete(&self, q: Delete<'_>) -> impl Future<Output = DbResult<u64>> + Send;
179 fn count(&self, q: Select<'_>) -> impl Future<Output = DbResult<u64>> + Send;
180}
181
182pub trait Transaction: Queries + 'static {
183 fn commit(self) -> impl Future<Output = DbResult<()>> + Send;
184 fn rollback(self) -> impl Future<Output = DbResult<()>> + Send;
185}
186
187pub trait Adapter: Queries + 'static {
188 type Tx: Transaction;
189
190 fn begin(&self) -> impl Future<Output = DbResult<Self::Tx>> + Send;
191
192 fn introspect(&self) -> impl Future<Output = DbResult<LiveSchema>> + Send;
194
195 fn apply(&self, plan: &MigrationPlan) -> impl Future<Output = DbResult<()>> + Send;
197
198 fn render_sql(&self, plan: &MigrationPlan) -> DbResult<String> {
200 let _ = plan;
201 Err(DbError::Unsupported("SQL rendering"))
202 }
203
204 fn session_with_user(
206 &self,
207 q: SessionWithUser<'_>,
208 ) -> impl Future<Output = DbResult<Option<(Row, Row)>>> + Send {
209 let value = Value::Bytes(q.token_hash.as_bytes().to_vec());
210 session_then_user(self, q.session, q.user, "token_hash", value)
211 }
212
213 fn session_with_user_by_token(
217 &self,
218 q: SessionWithUserByToken<'_>,
219 ) -> impl Future<Output = DbResult<Option<(Row, Row)>>> + Send {
220 let value = Value::Text(q.token.to_owned());
221 session_then_user(self, q.session, q.user, "token", value)
222 }
223
224 fn duplicates_query(&self, table: &TableDef, columns: &[&str]) -> Option<String> {
229 let _ = (table, columns);
230 None
231 }
232}