Skip to main content

fastauth_core/
memory.rs

1//! An in-memory adapter for tests and examples. Not for production: no durability, and a
2//! transaction is a snapshot that overwrites the store on commit.
3
4use std::cmp::Ordering;
5use std::collections::HashMap;
6use std::sync::{Arc, Mutex};
7
8use crate::adapter::{
9    Adapter, DbError, DbResult, Delete, Filter, Insert, Op, Order, Queries, Select, Transaction,
10    Update,
11};
12use crate::migrate::{LiveSchema, MigrationPlan, Step, duplicates_error, unique_key};
13use crate::schema::TableDef;
14use crate::value::{Row, Value};
15
16type Tables = HashMap<&'static str, Vec<Vec<Value>>>;
17
18#[derive(Clone, Default)]
19pub struct MemoryAdapter {
20    tables: Arc<Mutex<Tables>>,
21    live: Arc<Mutex<LiveSchema>>,
22}
23
24impl std::fmt::Debug for MemoryAdapter {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        f.write_str("MemoryAdapter")
27    }
28}
29
30impl MemoryAdapter {
31    pub fn new() -> Self {
32        Self::default()
33    }
34
35    /// Every row of a table, for assertions in tests.
36    pub fn dump(&self, table: &str) -> Vec<Vec<Value>> {
37        self.tables
38            .lock()
39            .unwrap()
40            .get(table)
41            .cloned()
42            .unwrap_or_default()
43    }
44}
45
46/// The stored name of `column`, which the live schema records, as a database would.
47fn stored<'t>(table: &'t TableDef, column: &'t str) -> &'t str {
48    table.stored_column(column).unwrap_or(column)
49}
50
51fn compare(a: &Value, b: &Value) -> Option<Ordering> {
52    match (a, b) {
53        (Value::Bool(a), Value::Bool(b)) => a.partial_cmp(b),
54        (Value::Int(a), Value::Int(b)) => a.partial_cmp(b),
55        (Value::Text(a), Value::Text(b)) => a.partial_cmp(b),
56        (Value::Bytes(a), Value::Bytes(b)) => a.partial_cmp(b),
57        (Value::Timestamp(a), Value::Timestamp(b)) => a.partial_cmp(b),
58        _ => None,
59    }
60}
61
62fn matches(filter: &Filter, row: &[Value]) -> bool {
63    match filter {
64        Filter::All => true,
65        Filter::Cmp { column, op, value } => {
66            let cell = &row[*column];
67            if cell.is_null() || value.is_null() {
68                return false;
69            }
70            let Some(ord) = compare(cell, value) else {
71                return *op == Op::Ne && cell != value;
72            };
73            match op {
74                Op::Eq => ord == Ordering::Equal,
75                Op::Ne => ord != Ordering::Equal,
76                Op::Lt => ord == Ordering::Less,
77                Op::Lte => ord != Ordering::Greater,
78                Op::Gt => ord == Ordering::Greater,
79                Op::Gte => ord != Ordering::Less,
80            }
81        }
82        Filter::In { column, values } => values.contains(&row[*column]),
83        Filter::Null { column, is_null } => row[*column].is_null() == *is_null,
84        Filter::StartsWith { column, prefix } => {
85            matches!(&row[*column], Value::Text(s) if s.starts_with(prefix.as_str()))
86        }
87        Filter::Contains { column, substring } => {
88            matches!(&row[*column], Value::Text(s) if s.contains(substring.as_str()))
89        }
90        Filter::EndsWith { column, suffix } => {
91            matches!(&row[*column], Value::Text(s) if s.ends_with(suffix.as_str()))
92        }
93        Filter::And(fs) => fs.iter().all(|f| matches(f, row)),
94        Filter::Or(fs) => fs.iter().any(|f| matches(f, row)),
95    }
96}
97
98fn check_unique(
99    table: &TableDef,
100    rows: &[Vec<Value>],
101    candidate: &[Value],
102    skip: Option<usize>,
103) -> DbResult<()> {
104    for (i, column) in table.columns.iter().enumerate() {
105        if !(column.unique || column.primary_key) || candidate[i].is_null() {
106            continue;
107        }
108        let clash = rows
109            .iter()
110            .enumerate()
111            .any(|(r, row)| Some(r) != skip && row[i] == candidate[i]);
112        if clash {
113            return Err(DbError::UniqueViolation {
114                table: table.name.to_owned(),
115                column: Some(column.name.to_owned()),
116            });
117        }
118    }
119    for unique in &table.uniques {
120        let positions: Vec<usize> = unique
121            .columns
122            .iter()
123            .filter_map(|c| table.position(c))
124            .collect();
125        if positions.iter().any(|&i| candidate[i].is_null()) {
126            continue;
127        }
128        let clash = rows
129            .iter()
130            .enumerate()
131            .any(|(r, row)| Some(r) != skip && positions.iter().all(|&i| row[i] == candidate[i]));
132        if clash {
133            return Err(DbError::UniqueViolation {
134                table: table.name.to_owned(),
135                column: None,
136            });
137        }
138    }
139    Ok(())
140}
141
142/// Some rows of `table` that share non-null values in `columns`, for `Step::AddUnique`.
143fn duplicates<'t>(
144    table: &'t TableDef,
145    rows: &[Vec<Value>],
146    columns: &[&'t str],
147) -> Vec<Vec<(&'t str, Value)>> {
148    let positions: Vec<(&str, usize)> = table
149        .primary_key()
150        .map(|pk| pk.name)
151        .into_iter()
152        .chain(columns.iter().copied())
153        .filter_map(|c| table.position(c).map(|i| (c, i)))
154        .collect();
155    let key = |row: &Vec<Value>| -> Option<Vec<Value>> {
156        let values: Vec<Value> = columns
157            .iter()
158            .filter_map(|c| table.position(c))
159            .map(|i| row[i].clone())
160            .collect();
161        (!values.iter().any(Value::is_null)).then_some(values)
162    };
163    rows.iter()
164        .filter(|row| {
165            key(row).is_some_and(|k| {
166                rows.iter()
167                    .filter(|other| key(other) == Some(k.clone()))
168                    .count()
169                    > 1
170            })
171        })
172        .take(10)
173        .map(|row| {
174            positions
175                .iter()
176                .map(|&(c, i)| (c, row[i].clone()))
177                .collect()
178        })
179        .collect()
180}
181
182fn select(tables: &Tables, q: &Select<'_>) -> Vec<Vec<Value>> {
183    let mut rows: Vec<Vec<Value>> = tables
184        .get(q.table.name)
185        .into_iter()
186        .flatten()
187        .filter(|r| matches(&q.filter, r))
188        .cloned()
189        .collect();
190    for (column, order) in q.order.iter().rev() {
191        rows.sort_by(|a, b| {
192            let ord = compare(&a[*column], &b[*column]).unwrap_or(Ordering::Equal);
193            if *order == Order::Desc {
194                ord.reverse()
195            } else {
196                ord
197            }
198        });
199    }
200    let offset = q.offset.unwrap_or(0) as usize;
201    let limit = q.limit.map_or(usize::MAX, |l| l as usize);
202    rows.into_iter().skip(offset).take(limit).collect()
203}
204
205fn insert(tables: &mut Tables, q: Insert<'_>) -> DbResult<Row> {
206    let rows = tables.entry(q.table.name).or_default();
207    check_unique(q.table, rows, &q.values, None)?;
208    rows.push(q.values.clone());
209    Ok(Row::new(q.table.clone(), q.values))
210}
211
212fn update(tables: &mut Tables, q: Update<'_>) -> DbResult<u64> {
213    let rows = tables.entry(q.table.name).or_default();
214    let targets: Vec<usize> = rows
215        .iter()
216        .enumerate()
217        .filter(|(_, r)| matches(&q.filter, r))
218        .map(|(i, _)| i)
219        .collect();
220    for &i in &targets {
221        let mut next = rows[i].clone();
222        for (column, value) in &q.set {
223            next[*column] = value.clone();
224        }
225        check_unique(q.table, rows, &next, Some(i))?;
226        rows[i] = next;
227    }
228    Ok(targets.len() as u64)
229}
230
231fn delete(tables: &mut Tables, q: Delete<'_>) -> u64 {
232    let rows = tables.entry(q.table.name).or_default();
233    let before = rows.len();
234    rows.retain(|r| !matches(&q.filter, r));
235    (before - rows.len()) as u64
236}
237
238fn rows_of(table: &Arc<TableDef>, raw: Vec<Vec<Value>>) -> Vec<Row> {
239    raw.into_iter()
240        .map(|v| Row::new(table.clone(), v))
241        .collect()
242}
243
244impl Queries for MemoryAdapter {
245    async fn insert(&self, q: Insert<'_>) -> DbResult<Row> {
246        insert(&mut self.tables.lock().unwrap(), q)
247    }
248
249    async fn find_one(&self, mut q: Select<'_>) -> DbResult<Option<Row>> {
250        q.limit = Some(1);
251        let raw = select(&self.tables.lock().unwrap(), &q);
252        Ok(rows_of(q.table, raw).pop())
253    }
254
255    async fn find_many(&self, q: Select<'_>) -> DbResult<Vec<Row>> {
256        let raw = select(&self.tables.lock().unwrap(), &q);
257        Ok(rows_of(q.table, raw))
258    }
259
260    async fn update(&self, q: Update<'_>) -> DbResult<u64> {
261        update(&mut self.tables.lock().unwrap(), q)
262    }
263
264    async fn delete(&self, q: Delete<'_>) -> DbResult<u64> {
265        Ok(delete(&mut self.tables.lock().unwrap(), q))
266    }
267
268    async fn count(&self, q: Select<'_>) -> DbResult<u64> {
269        Ok(select(&self.tables.lock().unwrap(), &q).len() as u64)
270    }
271}
272
273/// A snapshot of the store. Commit writes it back; drop or rollback discards it.
274pub struct MemoryTx {
275    target: Arc<Mutex<Tables>>,
276    snapshot: Mutex<Tables>,
277}
278
279impl Queries for MemoryTx {
280    async fn insert(&self, q: Insert<'_>) -> DbResult<Row> {
281        insert(&mut self.snapshot.lock().unwrap(), q)
282    }
283
284    async fn find_one(&self, mut q: Select<'_>) -> DbResult<Option<Row>> {
285        q.limit = Some(1);
286        let raw = select(&self.snapshot.lock().unwrap(), &q);
287        Ok(rows_of(q.table, raw).pop())
288    }
289
290    async fn find_many(&self, q: Select<'_>) -> DbResult<Vec<Row>> {
291        let raw = select(&self.snapshot.lock().unwrap(), &q);
292        Ok(rows_of(q.table, raw))
293    }
294
295    async fn update(&self, q: Update<'_>) -> DbResult<u64> {
296        update(&mut self.snapshot.lock().unwrap(), q)
297    }
298
299    async fn delete(&self, q: Delete<'_>) -> DbResult<u64> {
300        Ok(delete(&mut self.snapshot.lock().unwrap(), q))
301    }
302
303    async fn count(&self, q: Select<'_>) -> DbResult<u64> {
304        Ok(select(&self.snapshot.lock().unwrap(), &q).len() as u64)
305    }
306}
307
308impl Transaction for MemoryTx {
309    async fn commit(self) -> DbResult<()> {
310        *self.target.lock().unwrap() = self.snapshot.into_inner().unwrap();
311        Ok(())
312    }
313
314    async fn rollback(self) -> DbResult<()> {
315        Ok(())
316    }
317}
318
319impl Adapter for MemoryAdapter {
320    type Tx = MemoryTx;
321
322    async fn begin(&self) -> DbResult<MemoryTx> {
323        let snapshot = self.tables.lock().unwrap().clone();
324        Ok(MemoryTx {
325            target: self.tables.clone(),
326            snapshot: Mutex::new(snapshot),
327        })
328    }
329
330    async fn introspect(&self) -> DbResult<LiveSchema> {
331        Ok(self.live.lock().unwrap().clone())
332    }
333
334    async fn apply(&self, plan: &MigrationPlan) -> DbResult<()> {
335        let tables = self.tables.lock().unwrap();
336        for step in &plan.steps {
337            if let Step::AddUnique { table, columns } = step {
338                let rows = tables
339                    .get(table.name)
340                    .map(Vec::as_slice)
341                    .unwrap_or_default();
342                let clashing = duplicates(table, rows, columns);
343                if !clashing.is_empty() {
344                    return Err(duplicates_error(table.name, columns, &clashing));
345                }
346            }
347        }
348        drop(tables);
349        let mut live = self.live.lock().unwrap();
350        let mut uniques = live.uniques.take().unwrap_or_default();
351        for step in &plan.steps {
352            match step {
353                Step::CreateTable(t) => {
354                    live.tables.insert(
355                        t.name.to_owned(),
356                        (0..t.columns.len())
357                            .map(|i| t.stored_name(i).to_owned())
358                            .collect(),
359                    );
360                    uniques.extend(
361                        t.columns
362                            .iter()
363                            .filter(|c| c.unique && !c.primary_key)
364                            .map(|c| unique_key(t.name, &[stored(t, c.name)])),
365                    );
366                }
367                Step::AddColumn { table, column } => {
368                    live.tables
369                        .entry(table.name.to_owned())
370                        .or_default()
371                        .insert(stored(table, column.name).to_owned());
372                    if column.unique {
373                        uniques.insert(unique_key(table.name, &[stored(table, column.name)]));
374                    }
375                }
376                Step::AddUnique { table, columns } => {
377                    let columns: Vec<&str> = columns.iter().map(|c| stored(table, c)).collect();
378                    uniques.insert(unique_key(table.name, &columns));
379                }
380                Step::CreateIndex { table, column } => {
381                    live.indexes
382                        .insert((table.name.to_owned(), stored(table, column.name).to_owned()));
383                }
384            }
385        }
386        live.uniques = Some(uniques);
387        Ok(())
388    }
389}