fathomdb-query 0.5.3

Query AST, builder, and SQL compiler for the fathomdb agent datastore
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
use crate::{
    ComparisonOp, CompileError, CompiledGroupedQuery, CompiledQuery, EdgeExpansionSlot,
    ExpansionSlot, Predicate, QueryAst, QueryStep, ScalarValue, TextQuery, TraverseDirection,
    compile_grouped_query, compile_query,
};

/// Errors raised by tethered search builders when a caller opts into a
/// fused filter variant whose preconditions are not satisfied.
///
/// These errors are surfaced at filter-add time (before any SQL runs)
/// so developers who register a property-FTS schema for the kind see the
/// fused method succeed, while callers who forgot to register a schema
/// get a precise, actionable error instead of silent post-filter
/// degradation. See the Memex near-term roadmap item 7 and
/// `.claude/memory/project_fused_json_filters_contract.md` for the full
/// contract.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum BuilderValidationError {
    /// The caller invoked a `filter_json_fused_*` method on a tethered
    /// builder that has no registered property-FTS schema for the kind
    /// it targets.
    #[error(
        "kind {kind:?} has no registered property-FTS schema; register one with admin.register_fts_property_schema(..) before using filter_json_fused_* methods, or use the post-filter filter_json_* family for non-fused semantics"
    )]
    MissingPropertyFtsSchema {
        /// Node kind the builder was targeting.
        kind: String,
    },
    /// The caller invoked a `filter_json_fused_*` method with a path
    /// that is not covered by the registered property-FTS schema for the
    /// kind.
    #[error(
        "kind {kind:?} has a registered property-FTS schema but path {path:?} is not in its include list; add the path to the schema or use the post-filter filter_json_* family"
    )]
    PathNotIndexed {
        /// Node kind the builder was targeting.
        kind: String,
        /// Path the caller attempted to filter on.
        path: String,
    },
    /// The caller invoked a `filter_json_fused_*` method on a tethered
    /// builder that has not been bound to a specific kind (for example,
    /// `FallbackSearchBuilder` without a preceding `filter_kind_eq`).
    /// The fusion gate cannot resolve a schema without a kind.
    #[error(
        "filter_json_fused_* methods require a specific kind; call filter_kind_eq(..) before {method:?} or switch to the post-filter filter_json_* family"
    )]
    KindRequiredForFusion {
        /// Name of the fused filter method that was called.
        method: String,
    },
}

/// Fluent builder for constructing a [`QueryAst`].
///
/// Start with [`QueryBuilder::nodes`] and chain filtering, traversal, and
/// expansion steps before calling [`compile`](QueryBuilder::compile) or
/// [`compile_grouped`](QueryBuilder::compile_grouped).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryBuilder {
    ast: QueryAst,
}

impl QueryBuilder {
    /// Create a builder that queries nodes of the given kind.
    #[must_use]
    pub fn nodes(kind: impl Into<String>) -> Self {
        Self {
            ast: QueryAst {
                root_kind: kind.into(),
                steps: Vec::new(),
                expansions: Vec::new(),
                edge_expansions: Vec::new(),
                final_limit: None,
            },
        }
    }

    /// Add a vector similarity search step.
    #[must_use]
    pub fn vector_search(mut self, query: impl Into<String>, limit: usize) -> Self {
        self.ast.steps.push(QueryStep::VectorSearch {
            query: query.into(),
            limit,
        });
        self
    }

    /// Add a full-text search step.
    ///
    /// The input is parsed into `FathomDB`'s safe supported subset: literal
    /// terms, quoted phrases, uppercase `OR`, uppercase `NOT`, and implicit
    /// `AND` by adjacency. Unsupported syntax remains literal rather than being
    /// passed through as raw FTS5 control syntax.
    #[must_use]
    pub fn text_search(mut self, query: impl Into<String>, limit: usize) -> Self {
        let query = TextQuery::parse(&query.into());
        self.ast.steps.push(QueryStep::TextSearch { query, limit });
        self
    }

    /// Add a graph traversal step following edges of the given label.
    #[must_use]
    pub fn traverse(
        mut self,
        direction: TraverseDirection,
        label: impl Into<String>,
        max_depth: usize,
    ) -> Self {
        self.ast.steps.push(QueryStep::Traverse {
            direction,
            label: label.into(),
            max_depth,
            filter: None,
        });
        self
    }

