type-bridge-orm 1.5.2

Async ORM for TypeDB built on type-bridge-core-lib
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
//! Type-safe field references for building query expressions.
//!
//! [`FieldRef`] provides typed accessors for building [`Expr`] filters
//! and sort specifications without string-based attribute names.
//!
//! # Example
//!
//! ```text
//! // Instead of stringly-typed:
//! Expr::gte("age", AttributeValue::Long(18))
//!
//! // Use type-safe field references:
//! Person::fields().age.gte(Age(18))
//! ```

use std::marker::PhantomData;

use crate::attribute::TypeBridgeAttribute;
use crate::expr::{Agg, Expr, SortDir};

/// A typed reference to an entity/relation attribute field.
///
/// Generated by derive macros as part of `XxxFields` structs.
/// Provides type-safe expression builders that accept the concrete
/// attribute type rather than raw `AttributeValue`.
pub struct FieldRef<A: TypeBridgeAttribute> {
    attr_name: &'static str,
    _marker: PhantomData<A>,
}

impl<A: TypeBridgeAttribute> FieldRef<A> {
    /// Create a new field reference for the given attribute name.
    pub const fn new(attr_name: &'static str) -> Self {
        Self {
            attr_name,
            _marker: PhantomData,
        }
    }

    /// The TypeDB attribute name this field refers to.
    pub const fn attr_name(&self) -> &'static str {
        self.attr_name
    }

    // -- Comparison expressions --

    /// Equality: `attr == value`.
    pub fn eq(&self, value: A) -> Expr {
        Expr::Eq {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        }
    }

    /// Not equal: `attr != value`.
    pub fn neq(&self, value: A) -> Expr {
        Expr::Neq {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        }
    }

    /// Greater than: `attr > value`.
    pub fn gt(&self, value: A) -> Expr {
        Expr::Gt {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        }
    }

    /// Greater than or equal: `attr >= value`.
    pub fn gte(&self, value: A) -> Expr {
        Expr::Gte {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        }
    }

    /// Less than: `attr < value`.
    pub fn lt(&self, value: A) -> Expr {
        Expr::Lt {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        }
    }

    /// Less than or equal: `attr <= value`.
    pub fn lte(&self, value: A) -> Expr {
        Expr::Lte {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        }
    }

    // -- String expressions --

    /// String contains: `attr contains substring`.
    pub fn contains(&self, substring: impl Into<String>) -> Expr {
        Expr::Contains {
            attr: self.attr_name.to_string(),
            substring: substring.into(),
        }
    }

    /// String like (regex): `attr like pattern`.
    pub fn like(&self, pattern: impl Into<String>) -> Expr {
        Expr::Like {
            attr: self.attr_name.to_string(),
            pattern: pattern.into(),
        }
    }

    // -- Sort specifications --

    /// Sort ascending by this field.
    pub fn asc(&self) -> (String, SortDir) {
        (self.attr_name.to_string(), SortDir::Asc)
    }

    /// Sort descending by this field.
    pub fn desc(&self) -> (String, SortDir) {
        (self.attr_name.to_string(), SortDir::Desc)
    }

    // -- Aggregation helpers --

    /// Sum this field's values.
    pub fn sum(&self) -> Agg {
        Agg::Sum(self.attr_name.to_string())
    }

    /// Minimum of this field's values.
    pub fn min(&self) -> Agg {
        Agg::Min(self.attr_name.to_string())
    }

    /// Maximum of this field's values.
    pub fn max(&self) -> Agg {
        Agg::Max(self.attr_name.to_string())
    }

    /// Arithmetic mean of this field's values.
    pub fn mean(&self) -> Agg {
        Agg::Mean(self.attr_name.to_string())
    }

    /// Median of this field's values.
    pub fn median(&self) -> Agg {
        Agg::Median(self.attr_name.to_string())
    }

    // -- Range & string convenience methods --

    /// Range filter: `attr >= low AND attr <= high`.
    pub fn in_range(&self, low: A, high: A) -> Expr {
        Expr::And(vec![self.gte(low), self.lte(high)])
    }

    /// String starts-with: `attr like "^prefix.*"`.
    pub fn startswith(&self, prefix: impl Into<String>) -> Expr {
        Expr::startswith(self.attr_name, prefix)
    }

    /// String ends-with: `attr like ".*suffix$"`.
    pub fn endswith(&self, suffix: impl Into<String>) -> Expr {
        Expr::endswith(self.attr_name, suffix)
    }
}

// ---------------------------------------------------------------------------
// Role player field reference
// ---------------------------------------------------------------------------

