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