    /// Filter results to a single logical ID.
    #[must_use]
    pub fn filter_logical_id_eq(mut self, logical_id: impl Into<String>) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::LogicalIdEq(logical_id.into())));
        self
    }

    /// Filter results to nodes matching the given kind.
    #[must_use]
    pub fn filter_kind_eq(mut self, kind: impl Into<String>) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::KindEq(kind.into())));
        self
    }

    /// Filter results to nodes matching the given `source_ref`.
    #[must_use]
    pub fn filter_source_ref_eq(mut self, source_ref: impl Into<String>) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::SourceRefEq(source_ref.into())));
        self
    }

    /// Filter results to nodes where `content_ref` is not NULL.
    #[must_use]
    pub fn filter_content_ref_not_null(mut self) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::ContentRefNotNull));
        self
    }

    /// Filter results to nodes matching the given `content_ref` URI.
    #[must_use]
    pub fn filter_content_ref_eq(mut self, content_ref: impl Into<String>) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::ContentRefEq(
                content_ref.into(),
            )));
        self
    }

    /// Filter results where a JSON property at `path` equals the given text value.
    #[must_use]
    pub fn filter_json_text_eq(
        mut self,
        path: impl Into<String>,
        value: impl Into<String>,
    ) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathEq {
                path: path.into(),
                value: ScalarValue::Text(value.into()),
            }));
        self
    }

    /// Filter results where a JSON property at `path` equals the given boolean value.
    #[must_use]
    pub fn filter_json_bool_eq(mut self, path: impl Into<String>, value: bool) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathEq {
                path: path.into(),
                value: ScalarValue::Bool(value),
            }));
        self
    }

    /// Filter results where a JSON integer at `path` is greater than `value`.
    #[must_use]
    pub fn filter_json_integer_gt(mut self, path: impl Into<String>, value: i64) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathCompare {
                path: path.into(),
                op: ComparisonOp::Gt,
                value: ScalarValue::Integer(value),
            }));
        self
    }

    /// Filter results where a JSON integer at `path` is greater than or equal to `value`.
    #[must_use]
    pub fn filter_json_integer_gte(mut self, path: impl Into<String>, value: i64) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathCompare {
                path: path.into(),
                op: ComparisonOp::Gte,
                value: ScalarValue::Integer(value),
            }));
        self
    }

    /// Filter results where a JSON integer at `path` is less than `value`.
    #[must_use]
    pub fn filter_json_integer_lt(mut self, path: impl Into<String>, value: i64) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathCompare {
                path: path.into(),
                op: ComparisonOp::Lt,
                value: ScalarValue::Integer(value),
            }));
        self
    }

    /// Filter results where a JSON integer at `path` is less than or equal to `value`.
    #[must_use]
    pub fn filter_json_integer_lte(mut self, path: impl Into<String>, value: i64) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathCompare {
                path: path.into(),
                op: ComparisonOp::Lte,
                value: ScalarValue::Integer(value),
            }));
        self
    }

    /// Filter results where a JSON timestamp at `path` is after `value` (epoch seconds).
    #[must_use]
    pub fn filter_json_timestamp_gt(self, path: impl Into<String>, value: i64) -> Self {
        self.filter_json_integer_gt(path, value)
    }

    /// Filter results where a JSON timestamp at `path` is at or after `value`.
    #[must_use]
    pub fn filter_json_timestamp_gte(self, path: impl Into<String>, value: i64) -> Self {
        self.filter_json_integer_gte(path, value)
    }

    /// Filter results where a JSON timestamp at `path` is before `value`.
    #[must_use]
    pub fn filter_json_timestamp_lt(self, path: impl Into<String>, value: i64) -> Self {
        self.filter_json_integer_lt(path, value)
    }

    /// Filter results where a JSON timestamp at `path` is at or before `value`.
    #[must_use]
    pub fn filter_json_timestamp_lte(self, path: impl Into<String>, value: i64) -> Self {
        self.filter_json_integer_lte(path, value)
    }

    /// Append a fused JSON text-equality predicate without validating
    /// whether the caller has a property-FTS schema for the kind.
    ///
    /// Callers must have already validated the fusion gate; the
    /// tethered [`crate::QueryBuilder`] has no engine handle to consult
    /// a schema. Mis-use — calling this without prior schema
    /// validation — produces SQL that pushes a `json_extract` predicate
    /// into the search CTE's inner WHERE clause. That is valid SQL but
    /// defeats the "developer opt-in" contract.
    #[must_use]
    pub fn filter_json_fused_text_eq_unchecked(
        mut self,
        path: impl Into<String>,
        value: impl Into<String>,
    ) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathFusedEq {
                path: path.into(),
                value: value.into(),
            }));
        self
    }

    /// Append a fused JSON timestamp-greater-than predicate without
    /// validating the fusion gate. See
    /// [`Self::filter_json_fused_text_eq_unchecked`] for the contract.
    #[must_use]
    pub fn filter_json_fused_timestamp_gt_unchecked(
        mut self,
        path: impl Into<String>,
        value: i64,
    ) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathFusedTimestampCmp {
                path: path.into(),
                op: ComparisonOp::Gt,
                value,
            }));
        self
    }

    /// Append a fused JSON timestamp-greater-or-equal predicate without
    /// validating the fusion gate. See
    /// [`Self::filter_json_fused_text_eq_unchecked`] for the contract.
    #[must_use]
    pub fn filter_json_fused_timestamp_gte_unchecked(
        mut self,
        path: impl Into<String>,
        value: i64,
    ) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathFusedTimestampCmp {
                path: path.into(),
                op: ComparisonOp::Gte,
                value,
            }));
        self
    }

    /// Append a fused JSON timestamp-less-than predicate without
    /// validating the fusion gate. See
    /// [`Self::filter_json_fused_text_eq_unchecked`] for the contract.
    #[must_use]
    pub fn filter_json_fused_timestamp_lt_unchecked(
        mut self,
        path: impl Into<String>,
        value: i64,
    ) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathFusedTimestampCmp {
                path: path.into(),
                op: ComparisonOp::Lt,
                value,
            }));
        self
    }

    /// Append a fused JSON timestamp-less-or-equal predicate without
    /// validating the fusion gate. See
    /// [`Self::filter_json_fused_text_eq_unchecked`] for the contract.
    #[must_use]
    pub fn filter_json_fused_timestamp_lte_unchecked(
        mut self,
        path: impl Into<String>,
        value: i64,
    ) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathFusedTimestampCmp {
                path: path.into(),
                op: ComparisonOp::Lte,
                value,
            }));
        self
    }

    /// Append a fused JSON boolean-equality predicate without validating
    /// the fusion gate. See
    /// [`Self::filter_json_fused_text_eq_unchecked`] for the contract.
    #[must_use]
    pub fn filter_json_fused_bool_eq_unchecked(
        mut self,
        path: impl Into<String>,
        value: bool,
    ) -> Self {
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathFusedBoolEq {
                path: path.into(),
                value,
            }));
        self
    }

    /// Append a fused JSON text IN-set predicate without validating the
    /// fusion gate. See [`Self::filter_json_fused_text_eq_unchecked`] for
    /// the contract.
    ///
    /// # Panics
    ///
    /// Panics if `values` is empty — `SQLite` `IN` with an empty list is a syntax error.
    #[must_use]
    pub fn filter_json_fused_text_in_unchecked(
        mut self,
        path: impl Into<String>,
        values: Vec<String>,
    ) -> Self {
        assert!(
            !values.is_empty(),
            "filter_json_fused_text_in: values must not be empty"
        );
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathFusedIn {
                path: path.into(),
                values,
            }));
        self
    }

    /// Filter results where a JSON text property at `path` is one of `values`.
    ///
    /// This is the non-fused variant; the predicate is applied as a residual
    /// WHERE clause. No FTS schema is required.
    ///
    /// # Panics
    ///
    /// Panics if `values` is empty — `SQLite` `IN` with an empty list is a syntax error.
    #[must_use]
    pub fn filter_json_text_in(mut self, path: impl Into<String>, values: Vec<String>) -> Self {
        assert!(
            !values.is_empty(),
            "filter_json_text_in: values must not be empty"
        );
        self.ast
            .steps
            .push(QueryStep::Filter(Predicate::JsonPathIn {
                path: path.into(),
                values: values.into_iter().map(ScalarValue::Text).collect(),
            }));
        self
    }

    /// Add an expansion slot that traverses edges of the given label for each root result.
    ///
    /// Pass `filter: None` to preserve the existing behavior. `filter: Some(_)` is
    /// accepted by the AST but the compilation is not yet implemented (Pack 3).
    /// Pass `edge_filter: None` to preserve pre-Pack-D behavior (no edge filtering).
    /// `edge_filter: Some(EdgePropertyEq { .. })` filters traversed edges by their
    /// JSON properties; only edges matching the predicate are followed.
    #[must_use]
    pub fn expand(
        mut self,
        slot: impl Into<String>,
        direction: TraverseDirection,
        label: impl Into<String>,
        max_depth: usize,
        filter: Option<Predicate>,
        edge_filter: Option<Predicate>,
    ) -> Self {
        self.ast.expansions.push(ExpansionSlot {
            slot: slot.into(),
            direction,
            label: label.into(),
            max_depth,
            filter,
            edge_filter,
        });
        self
    }

    /// Begin registering an edge-projecting expansion slot. Chain
    /// [`EdgeExpansionBuilder::edge_filter`] /
    /// [`EdgeExpansionBuilder::endpoint_filter`] to attach predicates,
    /// then call [`EdgeExpansionBuilder::done`] to return this builder.
    ///
    /// Emits `(EdgeRow, NodeRow)` tuples per root on execution. The
    /// endpoint node is the target on `Out` traversal, source on `In`.
    /// Slot name must be unique across both node- and edge-expansions
    /// within the same query; collisions are reported by
    /// [`Self::compile_grouped`].
    #[must_use]
    pub fn traverse_edges(
        self,
        slot: impl Into<String>,
        direction: TraverseDirection,
        label: impl Into<String>,
        max_depth: usize,
    ) -> EdgeExpansionBuilder {
        EdgeExpansionBuilder {
            parent: self,
            slot: EdgeExpansionSlot {
                slot: slot.into(),
                direction,
                label: label.into(),
                max_depth,
                endpoint_filter: None,
                edge_filter: None,
            },
        }
    }

    /// Set the maximum number of result rows.
    #[must_use]
    pub fn limit(mut self, limit: usize) -> Self {
        self.ast.final_limit = Some(limit);
        self
    }

    /// Borrow the underlying [`QueryAst`].
    #[must_use]
    pub fn ast(&self) -> &QueryAst {
        &self.ast
    }

    /// Consume the builder and return the underlying [`QueryAst`].
    #[must_use]
    pub fn into_ast(self) -> QueryAst {
        self.ast
    }

    /// Compile this builder's AST into an executable [`CompiledQuery`].
    ///
    /// # Errors
    ///
    /// Returns [`CompileError`] if the query violates structural constraints
    /// (e.g. too many traversal steps or too many bind parameters).
    pub fn compile(&self) -> Result<CompiledQuery, CompileError> {
        compile_query(&self.ast)
    }

    /// Compile this builder's AST into an executable grouped query.
    ///
    /// # Errors
    ///
    /// Returns [`CompileError`] if the query violates grouped-query structural
    /// constraints such as duplicate slot names or excessive depth.
    pub fn compile_grouped(&self) -> Result<CompiledGroupedQuery, CompileError> {
        compile_grouped_query(&self.ast)
    }
}