/// A typed reference to an attribute on a role player entity.
///
/// Methods return [`Expr::RolePlayer`] wrapping the inner comparison,
/// ensuring the filter targets the role player variable.
///
/// # Example
///
/// ```ignore
/// Employment::fields().employee.attr::<Age>("age").gte(Age(30))
/// ```
pub struct RolePlayerFieldRef<A: TypeBridgeAttribute> {
    role_name: &'static str,
    attr_name: &'static str,
    _marker: PhantomData<A>,
}

impl<A: TypeBridgeAttribute> RolePlayerFieldRef<A> {
    /// Create a new role player field reference.
    pub const fn new(role_name: &'static str, attr_name: &'static str) -> Self {
        Self {
            role_name,
            attr_name,
            _marker: PhantomData,
        }
    }

    fn wrap(&self, inner: Expr) -> Expr {
        Expr::RolePlayer {
            role: self.role_name.to_string(),
            inner: Box::new(inner),
        }
    }

    /// Equality: `role_player.attr == value`.
    pub fn eq(&self, value: A) -> Expr {
        self.wrap(Expr::Eq {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        })
    }

    /// Not equal: `role_player.attr != value`.
    pub fn neq(&self, value: A) -> Expr {
        self.wrap(Expr::Neq {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        })
    }

    /// Greater than: `role_player.attr > value`.
    pub fn gt(&self, value: A) -> Expr {
        self.wrap(Expr::Gt {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        })
    }

    /// Greater than or equal: `role_player.attr >= value`.
    pub fn gte(&self, value: A) -> Expr {
        self.wrap(Expr::Gte {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        })
    }

    /// Less than: `role_player.attr < value`.
    pub fn lt(&self, value: A) -> Expr {
        self.wrap(Expr::Lt {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        })
    }

    /// Less than or equal: `role_player.attr <= value`.
    pub fn lte(&self, value: A) -> Expr {
        self.wrap(Expr::Lte {
            attr: self.attr_name.to_string(),
            value: value.to_value(),
        })
    }

    /// String contains: `role_player.attr contains substring`.
    pub fn contains(&self, substring: impl Into<String>) -> Expr {
        self.wrap(Expr::Contains {
            attr: self.attr_name.to_string(),
            substring: substring.into(),
        })
    }

    /// String like (regex): `role_player.attr like pattern`.
    pub fn like(&self, pattern: impl Into<String>) -> Expr {
        self.wrap(Expr::Like {
            attr: self.attr_name.to_string(),
            pattern: pattern.into(),
        })
    }

    /// Range filter: `role_player.attr >= low AND role_player.attr <= high`.
    pub fn in_range(&self, low: A, high: A) -> Expr {
        self.wrap(Expr::And(vec![
            Expr::Gte {
                attr: self.attr_name.to_string(),
                value: low.to_value(),
            },
            Expr::Lte {
                attr: self.attr_name.to_string(),
                value: high.to_value(),
            },
        ]))
    }

    /// String starts-with: `role_player.attr like "^prefix.*"`.
    pub fn startswith(&self, prefix: impl Into<String>) -> Expr {
        self.wrap(Expr::startswith(self.attr_name, prefix))
    }

    /// String ends-with: `role_player.attr like ".*suffix$"`.
    pub fn endswith(&self, suffix: impl Into<String>) -> Expr {
        self.wrap(Expr::endswith(self.attr_name, suffix))
    }
}

// ---------------------------------------------------------------------------
// Role reference
// ---------------------------------------------------------------------------

/// A reference to a role in a relation.
///
/// Provides access to role player attributes for building filter expressions.
///
/// # Example
///
/// ```ignore
/// // Access a role player's attribute:
/// Employment::fields().employee.attr::<Age>("age").gte(Age(30))
/// ```
pub struct RoleRef {
    role_name: &'static str,
}

impl RoleRef {
    /// Create a new role reference.
    pub const fn new(role_name: &'static str) -> Self {
        Self { role_name }
    }

