fraiseql-wire 2.2.0

Streaming JSON query engine for Postgres 17
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
//! WHERE clause operators
//!
//! Type-safe operator definitions for WHERE clause generation.
//! Supports 25+ operators across 5 categories with both JSONB and direct column sources.

use super::field::{Field, Value};

/// WHERE clause operators
///
/// Supports type-safe, audit-friendly WHERE clause construction
/// without raw SQL strings.
///
/// # Categories
///
/// - **Comparison**: Eq, Neq, Gt, Gte, Lt, Lte
/// - **Array**: In, Nin, Contains, `ArrayContains`, `ArrayContainedBy`, `ArrayOverlaps`
/// - **Array Length**: `LenEq`, `LenGt`, `LenGte`, `LenLt`, `LenLte`
/// - **String**: Icontains, Startswith, Istartswith, Endswith, Iendswith, Like, Ilike
/// - **Null**: `IsNull`
/// - **Vector Distance**: `L2Distance`, `CosineDistance`, `InnerProduct`, `L1Distance`, `HammingDistance`, `JaccardDistance`
/// - **Full-Text Search**: Matches, `PlainQuery`, `PhraseQuery`, `WebsearchQuery`
/// - **Network**: `IsIPv4`, `IsIPv6`, `IsPrivate`, `IsPublic`, `IsLoopback`, `InSubnet`, `ContainsSubnet`, `ContainsIP`, `IPRangeOverlap`
/// - **JSONB**: `StrictlyContains`
/// - **`LTree`**: `AncestorOf`, `DescendantOf`, `MatchesLquery`, `MatchesLtxtquery`, `MatchesAnyLquery`,
///   `DepthEq`, `DepthNeq`, `DepthGt`, `DepthGte`, `DepthLt`, `DepthLte`, Lca
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum WhereOperator {
    // ============ Comparison Operators ============
    /// Equal: `field = value`
    Eq(Field, Value),

    /// Not equal: `field != value` or `field <> value`
    Neq(Field, Value),

    /// Greater than: `field > value`
    Gt(Field, Value),

    /// Greater than or equal: `field >= value`
    Gte(Field, Value),

    /// Less than: `field < value`
    Lt(Field, Value),

    /// Less than or equal: `field <= value`
    Lte(Field, Value),

    // ============ Array Operators ============
    /// Array contains value: `field IN (...)`
    In(Field, Vec<Value>),

    /// Array does not contain value: `field NOT IN (...)`
    Nin(Field, Vec<Value>),

    /// String contains substring: `field LIKE '%substring%'`
    ///
    /// # Warning — LIKE wildcard injection
    ///
    /// The substring is embedded between `%` anchors. Characters `%` (any sequence) and
    /// `_` (any single character) in the substring itself are **also** treated as LIKE
    /// wildcards, causing broader matches than intended. Escape user-supplied values
    /// (replace `%` → `\%` and `_` → `\_`) before constructing this variant.
    Contains(Field, String),

    /// Array contains element: PostgreSQL array operator `@>`
    /// Generated SQL: `field @> array[value]`
    ArrayContains(Field, Value),

    /// Array is contained by: PostgreSQL array operator `<@`
    /// Generated SQL: `field <@ array[value]`
    ArrayContainedBy(Field, Value),

    /// Arrays overlap: PostgreSQL array operator `&&`
    /// Generated SQL: `field && array[value]`
    ArrayOverlaps(Field, Vec<Value>),

    // ============ Array Length Operators ============
    /// Array length equals: `array_length(field, 1) = value`
    LenEq(Field, usize),

    /// Array length greater than: `array_length(field, 1) > value`
    LenGt(Field, usize),

    /// Array length greater than or equal: `array_length(field, 1) >= value`
    LenGte(Field, usize),

    /// Array length less than: `array_length(field, 1) < value`
    LenLt(Field, usize),

    /// Array length less than or equal: `array_length(field, 1) <= value`
    LenLte(Field, usize),

    // ============ String Operators ============
    /// Case-insensitive contains: `field ILIKE '%substring%'`
    ///
    /// # Warning — LIKE wildcard injection
    ///
    /// Same escaping requirements as [`WhereOperator::Contains`]. ILIKE applies the same
    /// wildcard semantics, so `%` and `_` in the substring expand unexpectedly.
    Icontains(Field, String),

    /// Starts with: `field LIKE 'prefix%'`
    ///
    /// # Warning — LIKE wildcard injection
    ///
    /// The prefix string is passed verbatim before the trailing `%`. Characters `%` and `_`
    /// in the prefix are treated as wildcards; escape user-supplied values before use.
    Startswith(Field, String),

    /// Starts with (case-insensitive): `field ILIKE 'prefix%'`
    ///
    /// # Warning — LIKE wildcard injection
    ///
    /// Same escaping requirements as [`WhereOperator::Startswith`].
    Istartswith(Field, String),

    /// Ends with: `field LIKE '%suffix'`
    ///
    /// # Warning — LIKE wildcard injection
    ///
    /// The suffix string is passed verbatim after the leading `%`. Characters `%` and `_`
    /// in the suffix are treated as wildcards; escape user-supplied values before use.
    Endswith(Field, String),

    /// Ends with (case-insensitive): `field ILIKE '%suffix'`
    ///
    /// # Warning — LIKE wildcard injection
    ///
    /// Same escaping requirements as [`WhereOperator::Endswith`].
    Iendswith(Field, String),

    /// LIKE pattern matching: `field LIKE pattern`
    ///
    /// # Warning — LIKE wildcard injection
    ///
    /// The pattern string is passed to the database as-is. Characters `%` (any
    /// sequence) and `_` (any single character) are SQL LIKE wildcards. If the
    /// pattern originates from user input, callers **must** escape these
    /// characters (e.g. replace `%` → `\%` and `_` → `\_`) before constructing
    /// this variant, and append the appropriate `ESCAPE '\'` clause.
    Like(Field, String),

    /// Case-insensitive LIKE: `field ILIKE pattern`
    ///
    /// # Warning — LIKE wildcard injection
    ///
    /// Same escaping requirements as [`WhereOperator::Like`]. The `%` and `_`
    /// wildcards apply to ILIKE patterns as well.
    Ilike(Field, String),

    // ============ Null Operator ============
    /// IS NULL: `field IS NULL` or `field IS NOT NULL`
    ///
    /// When the boolean is true, generates `IS NULL`
    /// When false, generates `IS NOT NULL`
    IsNull(Field, bool),

    // ============ Vector Distance Operators (pgvector) ============
    /// L2 (Euclidean) distance: `l2_distance(field, vector) < threshold`
    ///
    /// Requires pgvector extension.
    L2Distance {
        /// The vector field to compare against
        field: Field,
        /// The embedding vector for distance calculation
        vector: Vec<f32>,
        /// Distance threshold for comparison
        threshold: f32,
    },

    /// Cosine distance: `cosine_distance(field, vector) < threshold`
    ///
    /// Requires pgvector extension.
    CosineDistance {
        /// The vector field to compare against
        field: Field,
        /// The embedding vector for distance calculation
        vector: Vec<f32>,
        /// Distance threshold for comparison
        threshold: f32,
    },

    /// Inner product: `inner_product(field, vector) > threshold`
    ///
    /// Requires pgvector extension.
    InnerProduct {
        /// The vector field to compare against
        field: Field,
        /// The embedding vector for distance calculation
        vector: Vec<f32>,
        /// Distance threshold for comparison
        threshold: f32,
    },

    /// L1 (Manhattan) distance: `l1_distance(field, vector) < threshold`
    ///
    /// Requires pgvector extension.
    L1Distance {
        /// The vector field to compare against
        field: Field,
        /// The embedding vector for distance calculation
        vector: Vec<f32>,
        /// Distance threshold for comparison
        threshold: f32,
    },

    /// Hamming distance: `hamming_distance(field, vector) < threshold`
    ///
    /// Requires pgvector extension. Works with bit vectors.
    HammingDistance {
        /// The vector field to compare against
        field: Field,
        /// The embedding vector for distance calculation
        vector: Vec<f32>,
        /// Distance threshold for comparison
        threshold: f32,
    },

    /// Jaccard distance: `jaccard_distance(field, set) < threshold`
    ///
    /// Works with text arrays, measures set overlap.
    JaccardDistance {
        /// The field to compare against
        field: Field,
        /// The set of values for comparison
        set: Vec<String>,
        /// Distance threshold for comparison
        threshold: f32,
    },

    // ============ Full-Text Search Operators ============
    /// Full-text search with language: `field @@ plainto_tsquery(language, query)`
    ///
    /// If language is None, defaults to 'english'
    Matches {
        /// The text field to search
        field: Field,
        /// The search query
        query: String,
        /// Optional language for text search (default: english)
        language: Option<String>,
    },

    /// Plain text query: `field @@ plainto_tsquery(query)`
    ///
    /// Uses no language specification
    PlainQuery {
        /// The text field to search
        field: Field,
        /// The search query
        query: String,
    },

    /// Phrase query with language: `field @@ phraseto_tsquery(language, query)`
    ///
    /// If language is None, defaults to 'english'
    PhraseQuery {
        /// The text field to search
        field: Field,
        /// The search query
        query: String,
        /// Optional language for text search (default: english)
        language: Option<String>,
    },

    /// Web search query with language: `field @@ websearch_to_tsquery(language, query)`
    ///
    /// If language is None, defaults to 'english'
    WebsearchQuery {
        /// The text field to search
        field: Field,
        /// The search query
        query: String,
        /// Optional language for text search (default: english)
        language: Option<String>,
    },

    // ============ Network/INET Operators ============
    /// Check if IP is `IPv4`: `family(field) = 4`
    IsIPv4(Field),

    /// Check if IP is `IPv6`: `family(field) = 6`
    IsIPv6(Field),

    /// Check if IP is private (RFC1918): matches private ranges
    IsPrivate(Field),

    /// Check if IP is public (not private): opposite of `IsPrivate`
    IsPublic(Field),

    /// Check if IP is loopback: `IPv4` 127.0.0.0/8 or `IPv6` `::1/128`
    IsLoopback(Field),

    /// IP is in subnet: `field << subnet`
    ///
    /// The subnet should be in CIDR notation (e.g., "192.168.0.0/24")
    InSubnet {
        /// The IP field to check
        field: Field,
        /// The CIDR subnet (e.g., "192.168.0.0/24")
        subnet: String,
    },

    /// Network contains subnet: `field >> subnet`
    ///
    /// The subnet should be in CIDR notation
    ContainsSubnet {
        /// The network field to check
        field: Field,
        /// The CIDR subnet to check for containment
        subnet: String,
    },

    /// Network/range contains IP: `field >> ip`
    ///
    /// The IP should be a single address (e.g., "192.168.1.1")
    ContainsIP {
        /// The network field to check
        field: Field,
        /// The IP address to check for containment
        ip: String,
    },

    /// IP ranges overlap: `field && range`
    ///
    /// The range should be in CIDR notation
    IPRangeOverlap {
        /// The IP range field to check
        field: Field,
        /// The IP range to check for overlap
        range: String,
    },

    // ============ JSONB Operators ============
    /// JSONB strictly contains: `field @> value`
    ///
    /// Checks if the JSONB field strictly contains the given value
    StrictlyContains(Field, Value),

    // ============ LTree Operators (Hierarchical) ============
    /// Ancestor of: `field @> path`
    ///
    /// Checks if the ltree field is an ancestor of the given path
    AncestorOf {
        /// The ltree field to check
        field: Field,
        /// The path to check ancestry against
        path: String,
    },

    /// Descendant of: `field <@ path`
    ///
    /// Checks if the ltree field is a descendant of the given path
    DescendantOf {
        /// The ltree field to check
        field: Field,
        /// The path to check descendancy against
        path: String,
    },

    /// Matches lquery: `field ~ lquery`
    ///
    /// Checks if the ltree field matches the given lquery pattern
    MatchesLquery {
        /// The ltree field to check
        field: Field,
        /// The lquery pattern to match against
        pattern: String,
    },

    /// Matches ltxtquery: `field @ ltxtquery`
    ///
    /// Checks if the ltree field matches the given ltxtquery pattern (Boolean query syntax)
    MatchesLtxtquery {
        /// The ltree field to check
        field: Field,
        /// The ltxtquery pattern to match against (e.g., "Science & !Deprecated")
        query: String,
    },

    /// Matches any lquery: `field ? array[lqueries]`
    ///
    /// Checks if the ltree field matches any of the given lquery patterns
    MatchesAnyLquery {
        /// The ltree field to check
        field: Field,
        /// Array of lquery patterns to match against
        patterns: Vec<String>,
    },

    /// `LTree` depth equals: `nlevel(field) = depth`
    DepthEq {
        /// The ltree field to check
        field: Field,
        /// The depth value to compare
        depth: usize,
    },

    /// `LTree` depth not equals: `nlevel(field) != depth`
    DepthNeq {
        /// The ltree field to check
        field: Field,
        /// The depth value to compare
        depth: usize,
    },

    /// `LTree` depth greater than: `nlevel(field) > depth`
    DepthGt {
        /// The ltree field to check
        field: Field,
        /// The depth value to compare
        depth: usize,
    },

    /// `LTree` depth greater than or equal: `nlevel(field) >= depth`
    DepthGte {
        /// The ltree field to check
        field: Field,
        /// The depth value to compare
        depth: usize,
    },

    /// `LTree` depth less than: `nlevel(field) < depth`
    DepthLt {
        /// The ltree field to check
        field: Field,
        /// The depth value to compare
        depth: usize,
    },

    /// `LTree` depth less than or equal: `nlevel(field) <= depth`
    DepthLte {
        /// The ltree field to check
        field: Field,
        /// The depth value to compare
        depth: usize,
    },

    /// Lowest common ancestor: `lca(field, paths)`
    ///
    /// Checks if the ltree field equals the lowest common ancestor of the given paths
    Lca {
        /// The ltree field to check
        field: Field,
        /// The paths to find LCA of
        paths: Vec<String>,
    },
}