/// Chained builder for an edge-projecting expansion slot. Returned by
/// [`QueryBuilder::traverse_edges`]; call [`Self::done`] to append the
/// slot to the parent `QueryBuilder` and resume chaining.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EdgeExpansionBuilder {
    parent: QueryBuilder,
    slot: EdgeExpansionSlot,
}

impl EdgeExpansionBuilder {
    /// Attach an edge-property predicate. Only `EdgePropertyEq` and
    /// `EdgePropertyCompare` are valid here; other variants are accepted
    /// by the AST but will be rejected downstream during edge-expansion
    /// compilation.
    #[must_use]
    pub fn edge_filter(mut self, predicate: Predicate) -> Self {
        self.slot.edge_filter = Some(predicate);
        self
    }

    /// Attach an endpoint-node predicate (applied to the target node on
    /// `Out` traversal, source node on `In`).
    #[must_use]
    pub fn endpoint_filter(mut self, predicate: Predicate) -> Self {
        self.slot.endpoint_filter = Some(predicate);
        self
    }

    /// Finalize the edge-expansion slot and return the parent
    /// `QueryBuilder` for further chaining.
    #[must_use]
    pub fn done(mut self) -> QueryBuilder {
        self.parent.ast.edge_expansions.push(self.slot);
        self.parent
    }
}

