somnia-core 0.5.1

Type-safe SurrealDB query builder and expression tree — core of the somnia ORM.
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//! The expression tree used inside `WHERE`/`SET`/projection clauses.
//!
//! Values render to SurrealQL via the [`SurrealQL`] trait (literals) and the
//! [`DynExpr`] trait (composed expressions). The building blocks include typed
//! [`Column`] accessors, the untyped [`Ident`], the [`Raw`] escape hatch,
//! [`RecordLink`] (`type::record(...)`), [`Func`] calls, and comparison/logical
//! operators that combine with `.and()` / `.or()`.

use std::fmt;

use crate::types::SurrealRecord;

// ═══════════════════════════════════════════════════════════════════════════════
// DynExpr — type-erased expression (the internal transport)
// ═══════════════════════════════════════════════════════════════════════════════

/// A type-erased expression that can render itself into a SurrealQL buffer.
/// Implemented by every expression node; the common currency of the builder.
pub trait DynExpr: fmt::Debug + Send + Sync {
    /// Append this expression's SurrealQL to `buf`.
    fn render_dyn(&self, buf: &mut String);
}

/// A boxed, type-erased expression. Useful for returning a composed filter from
/// a helper function (e.g. a shared tenant/owner predicate).
pub type DynExprBox = Box<dyn DynExpr>;

impl DynExpr for Box<dyn DynExpr> {
    fn render_dyn(&self, buf: &mut String) {
        (**self).render_dyn(buf);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Expr — typed expression (public API)
// ═══════════════════════════════════════════════════════════════════════════════

/// A [`DynExpr`] that also reports a SurrealQL type hint. Auto-implemented for
/// every `DynExpr` (returning `"any"`); concrete nodes may override the hint.
pub trait Expr: DynExpr {
    /// A best-effort SurrealQL type name for this expression.
    fn ty_hint(&self) -> &'static str;
}

// Any DynExpr is automatically an Expr with a default ty_hint
// (used internally; concrete types override this)
impl<E: DynExpr> Expr for E {
    fn ty_hint(&self) -> &'static str {
        "any"
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SurrealQL — literal value rendering
// ═══════════════════════════════════════════════════════════════════════════════

/// A Rust type that can be rendered as a SurrealQL literal (the right-hand side of
/// comparisons, `SET` values, etc.). Implemented for the common scalar types,
/// `Option<T>`, `serde_json::Value`, the geometry types, and `Thing<T>`.
pub trait SurrealQL: fmt::Debug + Clone + Send + Sync + 'static {
    /// The SurrealQL type name (e.g. `"string"`, `"datetime"`).
    fn surreal_type() -> &'static str;
    /// Append the literal form of `value` to `buf` (with any needed quoting/escaping).
    fn render_literal(value: &Self, buf: &mut String);
}

impl SurrealQL for String {
    fn surreal_type() -> &'static str {
        "string"
    }
    fn render_literal(value: &Self, buf: &mut String) {
        let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
        buf.push('\'');
        buf.push_str(&escaped);
        buf.push('\'');
    }
}

impl SurrealQL for bool {
    fn surreal_type() -> &'static str {
        "bool"
    }
    fn render_literal(value: &Self, buf: &mut String) {
        buf.push_str(if *value { "true" } else { "false" });
    }
}

macro_rules! surreal_display {
    ($t:ty, $name:literal) => {
        impl SurrealQL for $t {
            fn surreal_type() -> &'static str {
                $name
            }
            fn render_literal(value: &Self, buf: &mut String) {
                use std::fmt::Write;
                let _ = write!(buf, "{value}");
            }
        }
    };
}
surreal_display!(i64, "int");
surreal_display!(i32, "int");
surreal_display!(i16, "int");
surreal_display!(i8, "int");
surreal_display!(f64, "float");
surreal_display!(f32, "float");
surreal_display!(u32, "int");
surreal_display!(u64, "int");
surreal_display!(u16, "int");
surreal_display!(u8, "int");