impl WhereOperator {
    /// Get a human-readable name for this operator
    pub const fn name(&self) -> &'static str {
        match self {
            WhereOperator::Eq(_, _) => "Eq",
            WhereOperator::Neq(_, _) => "Neq",
            WhereOperator::Gt(_, _) => "Gt",
            WhereOperator::Gte(_, _) => "Gte",
            WhereOperator::Lt(_, _) => "Lt",
            WhereOperator::Lte(_, _) => "Lte",
            WhereOperator::In(_, _) => "In",
            WhereOperator::Nin(_, _) => "Nin",
            WhereOperator::Contains(_, _) => "Contains",
            WhereOperator::ArrayContains(_, _) => "ArrayContains",
            WhereOperator::ArrayContainedBy(_, _) => "ArrayContainedBy",
            WhereOperator::ArrayOverlaps(_, _) => "ArrayOverlaps",
            WhereOperator::LenEq(_, _) => "LenEq",
            WhereOperator::LenGt(_, _) => "LenGt",
            WhereOperator::LenGte(_, _) => "LenGte",
            WhereOperator::LenLt(_, _) => "LenLt",
            WhereOperator::LenLte(_, _) => "LenLte",
            WhereOperator::Icontains(_, _) => "Icontains",
            WhereOperator::Startswith(_, _) => "Startswith",
            WhereOperator::Istartswith(_, _) => "Istartswith",
            WhereOperator::Endswith(_, _) => "Endswith",
            WhereOperator::Iendswith(_, _) => "Iendswith",
            WhereOperator::Like(_, _) => "Like",
            WhereOperator::Ilike(_, _) => "Ilike",
            WhereOperator::IsNull(_, _) => "IsNull",
            WhereOperator::L2Distance { .. } => "L2Distance",
            WhereOperator::CosineDistance { .. } => "CosineDistance",
            WhereOperator::InnerProduct { .. } => "InnerProduct",
            WhereOperator::L1Distance { .. } => "L1Distance",
            WhereOperator::HammingDistance { .. } => "HammingDistance",
            WhereOperator::JaccardDistance { .. } => "JaccardDistance",
            WhereOperator::Matches { .. } => "Matches",
            WhereOperator::PlainQuery { .. } => "PlainQuery",
            WhereOperator::PhraseQuery { .. } => "PhraseQuery",
            WhereOperator::WebsearchQuery { .. } => "WebsearchQuery",
            WhereOperator::IsIPv4(_) => "IsIPv4",
            WhereOperator::IsIPv6(_) => "IsIPv6",
            WhereOperator::IsPrivate(_) => "IsPrivate",
            WhereOperator::IsPublic(_) => "IsPublic",
            WhereOperator::IsLoopback(_) => "IsLoopback",
            WhereOperator::InSubnet { .. } => "InSubnet",
            WhereOperator::ContainsSubnet { .. } => "ContainsSubnet",
            WhereOperator::ContainsIP { .. } => "ContainsIP",
            WhereOperator::IPRangeOverlap { .. } => "IPRangeOverlap",
            WhereOperator::StrictlyContains(_, _) => "StrictlyContains",
            WhereOperator::AncestorOf { .. } => "AncestorOf",
            WhereOperator::DescendantOf { .. } => "DescendantOf",
            WhereOperator::MatchesLquery { .. } => "MatchesLquery",
            WhereOperator::MatchesLtxtquery { .. } => "MatchesLtxtquery",
            WhereOperator::MatchesAnyLquery { .. } => "MatchesAnyLquery",
            WhereOperator::DepthEq { .. } => "DepthEq",
            WhereOperator::DepthNeq { .. } => "DepthNeq",
            WhereOperator::DepthGt { .. } => "DepthGt",
            WhereOperator::DepthGte { .. } => "DepthGte",
            WhereOperator::DepthLt { .. } => "DepthLt",
            WhereOperator::DepthLte { .. } => "DepthLte",
            WhereOperator::Lca { .. } => "Lca",
        }
    }

    /// Validate operator for basic correctness
    ///
    /// # Errors
    ///
    /// Returns an error string if the field name is invalid or, for vector distance
    /// operators, the threshold is not a finite number.
    pub fn validate(&self) -> Result<(), String> {
        match self {
            WhereOperator::Eq(f, _)
            | WhereOperator::Neq(f, _)
            | WhereOperator::Gt(f, _)
            | WhereOperator::Gte(f, _)
            | WhereOperator::Lt(f, _)
            | WhereOperator::Lte(f, _)
            | WhereOperator::In(f, _)
            | WhereOperator::Nin(f, _)
            | WhereOperator::Contains(f, _)
            | WhereOperator::ArrayContains(f, _)
            | WhereOperator::ArrayContainedBy(f, _)
            | WhereOperator::ArrayOverlaps(f, _)
            | WhereOperator::LenEq(f, _)
            | WhereOperator::LenGt(f, _)
            | WhereOperator::LenGte(f, _)
            | WhereOperator::LenLt(f, _)
            | WhereOperator::LenLte(f, _)
            | WhereOperator::Icontains(f, _)
            | WhereOperator::Startswith(f, _)
            | WhereOperator::Istartswith(f, _)
            | WhereOperator::Endswith(f, _)
            | WhereOperator::Iendswith(f, _)
            | WhereOperator::Like(f, _)
            | WhereOperator::Ilike(f, _)
            | WhereOperator::IsNull(f, _)
            | WhereOperator::StrictlyContains(f, _) => f.validate(),

            WhereOperator::L2Distance {
                field, threshold, ..
            }
            | WhereOperator::CosineDistance {
                field, threshold, ..
            }
            | WhereOperator::InnerProduct {
                field, threshold, ..
            }
            | WhereOperator::L1Distance {
                field, threshold, ..
            }
            | WhereOperator::HammingDistance {
                field, threshold, ..
            }
            | WhereOperator::JaccardDistance {
                field, threshold, ..
            } => {
                if !threshold.is_finite() {
                    return Err(format!(
                        "Vector distance threshold must be a finite number, got {}",
                        threshold
                    ));
                }
                field.validate()
            }

            WhereOperator::Matches { field, .. }
            | WhereOperator::PlainQuery { field, .. }
            | WhereOperator::PhraseQuery { field, .. }
            | WhereOperator::WebsearchQuery { field, .. }
            | WhereOperator::IsIPv4(field)
            | WhereOperator::IsIPv6(field)
            | WhereOperator::IsPrivate(field)
            | WhereOperator::IsPublic(field)
            | WhereOperator::IsLoopback(field)
            | WhereOperator::InSubnet { field, .. }
            | WhereOperator::ContainsSubnet { field, .. }
            | WhereOperator::ContainsIP { field, .. }
            | WhereOperator::IPRangeOverlap { field, .. }
            | WhereOperator::AncestorOf { field, .. }
            | WhereOperator::DescendantOf { field, .. }
            | WhereOperator::MatchesLquery { field, .. }
            | WhereOperator::MatchesLtxtquery { field, .. }
            | WhereOperator::MatchesAnyLquery { field, .. }
            | WhereOperator::DepthEq { field, .. }
            | WhereOperator::DepthNeq { field, .. }
            | WhereOperator::DepthGt { field, .. }
            | WhereOperator::DepthGte { field, .. }
            | WhereOperator::DepthLt { field, .. }
            | WhereOperator::DepthLte { field, .. }
            | WhereOperator::Lca { field, .. } => field.validate(),
        }
    }
}

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

    #[test]
    fn test_operator_names() {
        let op = WhereOperator::Eq(Field::JsonbField("id".to_string()), Value::Number(1.0));
        assert_eq!(op.name(), "Eq");

        let op = WhereOperator::LenGt(Field::JsonbField("tags".to_string()), 5);
        assert_eq!(op.name(), "LenGt");
    }

    #[test]
    fn test_operator_validation() {
        let op = WhereOperator::Eq(
            Field::JsonbField("name".to_string()),
            Value::String("John".to_string()),
        );
        op.validate()
            .unwrap_or_else(|e| panic!("expected Ok for valid field 'name': {e}"));

        let op = WhereOperator::Eq(
            Field::JsonbField("bad-name".to_string()),
            Value::String("John".to_string()),
        );
        let result = op.validate();
        assert!(
            result.is_err(),
            "expected Err for invalid field 'bad-name', got: {result:?}"
        );
    }

    #[test]
    fn test_vector_operator_creation() {
        let op = WhereOperator::L2Distance {
            field: Field::JsonbField("embedding".to_string()),
            vector: vec![0.1, 0.2, 0.3],
            threshold: 0.5,
        };
        assert_eq!(op.name(), "L2Distance");
    }

    #[test]
    fn test_network_operator_creation() {
        let op = WhereOperator::InSubnet {
            field: Field::JsonbField("ip".to_string()),
            subnet: "192.168.0.0/24".to_string(),
        };
        assert_eq!(op.name(), "InSubnet");
    }
}