cqrs-rust-lib 0.11.0

An opinionated implementation of CQRS/Event Sourcing with pluggable storage backends (InMemory, PostgreSQL, MongoDB, SurrealDB)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
use crate::read::page_order::warn_if_page_order_undefined;
use crate::read::query::{Pagination, Query};
use crate::read::sorter::order_by_clause;
use crate::read::storage::{HasId, Storage, StorageError};
use crate::read::Paged;
use crate::{Aggregate, CqrsContext, CqrsError};
use rest_sql::FieldMapper;
use rest_sql_drivers::surrealdb::SurrealCompiler;
use rest_sql_drivers::Driver;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::borrow::Cow;
use std::fmt::Debug;
use std::marker::PhantomData;
use surrealdb::engine::any::Any;
use surrealdb::Surreal;
use surrealdb_types::SurrealValue;

fn map_surreal_error(e: surrealdb::Error) -> CqrsError {
    CqrsError::database_error(e)
}

/// Maps field names with a `data.` prefix — used for CQRS views where entities
/// are stored under a `data` field in SurrealDB records.
#[derive(Debug, Clone)]
pub struct DataPrefixMapper;

impl FieldMapper for DataPrefixMapper {
    fn map<'a>(&self, field: &'a str) -> Cow<'a, str> {
        Cow::Owned(format!("data.{}", field))
    }
}

#[derive(Debug, serde::Deserialize, SurrealValue)]
struct CountRow {
    cnt: i64,
}

#[derive(Debug, serde::Deserialize, SurrealValue)]
struct DataRow {
    data: JsonValue,
}

#[derive(Debug, Clone)]
pub struct SurrealDBStorage<V, Q, M = DataPrefixMapper> {
    _phantom: PhantomData<(V, Q)>,
    db: Surreal<Any>,
    type_name: String,
    table_name: String,
    mapper: M,
}

impl<V, Q> SurrealDBStorage<V, Q, DataPrefixMapper> {
    #[must_use]
    pub fn new(db: Surreal<Any>, type_name: &str, table_name: &str) -> Self {
        Self::with_mapper(db, type_name, table_name, DataPrefixMapper)
    }
}

impl<V, Q, M> SurrealDBStorage<V, Q, M>
where
    M: FieldMapper + Debug + Clone + Send + Sync,
{
    #[must_use]
    pub fn with_mapper(db: Surreal<Any>, type_name: &str, table_name: &str, mapper: M) -> Self {
        Self {
            _phantom: PhantomData,
            db,
            type_name: type_name.to_string(),
            table_name: table_name.to_string(),
            mapper,
        }
    }

    fn build_where(
        &self,
        user_filter: Option<String>,
        parent_id: &Option<String>,
    ) -> Result<String, CqrsError>
    where
        V: HasId,
    {
        let mut clauses: Vec<String> = Vec::new();
        if let Some(w) = user_filter.filter(|w| !w.trim().is_empty()) {
            clauses.push(format!("({})", w));
        }
        match (V::parent_field_id(), parent_id) {
            (Some(_), Some(_)) => clauses.push("parent_id = $__cqrs_parent_id".to_string()),
            (Some(_), None) => {
                return Err(CqrsError::validation(
                    StorageError::MissingParentId.to_string(),
                ));
            }
            _ => {}
        }
        if clauses.is_empty() {
            Ok(String::new())
        } else {
            Ok(format!("WHERE {}", clauses.join(" AND ")))
        }
    }
}