impl SurrealQL for chrono::DateTime<chrono::Utc> {
    fn surreal_type() -> &'static str {
        "datetime"
    }
    fn render_literal(value: &Self, buf: &mut String) {
        // SurrealDB 2.0+ requires the `d` prefix on datetime literals. A bare
        // quoted string is a `string`, not a `datetime`, so `created_at > '…'`
        // would compare against the wrong type; `created_at > d'…'` is correct.
        buf.push_str("d'");
        buf.push_str(&value.to_rfc3339());
        buf.push('\'');
    }
}

impl SurrealQL for uuid::Uuid {
    fn surreal_type() -> &'static str {
        "uuid"
    }
    fn render_literal(value: &Self, buf: &mut String) {
        use std::fmt::Write;
        // SurrealDB 2.0+ requires the `u` prefix on uuid literals; a bare quoted
        // string is a `string`, not a `uuid`.
        buf.push_str("u'");
        let _ = write!(buf, "{value}");
        buf.push('\'');
    }
}

impl SurrealQL for serde_json::Value {
    fn surreal_type() -> &'static str {
        "object"
    }
    fn render_literal(value: &Self, buf: &mut String) {
        // JSON is a syntactic subset of SurrealQL value literals (objects,
        // arrays, numbers, bools, null, double-quoted strings all parse), so
        // the serialized form is a valid inline literal.
        use std::fmt::Write;
        let _ = write!(buf, "{value}");
    }
}

// Geometry literals render as GeoJSON objects (a valid SurrealQL object literal),
// e.g. `{"type":"Point","coordinates":[1.0,2.0]}`.
macro_rules! geometry_surrealql {
    ($t:ident, $name:literal) => {
        impl SurrealQL for crate::types::$t {
            fn surreal_type() -> &'static str {
                $name
            }
            fn render_literal(value: &Self, buf: &mut String) {
                if let Ok(s) = serde_json::to_string(value) {
                    buf.push_str(&s);
                }
            }
        }
    };
}
geometry_surrealql!(Point, "geometry<point>");
geometry_surrealql!(LineString, "geometry<line>");
geometry_surrealql!(Polygon, "geometry<polygon>");

impl<T: SurrealQL> SurrealQL for Option<T> {
    fn surreal_type() -> &'static str {
        T::surreal_type()
    }
    fn render_literal(value: &Self, buf: &mut String) {
        match value {
            Some(v) => T::render_literal(v, buf),
            None => buf.push_str("NONE"),
        }
    }
}

