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};
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    Ok(())
115}
116
117fn select(tables: &Tables, q: &Select<'_>) -> Vec<Vec<Value>> {
118    let mut rows: Vec<Vec<Value>> = tables
119        .get(q.table.name)
120        .into_iter()
121        .flatten()
122        .filter(|r| matches(&q.filter, r))
123        .cloned()
124        .collect();
125    for (column, order) in q.order.iter().rev() {
126        rows.sort_by(|a, b| {
127            let ord = compare(&a[*column], &b[*column]).unwrap_or(Ordering::Equal);
128            if *order == Order::Desc {
129                ord.reverse()
130            } else {
131                ord
132            }
133        });
134    }
135    let offset = q.offset.unwrap_or(0) as usize;
136    let limit = q.limit.map_or(usize::MAX, |l| l as usize);
137    rows.into_iter().skip(offset).take(limit).collect()
138}
139
140fn insert(tables: &mut Tables, q: Insert<'_>) -> DbResult<Row> {
141    let rows = tables.entry(q.table.name).or_default();
142    check_unique(q.table, rows, &q.values, None)?;
143    rows.push(q.values.clone());
144    Ok(Row::new(q.table.clone(), q.values))
145}
146
147fn update(tables: &mut Tables, q: Update<'_>) -> DbResult<u64> {
148    let rows = tables.entry(q.table.name).or_default();
149    let targets: Vec<usize> = rows
150        .iter()
151        .enumerate()
152        .filter(|(_, r)| matches(&q.filter, r))
153        .map(|(i, _)| i)
154        .collect();
155    for &i in &targets {
156        let mut next = rows[i].clone();
157        for (column, value) in &q.set {
158            next[*column] = value.clone();
159        }
160        check_unique(q.table, rows, &next, Some(i))?;
161        rows[i] = next;
162    }
163    Ok(targets.len() as u64)
164}
165
166fn delete(tables: &mut Tables, q: Delete<'_>) -> u64 {
167    let rows = tables.entry(q.table.name).or_default();
168    let before = rows.len();
169    rows.retain(|r| !matches(&q.filter, r));
170    (before - rows.len()) as u64
171}
172
173fn rows_of(table: &Arc<TableDef>, raw: Vec<Vec<Value>>) -> Vec<Row> {
174    raw.into_iter()
175        .map(|v| Row::new(table.clone(), v))
176        .collect()
177}
178
179impl Queries for MemoryAdapter {
180    async fn insert(&self, q: Insert<'_>) -> DbResult<Row> {
181        insert(&mut self.tables.lock().unwrap(), q)
182    }
183
184    async fn find_one(&self, mut q: Select<'_>) -> DbResult<Option<Row>> {
185        q.limit = Some(1);
186        let raw = select(&self.tables.lock().unwrap(), &q);
187        Ok(rows_of(q.table, raw).pop())
188    }
189
190    async fn find_many(&self, q: Select<'_>) -> DbResult<Vec<Row>> {
191        let raw = select(&self.tables.lock().unwrap(), &q);
192        Ok(rows_of(q.table, raw))
193    }
194
195    async fn update(&self, q: Update<'_>) -> DbResult<u64> {
196        update(&mut self.tables.lock().unwrap(), q)
197    }
198
199    async fn delete(&self, q: Delete<'_>) -> DbResult<u64> {
200        Ok(delete(&mut self.tables.lock().unwrap(), q))
201    }
202
203    async fn count(&self, q: Select<'_>) -> DbResult<u64> {
204        Ok(select(&self.tables.lock().unwrap(), &q).len() as u64)
205    }
206}
207
208/// A snapshot of the store. Commit writes it back; drop or rollback discards it.
209pub struct MemoryTx {
210    target: Arc<Mutex<Tables>>,
211    snapshot: Mutex<Tables>,
212}
213
214impl Queries for MemoryTx {
215    async fn insert(&self, q: Insert<'_>) -> DbResult<Row> {
216        insert(&mut self.snapshot.lock().unwrap(), q)
217    }
218
219    async fn find_one(&self, mut q: Select<'_>) -> DbResult<Option<Row>> {
220        q.limit = Some(1);
221        let raw = select(&self.snapshot.lock().unwrap(), &q);
222        Ok(rows_of(q.table, raw).pop())
223    }
224
225    async fn find_many(&self, q: Select<'_>) -> DbResult<Vec<Row>> {
226        let raw = select(&self.snapshot.lock().unwrap(), &q);
227        Ok(rows_of(q.table, raw))
228    }
229
230    async fn update(&self, q: Update<'_>) -> DbResult<u64> {
231        update(&mut self.snapshot.lock().unwrap(), q)
232    }
233
234    async fn delete(&self, q: Delete<'_>) -> DbResult<u64> {
235        Ok(delete(&mut self.snapshot.lock().unwrap(), q))
236    }
237
238    async fn count(&self, q: Select<'_>) -> DbResult<u64> {
239        Ok(select(&self.snapshot.lock().unwrap(), &q).len() as u64)
240    }
241}
242
243impl Transaction for MemoryTx {
244    async fn commit(self) -> DbResult<()> {
245        *self.target.lock().unwrap() = self.snapshot.into_inner().unwrap();
246        Ok(())
247    }
248
249    async fn rollback(self) -> DbResult<()> {
250        Ok(())
251    }
252}
253
254impl Adapter for MemoryAdapter {
255    type Tx = MemoryTx;
256
257    async fn begin(&self) -> DbResult<MemoryTx> {
258        let snapshot = self.tables.lock().unwrap().clone();
259        Ok(MemoryTx {
260            target: self.tables.clone(),
261            snapshot: Mutex::new(snapshot),
262        })
263    }
264
265    async fn introspect(&self) -> DbResult<LiveSchema> {
266        Ok(self.live.lock().unwrap().clone())
267    }
268
269    async fn apply(&self, plan: &MigrationPlan) -> DbResult<()> {
270        let mut live = self.live.lock().unwrap();
271        for step in &plan.steps {
272            match step {
273                Step::CreateTable(t) => {
274                    live.tables.insert(
275                        t.name.to_owned(),
276                        t.columns.iter().map(|c| c.name.to_owned()).collect(),
277                    );
278                }
279                Step::AddColumn { table, column } => {
280                    live.tables
281                        .entry(table.name.to_owned())
282                        .or_default()
283                        .insert(column.name.to_owned());
284                }
285                Step::CreateIndex { table, column } => {
286                    live.indexes
287                        .insert((table.name.to_owned(), column.name.to_owned()));
288                }
289            }
290        }
291        Ok(())
292    }
293}