cqrs_async_trait! {
impl<V, Q, M> Storage<V, Q> for SurrealDBStorage<V, Q, M>
where
    V: Debug + Clone + Default + Serialize + DeserializeOwned + Send + Sync + HasId,
    Q: Clone + Debug + Send + Sync + Query,
    M: FieldMapper + Debug + Clone + Send + Sync,
{
    fn type_name(&self) -> &str {
        &self.type_name
    }

    async fn filter(
        &self,
        parent_id: Option<String>,
        query: Q,
        _context: CqrsContext,
    ) -> Result<Paged<V>, CqrsError> {
        let user_filter = match query.filter() {
            Some(rsql) => Some(
                SurrealCompiler::new(self.mapper.clone())
                    .compile(&rsql)
                    .map_err(|e| CqrsError::internal(e.to_string()))?,
            ),
            None => None,
        };
        let where_clause = self.build_where(user_filter, &parent_id)?;
        let Pagination { skip, limit } = query.pagination().unwrap_or_default();
        let limit_v = limit.unwrap_or(20).max(0);
        let offset_v = skip.unwrap_or(0).max(0);

        let sort = query.sort();
        warn_if_page_order_undefined(&self.type_name, offset_v, sort.as_deref());
        let order_by = order_by_clause(sort, &self.mapper)?;

        let count_sql = format!(
            "SELECT count() AS cnt FROM {} {} GROUP ALL",
            self.table_name, where_clause
        );
        let mut count_q = self.db.query(count_sql);
        if let Some(pid) = parent_id.as_ref() {
            count_q = count_q.bind(("__cqrs_parent_id", pid.clone()));
        }
        let mut r = count_q.await.map_err(map_surreal_error)?;
        let counts: Vec<CountRow> = r.take(0).map_err(map_surreal_error)?;
        let total = counts.first().map(|c| c.cnt).unwrap_or(0);

        // SELECT * so fields referenced in ORDER BY are projected (SurrealDB v3 requirement).
        let select_sql = format!(
            "SELECT * FROM {} {}{} LIMIT $__cqrs_limit START $__cqrs_offset",
            self.table_name, where_clause, order_by
        );
        let mut select_q = self
            .db
            .query(select_sql)
            .bind(("__cqrs_limit", limit_v))
            .bind(("__cqrs_offset", offset_v));
        if let Some(pid) = parent_id.as_ref() {
            select_q = select_q.bind(("__cqrs_parent_id", pid.clone()));
        }
        let mut result = select_q.await.map_err(map_surreal_error)?;
        let rows: Vec<DataRow> = result.take(0).map_err(map_surreal_error)?;
        let mut items: Vec<V> = Vec::with_capacity(rows.len());
        for row in rows {
            let v: V = serde_json::from_value(row.data).map_err(CqrsError::serialization_error)?;
            items.push(v);
        }
        Ok(Paged::new(items, total, offset_v, limit_v))
    }

    async fn find_by_id(
        &self,
        parent_id: Option<String>,
        id: &str,
        _context: CqrsContext,
    ) -> Result<Option<V>, CqrsError> {
        let id = id.to_string();
        let table = self.table_name.clone();
        let mut where_clause = String::from("id = type::record($__cqrs_table, $__cqrs_id)");
        match (V::parent_field_id(), parent_id.as_ref()) {
            (Some(_), Some(_)) => where_clause.push_str(" AND parent_id = $__cqrs_parent_id"),
            (Some(_), None) => {
                return Err(CqrsError::validation(
                    StorageError::MissingParentId.to_string(),
                ))
            }
            _ => {}
        }
        let sql = format!("SELECT data FROM {} WHERE {}", self.table_name, where_clause);
        let mut q = self
            .db
            .query(sql)
            .bind(("__cqrs_table", table))
            .bind(("__cqrs_id", id));
        if let Some(pid) = parent_id {
            q = q.bind(("__cqrs_parent_id", pid));
        }
        let mut result = q.await.map_err(map_surreal_error)?;
        let rows: Vec<DataRow> = result.take(0).map_err(map_surreal_error)?;
        match rows.into_iter().next() {
            Some(row) => {
                let v: V =
                    serde_json::from_value(row.data).map_err(CqrsError::serialization_error)?;
                Ok(Some(v))
            }
            None => Ok(None),
        }
    }

    async fn save(&self, entity: V, _context: CqrsContext) -> Result<(), CqrsError> {
        let id = entity.id().to_string();
        let parent_id = entity.parent_id().map(|s| s.to_string());
        let data = serde_json::to_value(&entity).map_err(CqrsError::serialization_error)?;
        if V::parent_field_id().is_some() && parent_id.is_none() {
            return Err(CqrsError::validation(
                StorageError::MissingParentId.to_string(),
            ));
        }
        let table = self.table_name.clone();
        self.db
            .query(
                "UPSERT type::record($__cqrs_table, $__cqrs_id) SET parent_id = $__cqrs_parent, data = $__cqrs_data",
            )
            .bind(("__cqrs_table", table))
            .bind(("__cqrs_id", id))
            .bind(("__cqrs_parent", parent_id))
            .bind(("__cqrs_data", data))
            .await
            .map_err(map_surreal_error)?
            .check()
            .map_err(map_surreal_error)?;
        Ok(())
    }
}
}