impl<T: crate::types::SurrealRecord> SurrealQL for crate::types::Thing<T> {
    fn surreal_type() -> &'static str {
        "record"
    }
    fn render_literal(value: &Self, buf: &mut String) {
        buf.push_str(T::table_name());
        buf.push(':');
        value.key.render_id(buf);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Literal — wraps a SurrealQL value as an expression
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct Literal<V: SurrealQL>(pub V);

impl<V: SurrealQL> DynExpr for Literal<V> {
    fn render_dyn(&self, buf: &mut String) {
        V::render_literal(&self.0, buf);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Column — typed field reference (e.g., `asset.name`)
// ═══════════════════════════════════════════════════════════════════════════════

/// A typed reference to a record field — e.g. `Post::title()` yields a
/// `Column<Post, String>`. Generated by `#[derive(SurrealRecord)]` and used to
/// build type-checked filters (`.eq(...)`, `.gt(...)`, …) and projections.
pub struct Column<T: SurrealRecord, V: SurrealQL> {
    /// The database column name.
    pub name: &'static str,
    /// The SurrealQL type name for this column.
    pub surreal_type: &'static str,
    #[doc(hidden)]
    pub _marker: std::marker::PhantomData<(T, V)>,
}

impl<T: SurrealRecord, V: SurrealQL> std::fmt::Debug for Column<T, V> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Column").field("name", &self.name).finish()
    }
}

impl<T: SurrealRecord, V: SurrealQL> Clone for Column<T, V> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T: SurrealRecord, V: SurrealQL> Copy for Column<T, V> {}

impl<T: SurrealRecord, V: SurrealQL> DynExpr for Column<T, V> {
    fn render_dyn(&self, buf: &mut String) {
        buf.push_str(self.name);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Ident — an untyped column/field reference usable in WHERE clauses
// ═══════════════════════════════════════════════════════════════════════════════

/// An untyped identifier (column or field path) for building filter expressions
/// where a typed [`Column`] accessor is unavailable (e.g. record-link fields the
/// derive doesn't expose, or `tenant.slug` paths). Mirrors `Column`'s operators.
#[derive(Debug, Clone, Copy)]
pub struct Ident(pub &'static str);

/// Construct an [`Ident`] for a field name.
pub fn ident(name: &'static str) -> Ident {
    Ident(name)
}

impl Ident {
    fn dyn_box(&self) -> Box<dyn DynExpr> {
        Box::new(Raw(self.0.to_string()))
    }

    pub fn eq<V: SurrealQL>(&self, v: V) -> EqExpr {
        EqExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(v)),
        }
    }
    pub fn ne<V: SurrealQL>(&self, v: V) -> NeExpr {
        NeExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(v)),
        }
    }
    pub fn gt<V: SurrealQL>(&self, v: V) -> GtExpr {
        GtExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(v)),
        }
    }
    pub fn lt<V: SurrealQL>(&self, v: V) -> LtExpr {
        LtExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(v)),
        }
    }
    pub fn gte<V: SurrealQL>(&self, v: V) -> GteExpr {
        GteExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(v)),
        }
    }
    pub fn lte<V: SurrealQL>(&self, v: V) -> LteExpr {
        LteExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(v)),
        }
    }
    pub fn contains<V: SurrealQL>(&self, v: V) -> ContainsExpr {
        ContainsExpr {
            haystack: self.dyn_box(),
            needle: Box::new(Literal(v)),
        }
    }
    /// Compare to an arbitrary expression — e.g. `asset = type::record('asset', …)`.
    pub fn eq_expr(&self, rhs: impl DynExpr + 'static) -> EqExpr {
        EqExpr {
            left: self.dyn_box(),
            right: Box::new(rhs),
        }
    }
    pub fn ne_expr(&self, rhs: impl DynExpr + 'static) -> NeExpr {
        NeExpr {
            left: self.dyn_box(),
            right: Box::new(rhs),
        }
    }
    /// `field IS NONE`.
    pub fn is_none(&self) -> Raw {
        Raw(format!("{} IS NONE", self.0))
    }
}