#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
    use crate::{Predicate, QueryBuilder, QueryStep, ScalarValue, TextQuery, TraverseDirection};

    #[test]
    fn builder_accumulates_expected_steps() {
        let query = QueryBuilder::nodes("Meeting")
            .text_search("budget", 5)
            .traverse(TraverseDirection::Out, "HAS_TASK", 2)
            .filter_json_text_eq("$.status", "active")
            .limit(10);

        assert_eq!(query.ast().steps.len(), 3);
        assert_eq!(query.ast().final_limit, Some(10));
    }

    #[test]
    fn builder_filter_json_bool_eq_produces_correct_predicate() {
        let query = QueryBuilder::nodes("Feature").filter_json_bool_eq("$.enabled", true);

        assert_eq!(query.ast().steps.len(), 1);
        match &query.ast().steps[0] {
            QueryStep::Filter(Predicate::JsonPathEq { path, value }) => {
                assert_eq!(path, "$.enabled");
                assert_eq!(*value, ScalarValue::Bool(true));
            }
            other => panic!("expected JsonPathEq/Bool, got {other:?}"),
        }
    }

    #[test]
    fn builder_text_search_parses_into_typed_query() {
        let query = QueryBuilder::nodes("Meeting").text_search("ship NOT blocked", 10);

        match &query.ast().steps[0] {
            QueryStep::TextSearch { query, limit } => {
                assert_eq!(*limit, 10);
                assert_eq!(
                    *query,
                    TextQuery::And(vec![
                        TextQuery::Term("ship".into()),
                        TextQuery::Not(Box::new(TextQuery::Term("blocked".into()))),
                    ])
                );
            }
            other => panic!("expected TextSearch, got {other:?}"),
        }
    }
}