const NO_PARENT_ON_SNAPSHOT: &str =
    "a snapshot table has no parent column, so a parent id cannot be filtered on";

/// Read-side storage over the event store's **snapshot** table.
///
/// This does not reuse [`SurrealDBStorage`], for the same reason as the Postgres one: the
/// snapshot row stores the **bare aggregate** under `data`, while the view storage
/// deserializes that field into its `V`. Pointing it at `Snapshot<A>` asked for a shape
/// nobody wrote, and every read failed with `missing field \`_id\``. See #10.
///
/// The row layout does line up otherwise — the record id is the aggregate id, and
/// `DataPrefixMapper` already maps a logical name onto `data.field`, which is where the
/// aggregate's own fields live. So the queries here are the view storage's, with `data`
/// read as an `A` and no parent column. Writing stays unsupported: the event store owns
/// this table.
#[derive(Debug, Clone)]
pub struct SurrealDBFromSnapshotStorage<A, Q, M = DataPrefixMapper> {
    _phantom: PhantomData<(A, Q)>,
    db: Surreal<Any>,
    snapshot_table: String,
    mapper: M,
}

impl<A, Q> SurrealDBFromSnapshotStorage<A, Q, DataPrefixMapper> {
    /// `snapshot_table` is what `SurrealDBPersist::snapshot_table_name()` returns.
    #[must_use]
    pub fn new(db: Surreal<Any>, snapshot_table: &str) -> Self {
        Self::with_mapper(db, snapshot_table, DataPrefixMapper)
    }
}

impl<A, Q, M> SurrealDBFromSnapshotStorage<A, Q, M> {
    #[must_use]
    pub fn with_mapper(db: Surreal<Any>, snapshot_table: &str, mapper: M) -> Self {
        Self {
            _phantom: PhantomData,
            db,
            snapshot_table: snapshot_table.to_string(),
            mapper,
        }
    }
}