impl DynExpr for Ident {
    fn render_dyn(&self, buf: &mut String) {
        buf.push_str(self.0);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Raw — verbatim SurrealQL escape hatch (lambdas, IF/THEN/ELSE, field paths…)
// ═══════════════════════════════════════════════════════════════════════════════

/// A verbatim SurrealQL fragment. Use for expressions somnia does not model as
/// typed nodes (e.g. `IF x != NONE THEN … END`, lambdas, `tenant.slug`).
#[derive(Debug, Clone)]
pub struct Raw(pub String);

impl Raw {
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }
}

impl DynExpr for Raw {
    fn render_dyn(&self, buf: &mut String) {
        buf.push_str(&self.0);
    }
}

/// SurrealDB's `NONE`.
#[derive(Debug, Clone)]
pub struct NoneLit;
impl DynExpr for NoneLit {
    fn render_dyn(&self, buf: &mut String) {
        buf.push_str("NONE");
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RecordLink — `type::record('table', <key>)`
// ═══════════════════════════════════════════════════════════════════════════════

/// Builds a SurrealDB record link `type::record('table', <key>)`. The key is any
/// literal value (typically the bare UUID/string id of the related row).
#[derive(Debug)]
pub struct RecordLink {
    table: &'static str,
    key: Box<dyn DynExpr>,
}

impl RecordLink {
    /// `type::record('table', '<key literal>')`.
    pub fn new<V: SurrealQL>(table: &'static str, key: V) -> Self {
        Self {
            table,
            key: Box::new(Literal(key)),
        }
    }
    /// `type::record('table', <key expr>)` — key rendered from an arbitrary expr.
    pub fn from_expr(table: &'static str, key: impl DynExpr + 'static) -> Self {
        Self {
            table,
            key: Box::new(key),
        }
    }
}

impl DynExpr for RecordLink {
    fn render_dyn(&self, buf: &mut String) {
        buf.push_str("type::record('");
        buf.push_str(self.table);
        buf.push_str("', ");
        self.key.render_dyn(buf);
        buf.push(')');
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Path — graph traversal (`->edge->table`, `<-edge<-table`, `<->edge<->table`)
// ═══════════════════════════════════════════════════════════════════════════════

/// Direction of a single graph hop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Dir {
    /// outgoing edge — `->`
    Out,
    /// incoming edge — `<-`
    In,
    /// either direction — `<->`
    Both,
}

impl Dir {
    fn arrow(self) -> &'static str {
        match self {
            Dir::Out => "->",
            Dir::In => "<-",
            Dir::Both => "<->",
        }
    }
}

/// One hop in a graph [`Path`]: a direction, an edge table, an optional
/// destination table, and an optional `WHERE` filter on the edge.
#[derive(Debug)]
struct Step {
    dir: Dir,
    edge: &'static str,
    dest: Option<&'static str>,
    filter: Option<Box<dyn DynExpr>>,
}

impl Step {
    fn render(&self, buf: &mut String) {
        buf.push_str(self.dir.arrow());
        match &self.filter {
            // `->(edge WHERE <expr>)`
            Some(f) => {
                buf.push('(');
                buf.push_str(self.edge);
                buf.push_str(" WHERE ");
                f.render_dyn(buf);
                buf.push(')');
            }
            None => buf.push_str(self.edge),
        }
        if let Some(dest) = self.dest {
            buf.push_str(self.dir.arrow());
            buf.push_str(dest);
        }
    }
}

/// The trailing field accessor on a [`Path`] — `.field` or `.*`.
#[derive(Debug)]
enum Tail {
    Field(String),
    All,
}

/// A graph-traversal expression — e.g. `->wrote->post`, `<-wrote<-user`, or a
/// multi-hop chain with an optional `.field`/`.*` accessor at the end.
///
/// A `Path` is a [`DynExpr`], so it works anywhere the builder takes an
/// expression: as a `SELECT` projection (`Projection::aliased(path, "posts")`),
/// inside a `WHERE` filter, or as a `SET` value. With no start it is relative to
/// the statement's `FROM` table; [`Path::from_record`] anchors it to a record.
///
/// ```ignore
/// // ->wrote->post.title AS titles
/// let p = Path::out::<Wrote>().to::<Post>().field("title");
/// Post::table().project(vec![Projection::aliased(p, "titles")]);
/// ```
#[derive(Debug)]
pub struct Path {
    start: Option<Box<dyn DynExpr>>,
    steps: Vec<Step>,
    tail: Option<Tail>,
}

impl Path {
    fn from_step(dir: Dir, edge: &'static str) -> Self {
        Self {
            start: None,
            steps: vec![Step {
                dir,
                edge,
                dest: None,
                filter: None,
            }],
            tail: None,
        }
    }

    /// Start an outgoing hop over edge `E` — `->edge`.
    pub fn out<E: crate::types::SurrealEdge>() -> Self {
        Self::from_step(Dir::Out, E::edge_name())
    }
    /// Start an incoming hop over edge `E` — `<-edge`.
    pub fn inn<E: crate::types::SurrealEdge>() -> Self {
        Self::from_step(Dir::In, E::edge_name())
    }
    /// Start a bidirectional hop over edge `E` — `<->edge`.
    pub fn both<E: crate::types::SurrealEdge>() -> Self {
        Self::from_step(Dir::Both, E::edge_name())
    }

    /// Start an outgoing hop over a raw edge name — `->edge`.
    pub fn out_edge(edge: &'static str) -> Self {
        Self::from_step(Dir::Out, edge)
    }
    /// Start an incoming hop over a raw edge name — `<-edge`.
    pub fn in_edge(edge: &'static str) -> Self {
        Self::from_step(Dir::In, edge)
    }
    /// Start a bidirectional hop over a raw edge name — `<->edge`.
    pub fn both_edge(edge: &'static str) -> Self {
        Self::from_step(Dir::Both, edge)
    }

    /// Anchor an existing path to a starting record literal — `<record><path>`
    /// (e.g. `user:tobie->wrote->post`). Pass a [`Thing`](crate::types::Thing).
    pub fn from_record<V: SurrealQL>(mut self, start: V) -> Self {
        self.start = Some(Box::new(Literal(start)));
        self
    }

    /// Anchor an existing path to a starting expression — e.g. a
    /// [`RecordLink`] (`type::record('user', $id)->wrote->post`).
    pub fn from_expr(mut self, start: impl DynExpr + 'static) -> Self {
        self.start = Some(Box::new(start));
        self
    }

    fn last_mut(&mut self) -> &mut Step {
        self.steps.last_mut().expect("path always has ≥1 step")
    }

    /// Constrain the destination of the most recent hop to table `T` — `->edge->table`.
    pub fn to<T: SurrealRecord>(mut self) -> Self {
        self.last_mut().dest = Some(T::table_name());
        self
    }
    /// Constrain the destination of the most recent hop to a raw table name.
    pub fn to_table(mut self, table: &'static str) -> Self {
        self.last_mut().dest = Some(table);
        self
    }

    /// Filter the most recent hop's edge — `->(edge WHERE <expr>)`.
    pub fn where_(mut self, expr: impl DynExpr + 'static) -> Self {
        self.last_mut().filter = Some(Box::new(expr));
        self
    }

    /// Chain another outgoing hop over edge `E`.
    pub fn then_out<E: crate::types::SurrealEdge>(self) -> Self {
        self.push_step(Dir::Out, E::edge_name())
    }
    /// Chain another incoming hop over edge `E`.
    pub fn then_in<E: crate::types::SurrealEdge>(self) -> Self {
        self.push_step(Dir::In, E::edge_name())
    }
    /// Chain another bidirectional hop over edge `E`.
    pub fn then_both<E: crate::types::SurrealEdge>(self) -> Self {
        self.push_step(Dir::Both, E::edge_name())
    }
    /// Chain another hop over a raw edge name, outgoing.
    pub fn then_out_edge(self, edge: &'static str) -> Self {
        self.push_step(Dir::Out, edge)
    }
    /// Chain another hop over a raw edge name, incoming.
    pub fn then_in_edge(self, edge: &'static str) -> Self {
        self.push_step(Dir::In, edge)
    }

    fn push_step(mut self, dir: Dir, edge: &'static str) -> Self {
        self.steps.push(Step {
            dir,
            edge,
            dest: None,
            filter: None,
        });
        self
    }

    /// Append a field accessor — `<path>.field`.
    pub fn field(mut self, name: impl Into<String>) -> Self {
        self.tail = Some(Tail::Field(name.into()));
        self
    }
    /// Append the all-fields accessor — `<path>.*`.
    pub fn all(mut self) -> Self {
        self.tail = Some(Tail::All);
        self
    }

    /// `<path> CONTAINS <value>` — e.g. membership test over a traversed list.
    pub fn contains<V: SurrealQL>(self, value: V) -> ContainsExpr {
        ContainsExpr {
            haystack: Box::new(self),
            needle: Box::new(Literal(value)),
        }
    }
    /// `<path> = <expr>`.
    pub fn eq_expr(self, rhs: impl DynExpr + 'static) -> EqExpr {
        EqExpr {
            left: Box::new(self),
            right: Box::new(rhs),
        }
    }
}

impl DynExpr for Path {
    fn render_dyn(&self, buf: &mut String) {
        if let Some(start) = &self.start {
            start.render_dyn(buf);
        }
        for step in &self.steps {
            step.render(buf);
        }
        match &self.tail {
            Some(Tail::Field(f)) => {
                buf.push('.');
                buf.push_str(f);
            }
            Some(Tail::All) => buf.push_str(".*"),
            None => {}
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Func — `name(arg, arg, …)` (record::id, type::string, string::lowercase, …)
// ═══════════════════════════════════════════════════════════════════════════════

/// A SurrealQL function call `name(args…)`.
#[derive(Debug)]
pub struct Func {
    name: &'static str,
    args: Vec<Box<dyn DynExpr>>,
}

impl Func {
    pub fn new(name: &'static str, args: Vec<Box<dyn DynExpr>>) -> Self {
        Self { name, args }
    }
    /// Single-argument function over a bare column/identifier, e.g.
    /// `record::id(id)` → `Func::of("record::id", "id")`.
    pub fn of(name: &'static str, ident: &'static str) -> Self {
        Self {
            name,
            args: vec![Box::new(Raw(ident.to_string()))],
        }
    }
}

impl DynExpr for Func {
    fn render_dyn(&self, buf: &mut String) {
        buf.push_str(self.name);
        buf.push('(');
        for (i, a) in self.args.iter().enumerate() {
            if i > 0 {
                buf.push_str(", ");
            }
            a.render_dyn(buf);
        }
        buf.push(')');
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Binary expression nodes
// ═══════════════════════════════════════════════════════════════════════════════

macro_rules! binop {
    ($name:ident, $op:literal) => {
        #[derive(Debug)]
        pub struct $name {
            pub(crate) left: Box<dyn DynExpr>,
            pub(crate) right: Box<dyn DynExpr>,
        }
        impl DynExpr for $name {
            fn render_dyn(&self, buf: &mut String) {
                self.left.render_dyn(buf);
                buf.push(' ');
                buf.push_str($op);
                buf.push(' ');
                self.right.render_dyn(buf);
            }
        }
    };
}

binop!(EqExpr, "=");
binop!(NeExpr, "!=");
binop!(GtExpr, ">");
binop!(LtExpr, "<");
binop!(GteExpr, ">=");
binop!(LteExpr, "<=");
binop!(AndExpr, "AND");
binop!(OrExpr, "OR");

#[derive(Debug)]
pub struct NotExpr {
    pub(crate) inner: Box<dyn DynExpr>,
}

impl DynExpr for NotExpr {
    fn render_dyn(&self, buf: &mut String) {
        buf.push_str("NOT ");
        self.inner.render_dyn(buf);
    }
}

#[derive(Debug)]
pub struct ContainsExpr {
    pub(crate) haystack: Box<dyn DynExpr>,
    pub(crate) needle: Box<dyn DynExpr>,
}

impl DynExpr for ContainsExpr {
    fn render_dyn(&self, buf: &mut String) {
        self.haystack.render_dyn(buf);
        buf.push_str(" CONTAINS ");
        self.needle.render_dyn(buf);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Column operator methods (Diesel-style: asset.name.eq("foo"))
// ═══════════════════════════════════════════════════════════════════════════════

impl<T: SurrealRecord, V: SurrealQL> Column<T, V> {
    pub fn eq(&self, value: V) -> EqExpr {
        EqExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(value)),
        }
    }
    pub fn ne(&self, value: V) -> NeExpr {
        NeExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(value)),
        }
    }
    pub fn gt(&self, value: V) -> GtExpr {
        GtExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(value)),
        }
    }
    pub fn lt(&self, value: V) -> LtExpr {
        LtExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(value)),
        }
    }
    pub fn gte(&self, value: V) -> GteExpr {
        GteExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(value)),
        }
    }
    pub fn lte(&self, value: V) -> LteExpr {
        LteExpr {
            left: self.dyn_box(),
            right: Box::new(Literal(value)),
        }
    }
    pub fn contains(&self, value: V) -> ContainsExpr {
        ContainsExpr {
            haystack: self.dyn_box(),
            needle: Box::new(Literal(value)),
        }
    }