    /// Get a typed field reference for a role player's attribute.
    pub fn attr<A: TypeBridgeAttribute>(&self, attr_name: &'static str) -> RolePlayerFieldRef<A> {
        RolePlayerFieldRef::new(self.role_name, attr_name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::define_attribute;

    define_attribute!(TestName, "name", "string");
    define_attribute!(TestAge, "age", "long");

    #[test]
    fn field_ref_eq() {
        let field: FieldRef<TestAge> = FieldRef::new("age");
        let expr = field.eq(TestAge(30));
        match expr {
            Expr::Eq { attr, value } => {
                assert_eq!(attr, "age");
                assert_eq!(value, crate::value::AttributeValue::Long(30));
            }
            _ => panic!("expected Eq"),
        }
    }

    #[test]
    fn field_ref_comparisons() {
        let field: FieldRef<TestAge> = FieldRef::new("age");
        assert!(matches!(field.gt(TestAge(1)), Expr::Gt { .. }));
        assert!(matches!(field.lt(TestAge(1)), Expr::Lt { .. }));
        assert!(matches!(field.gte(TestAge(1)), Expr::Gte { .. }));
        assert!(matches!(field.lte(TestAge(1)), Expr::Lte { .. }));
        assert!(matches!(field.neq(TestAge(1)), Expr::Neq { .. }));
    }

    #[test]
    fn field_ref_string_ops() {
        let field: FieldRef<TestName> = FieldRef::new("name");
        assert!(matches!(field.contains("Ali"), Expr::Contains { .. }));
        assert!(matches!(field.like("^A.*"), Expr::Like { .. }));
    }

    #[test]
    fn field_ref_sort() {
        let field: FieldRef<TestAge> = FieldRef::new("age");
        let (attr, dir) = field.asc();
        assert_eq!(attr, "age");
        assert_eq!(dir, SortDir::Asc);
        let (_, dir) = field.desc();
        assert_eq!(dir, SortDir::Desc);
    }

    #[test]
    fn field_ref_in_range() {
        let field: FieldRef<TestAge> = FieldRef::new("age");
        let expr = field.in_range(TestAge(20), TestAge(30));
        match expr {
            Expr::And(children) => {
                assert_eq!(children.len(), 2);
                assert!(matches!(&children[0], Expr::Gte { attr, .. } if attr == "age"));
                assert!(matches!(&children[1], Expr::Lte { attr, .. } if attr == "age"));
            }
            _ => panic!("expected And"),
        }
    }

    #[test]
    fn field_ref_startswith() {
        let field: FieldRef<TestName> = FieldRef::new("name");
        let expr = field.startswith("Ali");
        match expr {
            Expr::Like { attr, pattern } => {
                assert_eq!(attr, "name");
                assert_eq!(pattern, "^Ali.*");
            }
            _ => panic!("expected Like"),
        }
    }

    #[test]
    fn field_ref_endswith() {
        let field: FieldRef<TestName> = FieldRef::new("name");
        let expr = field.endswith("ice");
        match expr {
            Expr::Like { attr, pattern } => {
                assert_eq!(attr, "name");
                assert_eq!(pattern, ".*ice$");
            }
            _ => panic!("expected Like"),
        }
    }

    #[test]
    fn role_player_field_ref_eq() {
        let rpf: RolePlayerFieldRef<TestAge> = RolePlayerFieldRef::new("employee", "age");
        let expr = rpf.eq(TestAge(30));
        match expr {
            Expr::RolePlayer { role, inner } => {
                assert_eq!(role, "employee");
                assert!(matches!(*inner, Expr::Eq { ref attr, .. } if attr == "age"));
            }
            _ => panic!("expected RolePlayer"),
        }
    }

    #[test]
    fn role_player_field_ref_comparisons() {
        let rpf: RolePlayerFieldRef<TestAge> = RolePlayerFieldRef::new("employee", "age");
        assert!(matches!(rpf.gt(TestAge(1)), Expr::RolePlayer { .. }));
        assert!(matches!(rpf.lt(TestAge(1)), Expr::RolePlayer { .. }));
        assert!(matches!(rpf.gte(TestAge(1)), Expr::RolePlayer { .. }));
        assert!(matches!(rpf.lte(TestAge(1)), Expr::RolePlayer { .. }));
        assert!(matches!(rpf.neq(TestAge(1)), Expr::RolePlayer { .. }));
    }

    #[test]
    fn role_player_field_ref_in_range() {
        let rpf: RolePlayerFieldRef<TestAge> = RolePlayerFieldRef::new("employee", "age");
        let expr = rpf.in_range(TestAge(20), TestAge(30));
        match expr {
            Expr::RolePlayer { role, inner } => {
                assert_eq!(role, "employee");
                assert!(matches!(*inner, Expr::And(_)));
            }
            _ => panic!("expected RolePlayer"),
        }
    }

    #[test]
    fn role_ref_attr() {
        let role = RoleRef::new("employee");
        let field: RolePlayerFieldRef<TestAge> = role.attr("age");
        let expr = field.gte(TestAge(18));
        match expr {
            Expr::RolePlayer { role, inner } => {
                assert_eq!(role, "employee");
                assert!(matches!(*inner, Expr::Gte { ref attr, .. } if attr == "age"));
            }
            _ => panic!("expected RolePlayer"),
        }
    }

    #[test]
    fn field_ref_aggregations() {
        let field: FieldRef<TestAge> = FieldRef::new("age");
        assert!(matches!(field.sum(), Agg::Sum(ref a) if a == "age"));
        assert!(matches!(field.min(), Agg::Min(ref a) if a == "age"));
        assert!(matches!(field.max(), Agg::Max(ref a) if a == "age"));
        assert!(matches!(field.mean(), Agg::Mean(ref a) if a == "age"));
        assert!(matches!(field.median(), Agg::Median(ref a) if a == "age"));
    }
}