cqrs_async_trait! {
impl<A, Q, M> Storage<A, Q> for SurrealDBFromSnapshotStorage<A, Q, M>
where
    A: Aggregate,
    Q: Clone + Debug + Send + Sync + Query,
    M: FieldMapper + Debug + Clone + Send + Sync,
{
    fn type_name(&self) -> &str {
        A::TYPE
    }

    async fn filter(
        &self,
        parent_id: Option<String>,
        query: Q,
        _context: CqrsContext,
    ) -> Result<Paged<A>, CqrsError> {
        if parent_id.is_some() {
            return Err(CqrsError::validation(NO_PARENT_ON_SNAPSHOT));
        }

        let where_clause = match query.filter() {
            Some(rsql) => {
                let compiled = SurrealCompiler::new(self.mapper.clone())
                    .compile(&rsql)
                    .map_err(|e| CqrsError::internal(e.to_string()))?;
                format!("WHERE {}", compiled)
            }
            None => String::new(),
        };

        let Pagination { skip, limit } = query.pagination().unwrap_or_default();
        let limit_v = limit.unwrap_or(20).max(0);
        let offset_v = skip.unwrap_or(0).max(0);

        let sort = query.sort();
        warn_if_page_order_undefined(A::TYPE, offset_v, sort.as_deref());
        let order_by = order_by_clause(sort, &self.mapper)?;

        let count_sql = format!(
            "SELECT count() AS cnt FROM {} {} GROUP ALL",
            self.snapshot_table, where_clause
        );
        let mut r = self.db.query(count_sql).await.map_err(map_surreal_error)?;
        let counts: Vec<CountRow> = r.take(0).map_err(map_surreal_error)?;
        let total = counts.first().map(|c| c.cnt).unwrap_or(0);

        // SELECT * so fields referenced in ORDER BY are projected (SurrealDB v3).
        let select_sql = format!(
            "SELECT * FROM {} {}{} LIMIT $__cqrs_limit START $__cqrs_offset",
            self.snapshot_table, where_clause, order_by
        );
        let mut result = self
            .db
            .query(select_sql)
            .bind(("__cqrs_limit", limit_v))
            .bind(("__cqrs_offset", offset_v))
            .await
            .map_err(map_surreal_error)?;
        let rows: Vec<DataRow> = result.take(0).map_err(map_surreal_error)?;

        let mut items: Vec<A> = Vec::with_capacity(rows.len());
        for row in rows {
            // `data` is the aggregate itself, not a `Snapshot` wrapper.
            items.push(serde_json::from_value(row.data).map_err(CqrsError::serialization_error)?);
        }
        Ok(Paged::new(items, total, offset_v, limit_v))
    }

    async fn find_by_id(
        &self,
        parent_id: Option<String>,
        id: &str,
        _context: CqrsContext,
    ) -> Result<Option<A>, CqrsError> {
        if parent_id.is_some() {
            return Err(CqrsError::validation(NO_PARENT_ON_SNAPSHOT));
        }

        // The snapshot's record id *is* the aggregate id — `save_snapshot` upserts
        // `type::record($table, $aggregate_id)`.
        let sql = format!(
            "SELECT data FROM {} WHERE id = type::record($__cqrs_table, $__cqrs_id)",
            self.snapshot_table
        );
        let mut result = self
            .db
            .query(sql)
            .bind(("__cqrs_table", self.snapshot_table.clone()))
            .bind(("__cqrs_id", id.to_string()))
            .await
            .map_err(map_surreal_error)?;
        let rows: Vec<DataRow> = result.take(0).map_err(map_surreal_error)?;

        match rows.into_iter().next() {
            Some(row) => Ok(Some(
                serde_json::from_value(row.data).map_err(CqrsError::serialization_error)?,
            )),
            None => Ok(None),
        }
    }

    async fn save(&self, _entity: A, _context: CqrsContext) -> Result<(), CqrsError> {
        Err(CqrsError::database_error(StorageError::UnsupportedMethod(
            "SnapshotStorage#save".to_string(),
        )))
    }
}
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::log_capture::{containing, events_of_async};
    use crate::read::query::{Pagination, Query};
    use crate::read::storage::Storage;
    use crate::read::Sorter;
    use crate::CqrsContext;
    use rest_sql::{filter, RestSql};
    use serde::{Deserialize, Serialize};
    use surrealdb::engine::any::connect;

    // ── Test view type ───────────────────────────────────────────────────────

    #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
    struct Article {
        id: String,
        title: String,
        score: i32,
    }

    impl HasId for Article {
        fn field_id() -> &'static str {
            "id"
        }
        fn id(&self) -> &str {
            &self.id
        }
        fn parent_field_id() -> Option<&'static str> {
            None
        }
        fn parent_id(&self) -> Option<&str> {
            None
        }
    }

    // ── Query ────────────────────────────────────────────────────────────────

    #[derive(Debug, Clone, Default, Serialize, Deserialize)]
    struct ArticleQuery {
        min_score: Option<i32>,
    }

    impl Query for ArticleQuery {
        fn filter(&self) -> Option<RestSql> {
            let score = self.min_score?;
            RestSql::from_ast(filter::gte("score", score as i64)).ok()
        }

        fn pagination(&self) -> Option<Pagination> {
            Some(Pagination {
                skip: None,
                limit: Some(10),
            })
        }

        fn sort(&self) -> Option<Vec<Sorter>> {
            Some(vec![Sorter {
                field: "score".into(),
                direction: crate::read::sorter::SortDirection::Asc,
            }])
        }
    }

    // ── Setup helper ─────────────────────────────────────────────────────────

    /// A fresh in-memory store. The view name is a parameter because the page-order
    /// warning is once-per-view and its state is process-global, so a test that asserts
    /// on the warning needs a name no other test has used.
    async fn setup_named<Q>(type_name: &str) -> SurrealDBStorage<Article, Q> {
        let db = connect("mem://").await.unwrap();
        db.use_ns("test").use_db("test").await.unwrap();
        db.query("DEFINE TABLE IF NOT EXISTS articles SCHEMALESS")
            .await
            .unwrap()
            .check()
            .unwrap();
        SurrealDBStorage::new(db, type_name, "articles")
    }

    async fn setup_for<Q>() -> SurrealDBStorage<Article, Q> {
        setup_named("article").await
    }

    async fn setup() -> SurrealDBStorage<Article, ArticleQuery> {
        setup_for().await
    }

    fn article(id: &str, title: &str, score: i32) -> Article {
        Article {
            id: id.to_string(),
            title: title.to_string(),
            score,
        }
    }

    // ── Tests ────────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn save_and_find_by_id() {
        let store = setup().await;
        let ctx = CqrsContext::default();

        let a = article("a1", "Hello", 42);
        store.save(a.clone(), ctx.clone()).await.unwrap();

        let found = store.find_by_id(None, "a1", ctx).await.unwrap();
        assert_eq!(found, Some(a));
    }

    #[tokio::test]
    async fn find_by_id_returns_none_when_missing() {
        let store = setup().await;
        let ctx = CqrsContext::default();

        let found = store.find_by_id(None, "nonexistent", ctx).await.unwrap();
        assert!(found.is_none());
    }

    #[tokio::test]
    async fn upsert_replaces_existing_record() {
        let store = setup().await;
        let ctx = CqrsContext::default();

        store
            .save(article("a1", "First", 1), ctx.clone())
            .await
            .unwrap();
        store
            .save(article("a1", "Updated", 99), ctx.clone())
            .await
            .unwrap();

        let found = store.find_by_id(None, "a1", ctx).await.unwrap().unwrap();
        assert_eq!(found.title, "Updated");
        assert_eq!(found.score, 99);
    }

    #[tokio::test]
    async fn filter_returns_all_when_no_where() {
        let store = setup().await;
        let ctx = CqrsContext::default();

        for (id, title, score) in [("a1", "A", 10), ("a2", "B", 20), ("a3", "C", 30)] {
            store
                .save(article(id, title, score), ctx.clone())
                .await
                .unwrap();
        }

        let result = store
            .filter(None, ArticleQuery::default(), ctx)
            .await
            .unwrap();
        assert_eq!(result.total, 3);
        assert_eq!(result.items.len(), 3);
    }

    #[tokio::test]
    async fn filter_with_min_score() {
        let store = setup().await;
        let ctx = CqrsContext::default();

        for (id, title, score) in [("a1", "Low", 5), ("a2", "Mid", 50), ("a3", "High", 100)] {
            store
                .save(article(id, title, score), ctx.clone())
                .await
                .unwrap();
        }

        let result = store
            .filter(
                None,
                ArticleQuery {
                    min_score: Some(50),
                },
                ctx,
            )
            .await
            .unwrap();
        assert_eq!(result.total, 2);
        assert!(result.items.iter().all(|a| a.score >= 50));
    }

    #[tokio::test]
    async fn filter_ordering() {
        let store = setup().await;
        let ctx = CqrsContext::default();

        for i in 1..=5i32 {
            store
                .save(article(&format!("a{i}"), "item", i * 10), ctx.clone())
                .await
                .unwrap();
        }

        let result = store
            .filter(None, ArticleQuery::default(), ctx)
            .await
            .unwrap();
        let scores: Vec<i32> = result.items.iter().map(|a| a.score).collect();
        assert!(
            scores.windows(2).all(|w| w[0] <= w[1]),
            "items should be sorted ascending by score"
        );
    }

    /// `skip` deliberately not a multiple of `limit`, to check the offset is
    /// applied verbatim and reported back untouched.
    #[derive(Debug, Clone, Default, Serialize, Deserialize)]
    struct OffsetQuery;

    impl Query for OffsetQuery {
        fn pagination(&self) -> Option<Pagination> {
            Some(Pagination {
                skip: Some(3),
                limit: Some(2),
            })
        }
        fn sort(&self) -> Option<Vec<Sorter>> {
            Some(vec![Sorter {
                field: "score".into(),
                direction: crate::read::sorter::SortDirection::Asc,
            }])
        }
    }

    #[tokio::test]
    async fn filter_reports_the_exact_offset_window() {
        let store = setup_for::<OffsetQuery>().await;
        let ctx = CqrsContext::default();

        for i in 1..=6i32 {
            store
                .save(article(&format!("a{i}"), "item", i * 10), ctx.clone())
                .await
                .unwrap();
        }

        let result = store.filter(None, OffsetQuery, ctx).await.unwrap();

        assert_eq!(result.total, 6);
        assert_eq!(result.skip, 3);
        assert_eq!(result.limit, 2);
        // page/pageSize stay available but are only a derived approximation
        assert_eq!(result.page, 1);
        assert_eq!(result.page_size, 2);
        let scores: Vec<i32> = result.items.iter().map(|a| a.score).collect();
        assert_eq!(scores, vec![40, 50]);
    }

    // ── Sort field validation ────────────────────────────────────────────────

    /// A query whose sort is whatever the caller asked for — the untrusted path.
    #[derive(Debug, Clone, Default, Serialize, Deserialize)]
    struct SortedQuery(String);

    impl Query for SortedQuery {
        fn sort(&self) -> Option<Vec<Sorter>> {
            Some(vec![Sorter {
                field: self.0.clone(),
                direction: crate::read::sorter::SortDirection::Asc,
            }])
        }
    }

    /// The clause is shared (`read::sorter::order_by_clause`); what is specific here is
    /// that `DataPrefixMapper` runs *after* validation, so a dotted logical path stays
    /// legal while the mapped output would never pass the validator itself.
    #[test]
    fn the_data_prefix_mapper_is_applied_after_validation() {
        let sorters = vec![
            Sorter {
                field: "score".into(),
                direction: crate::read::sorter::SortDirection::Asc,
            },
            Sorter {
                field: "muscle.primary".into(),
                direction: crate::read::sorter::SortDirection::Desc,
            },
        ];
        assert_eq!(
            order_by_clause(Some(sorters), &DataPrefixMapper).unwrap(),
            " ORDER BY data.score ASC, data.muscle.primary DESC"
        );
    }

    /// A query asking for a later page with no sort declared.
    #[derive(Debug, Clone, Default, Serialize, Deserialize)]
    struct SecondPageQuery;

    impl Query for SecondPageQuery {
        fn pagination(&self) -> Option<Pagination> {
            Some(Pagination {
                skip: Some(2),
                limit: Some(2),
            })
        }
    }

    /// Pins the warning into SurrealDB's `filter`, end-to-end on the in-memory engine:
    /// delete the call in `surrealdb.rs` and this fails. The view name is its own,
    /// because the warning is once-per-view and the state is process-global.
    #[tokio::test]
    async fn filter_warns_when_paging_without_a_sort() {
        let store: SurrealDBStorage<Article, SecondPageQuery> =
            setup_named("surreal_unsorted_view").await;
        let ctx = CqrsContext::default();

        let events = events_of_async(async {
            store
                .filter(None, SecondPageQuery, ctx.clone())
                .await
                .expect("the query itself still succeeds — only the order is undefined");
        })
        .await;

        let ours = containing(&events, "no sort in effect");
        assert_eq!(ours.len(), 1, "exactly one warning, got {events:?}");
        assert!(ours[0].starts_with("WARN "), "{}", ours[0]);
        assert!(
            ours[0].contains("type_name=surreal_unsorted_view"),
            "{}",
            ours[0]
        );
        assert!(ours[0].contains("skip=2"), "{}", ours[0]);
    }

    /// End-to-end against the in-memory engine: the hostile field is rejected and no
    /// query is run, rather than being interpolated into the SurrealQL string.
    #[tokio::test]
    async fn filter_rejects_a_hostile_sort_field() {
        let store: SurrealDBStorage<Article, SortedQuery> = setup_for().await;
        let ctx = CqrsContext::default();
        store
            .save(article("a1", "Hello", 42), ctx.clone())
            .await
            .unwrap();

        let hostile = "1 UNION ALL SELECT data FROM secrets--";
        let err = store
            .filter(None, SortedQuery(hostile.to_string()), ctx.clone())
            .await
            .unwrap_err();
        assert_eq!(err.code, "GENERIC_VALIDATION_FAILED");
        assert!(err.message.contains(hostile));
    }

    #[tokio::test]
    async fn filter_still_accepts_a_legitimate_sort_field() {
        let store: SurrealDBStorage<Article, SortedQuery> = setup_for().await;
        let ctx = CqrsContext::default();
        for (id, score) in [("a1", 30), ("a2", 10), ("a3", 20)] {
            store
                .save(article(id, "item", score), ctx.clone())
                .await
                .unwrap();
        }

        let result = store
            .filter(None, SortedQuery("score".to_string()), ctx)
            .await
            .unwrap();
        let scores: Vec<i32> = result.items.iter().map(|a| a.score).collect();
        assert_eq!(scores, vec![10, 20, 30]);
    }
}