    /// Compare this column to an arbitrary expression — e.g. a [`RecordLink`]
    /// (`asset = type::record('asset', …)`) or [`NoneLit`] (`tenant = NONE`).
    pub fn eq_expr(&self, rhs: impl DynExpr + 'static) -> EqExpr {
        EqExpr {
            left: self.dyn_box(),
            right: Box::new(rhs),
        }
    }
    pub fn ne_expr(&self, rhs: impl DynExpr + 'static) -> NeExpr {
        NeExpr {
            left: self.dyn_box(),
            right: Box::new(rhs),
        }
    }
    /// `column IS NONE`.
    pub fn is_none(&self) -> Raw {
        Raw(format!("{} IS NONE", self.name))
    }

    fn dyn_box(&self) -> Box<dyn DynExpr> {
        Box::new(Self {
            name: self.name,
            surreal_type: self.surreal_type,
            _marker: self._marker,
        })
    }
}

// Combinators: (a = 1).and(b = 2).or(c = 3). Available on every expression node.
macro_rules! combinators {
    ($($t:ty),* $(,)?) => {$(
        impl $t {
            pub fn and(self, other: impl DynExpr + 'static) -> AndExpr {
                AndExpr { left: Box::new(self), right: Box::new(other) }
            }
            pub fn or(self, other: impl DynExpr + 'static) -> OrExpr {
                OrExpr { left: Box::new(self), right: Box::new(other) }
            }
        }
    )*};
}
combinators!(
    EqExpr,
    NeExpr,
    GtExpr,
    LtExpr,
    GteExpr,
    LteExpr,
    AndExpr,
    OrExpr,
    ContainsExpr,
    NotExpr,
    Raw
);

/// Wraps an expression in parentheses: `(<expr>)`. Use to force grouping/precedence.
#[derive(Debug)]
pub struct Grouped(pub Box<dyn DynExpr>);

impl Grouped {
    pub fn new(inner: impl DynExpr + 'static) -> Self {
        Self(Box::new(inner))
    }
}

impl DynExpr for Grouped {
    fn render_dyn(&self, buf: &mut String) {
        buf.push('(');
        self.0.render_dyn(buf);
        buf.push(')');
    }
}

combinators!(Grouped, Func, Path);

// ═══════════════════════════════════════════════════════════════════════════════
// Projection — a SELECT field, optionally `<expr> AS alias`
// ═══════════════════════════════════════════════════════════════════════════════

/// A single SELECT-list entry. Either a bare expression or `<expr> AS <alias>`.
#[derive(Debug)]
pub struct Projection {
    expr: Box<dyn DynExpr>,
    alias: Option<&'static str>,
}

impl Projection {
    /// A bare field/expression with no alias.
    pub fn new(expr: impl DynExpr + 'static) -> Self {
        Self {
            expr: Box::new(expr),
            alias: None,
        }
    }
    /// `<expr> AS <alias>`.
    pub fn aliased(expr: impl DynExpr + 'static, alias: &'static str) -> Self {
        Self {
            expr: Box::new(expr),
            alias: Some(alias),
        }
    }
    pub fn render(&self, buf: &mut String) {
        self.expr.render_dyn(buf);
        if let Some(a) = self.alias {
            buf.push_str(" AS ");
            buf.push_str(a);
        }
    }
}

/// A bare column name as a projection: `name`.
pub fn col(name: &'static str) -> Projection {
    Projection::new(Raw(name.to_string()))
}

/// `<raw> AS <alias>` — verbatim expression with an alias.
pub fn field(raw: &'static str, alias: &'static str) -> Projection {
    Projection::aliased(Raw(raw.to_string()), alias)
}

// ═══════════════════════════════════════════════════════════════════════════════
// ColumnSet — `*` selector generated by derive macro
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct ColumnMeta {
    pub name: &'static str,
    pub surreal_type: &'static str,
}

/// Select-all (`*`) column list. Generated by `#[derive(SurrealRecord)]`.
pub struct ColumnSet<T: SurrealRecord> {
    pub cols: &'static [ColumnMeta],
    pub _marker: std::marker::PhantomData<T>,
}

impl<T: SurrealRecord> std::fmt::Debug for ColumnSet<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ColumnSet")
            .field("cols", &self.cols)
            .finish()
    }
}

impl<T: SurrealRecord> DynExpr for ColumnSet<T> {
    fn render_dyn(&self, buf: &mut String) {
        buf.push('*');
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ORDER BY
// ═══════════════════════════════════════════════════════════════════════════════

/// Sort direction for `ORDER BY`.
#[derive(Debug, Clone, Copy)]
pub enum Order {
    /// Ascending (`ASC`).
    Asc,
    /// Descending (`DESC`).
    Desc,
}

impl Order {
    pub fn render_suffix(&self) -> &'static str {
        match self {
            Order::Asc => "ASC",
            Order::Desc => "DESC",
        }
    }
}

impl std::fmt::Display for Order {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.render_suffix())
    }
}