prax-query 0.10.0

Type-safe query builder for the Prax 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
//! Reusable scalar filter wrappers shared by every generated `*WhereInput`.
//!
//! Each wrapper is a struct of `Option`-fields, one per operator. Empty
//! wrappers (all fields `None`) lower to `Filter::None`. Multiple set
//! fields AND-combine. `From<scalar>` impls support the macro shorthand
//! `email: "alice@x.com"` => `StringFilter { equals: Some("..."), .. }`.
//!
//! Every wrapper implements [`ScalarFilter`], whose `into_filter`
//! method takes the column name (which the parent `WhereInput` knows)
//! and produces a runtime [`Filter`].

use crate::filter::{Filter, FilterValue};
use serde::{Deserialize, Serialize};

/// Helper trait implemented by every scalar filter wrapper.
///
/// The wrapper itself doesn't know its column name — the parent
/// `WhereInput::into_ir` impl threads the column in when lowering.
pub trait ScalarFilter {
    /// Lower this scalar filter to a runtime [`Filter`] keyed by
    /// the given column name.
    fn into_filter(self, column: &str) -> Filter;
}

/// Collapse a list of operator filters into a single [`Filter`].
///
/// Every `ScalarFilter::into_filter` impl accumulates one entry per
/// active operator and then needs to reduce that list to a `Filter`.
/// The reduction is identical across all of them:
/// - empty → `Filter::None`
/// - single → that filter unwrapped
/// - multiple → `Filter::and(parts)`.
pub(crate) fn combine_filters(parts: Vec<Filter>) -> Filter {
    match parts.len() {
        0 => Filter::None,
        1 => parts.into_iter().next().unwrap(),
        _ => Filter::and(parts),
    }
}

/// Comparison mode for string filters.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum QueryMode {
    /// Default (case-sensitive) comparison.
    #[default]
    Default,
    /// Case-insensitive comparison. Requires `SupportsCaseInsensitiveMode`
    /// for engines that don't fall back to `LOWER(...)`.
    Insensitive,
}

/// Filter operators for a non-nullable `String` column.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct StringFilter {
    /// `column = value`
    pub equals: Option<String>,
    /// Negation of the inner filter.
    pub not: Option<Box<StringFilter>>,
    /// `column IN (...)`
    pub in_list: Option<Vec<String>>,
    /// `column NOT IN (...)`
    pub not_in: Option<Vec<String>>,
    /// `column < value`
    pub lt: Option<String>,
    /// `column <= value`
    pub lte: Option<String>,
    /// `column > value`
    pub gt: Option<String>,
    /// `column >= value`
    pub gte: Option<String>,
    /// `column LIKE %value%`
    pub contains: Option<String>,
    /// `column LIKE value%`
    pub starts_with: Option<String>,
    /// `column LIKE %value`
    pub ends_with: Option<String>,
    /// Comparison mode (case sensitivity).
    pub mode: Option<QueryMode>,
}

impl StringFilter {
    /// `equals: Some(value)`.
    pub fn equals(v: impl Into<String>) -> Self {
        Self {
            equals: Some(v.into()),
            ..Default::default()
        }
    }
    /// `contains: Some(value)`.
    pub fn contains(v: impl Into<String>) -> Self {
        Self {
            contains: Some(v.into()),
            ..Default::default()
        }
    }
    /// `starts_with: Some(value)`.
    pub fn starts_with(v: impl Into<String>) -> Self {
        Self {
            starts_with: Some(v.into()),
            ..Default::default()
        }
    }
    /// `ends_with: Some(value)`.
    pub fn ends_with(v: impl Into<String>) -> Self {
        Self {
            ends_with: Some(v.into()),
            ..Default::default()
        }
    }
}

impl From<&str> for StringFilter {
    fn from(v: &str) -> Self {
        Self::equals(v)
    }
}
impl From<String> for StringFilter {
    fn from(v: String) -> Self {
        Self::equals(v)
    }
}

impl ScalarFilter for StringFilter {
    fn into_filter(self, column: &str) -> Filter {
        let mut parts: Vec<Filter> = Vec::new();
        let col = column.to_string();
        if let Some(v) = self.equals {
            parts.push(Filter::Equals(col.clone().into(), FilterValue::String(v)));
        }
        if let Some(boxed) = self.not {
            let inner = boxed.into_filter(column);
            parts.push(Filter::Not(Box::new(inner)));
        }
        if let Some(values) = self.in_list {
            let vs: Vec<FilterValue> = values.into_iter().map(FilterValue::String).collect();
            parts.push(Filter::In(col.clone().into(), vs));
        }
        if let Some(values) = self.not_in {
            let vs: Vec<FilterValue> = values.into_iter().map(FilterValue::String).collect();
            parts.push(Filter::NotIn(col.clone().into(), vs));
        }
        if let Some(v) = self.lt {
            parts.push(Filter::Lt(col.clone().into(), FilterValue::String(v)));
        }
        if let Some(v) = self.lte {
            parts.push(Filter::Lte(col.clone().into(), FilterValue::String(v)));
        }
        if let Some(v) = self.gt {
            parts.push(Filter::Gt(col.clone().into(), FilterValue::String(v)));
        }
        if let Some(v) = self.gte {
            parts.push(Filter::Gte(col.clone().into(), FilterValue::String(v)));
        }
        if let Some(v) = self.contains {
            parts.push(Filter::Contains(col.clone().into(), FilterValue::String(v)));
        }
        if let Some(v) = self.starts_with {
            parts.push(Filter::StartsWith(
                col.clone().into(),
                FilterValue::String(v),
            ));
        }
        if let Some(v) = self.ends_with {
            parts.push(Filter::EndsWith(col.clone().into(), FilterValue::String(v)));
        }
        // `mode` is honored by the dialect layer in phase 2+; phase 1 ignores
        // it here. The field is kept so downstream phases don't need a
        // breaking-shape change.
        let _ = self.mode;
        combine_filters(parts)
    }
}

/// Filter operators for a nullable `String` column.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct StringNullableFilter {
    /// `column = value`
    pub equals: Option<String>,
    /// Negation of the inner filter.
    pub not: Option<Box<StringNullableFilter>>,
    /// `column IN (...)`
    pub in_list: Option<Vec<String>>,
    /// `column NOT IN (...)`
    pub not_in: Option<Vec<String>>,
    /// `column < value`
    pub lt: Option<String>,
    /// `column <= value`
    pub lte: Option<String>,
    /// `column > value`
    pub gt: Option<String>,
    /// `column >= value`
    pub gte: Option<String>,
    /// `column LIKE %value%`
    pub contains: Option<String>,
    /// `column LIKE value%`
    pub starts_with: Option<String>,
    /// `column LIKE %value`
    pub ends_with: Option<String>,
    /// Comparison mode.
    pub mode: Option<QueryMode>,
    /// `is_null: Some(true)` => `IS NULL`; `Some(false)` => `IS NOT NULL`.
    pub is_null: Option<bool>,
}

impl From<&str> for StringNullableFilter {
    fn from(v: &str) -> Self {
        Self {
            equals: Some(v.into()),
            ..Default::default()
        }
    }
}
impl From<String> for StringNullableFilter {
    fn from(v: String) -> Self {
        Self {
            equals: Some(v),
            ..Default::default()
        }
    }
}

impl ScalarFilter for StringNullableFilter {
    fn into_filter(self, column: &str) -> Filter {
        let mut parts: Vec<Filter> = Vec::new();
        let col = column.to_string();
        if let Some(b) = self.is_null {
            parts.push(if b {
                Filter::IsNull(col.clone().into())
            } else {
                Filter::IsNotNull(col.clone().into())
            });
        }
        // Reuse StringFilter's lowering for the remaining ops.
        let inner = StringFilter {
            equals: self.equals,
            not: self.not.map(|b| {
                Box::new(StringFilter {
                    equals: b.equals,
                    in_list: b.in_list,
                    not_in: b.not_in,
                    lt: b.lt,
                    lte: b.lte,
                    gt: b.gt,
                    gte: b.gte,
                    contains: b.contains,
                    starts_with: b.starts_with,
                    ends_with: b.ends_with,
                    mode: b.mode,
                    not: None,
                })
            }),
            in_list: self.in_list,
            not_in: self.not_in,
            lt: self.lt,
            lte: self.lte,
            gt: self.gt,
            gte: self.gte,
            contains: self.contains,
            starts_with: self.starts_with,
            ends_with: self.ends_with,
            mode: self.mode,
        };
        let inner_filter = inner.into_filter(column);
        if !matches!(inner_filter, Filter::None) {
            parts.push(inner_filter);
        }
        combine_filters(parts)
    }
}

/// Macro to emit a scalar filter wrapper + nullable counterpart that
/// lowers to a `FilterValue::$variant`. Keeps the table of integer /
/// floating / temporal / blob types DRY without sacrificing rustdoc
/// per-type.
macro_rules! scalar_filter {
    (
        $(#[$nn_meta:meta])*
        $name:ident<$rust:ty> => |$conv_v:ident| $conv:block,
        $(#[$null_meta:meta])*
        nullable $null:ident
    ) => {
        $(#[$nn_meta])*
        #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
        #[serde(rename_all = "snake_case")]
        pub struct $name {
            /// `column = value`
            pub equals: Option<$rust>,
            /// Negation.
            pub not: Option<Box<$name>>,
            /// `column IN (...)`
            pub in_list: Option<Vec<$rust>>,
            /// `column NOT IN (...)`
            pub not_in: Option<Vec<$rust>>,
            /// `column < value`
            pub lt: Option<$rust>,
            /// `column <= value`
            pub lte: Option<$rust>,
            /// `column > value`
            pub gt: Option<$rust>,
            /// `column >= value`
            pub gte: Option<$rust>,
        }

        impl $name {
            /// `equals: Some(value)`.
            pub fn equals(v: impl Into<$rust>) -> Self {
                Self { equals: Some(v.into()), ..Default::default() }
            }
            /// `lt: Some(value)`.
            pub fn lt(v: impl Into<$rust>) -> Self {
                Self { lt: Some(v.into()), ..Default::default() }
            }
            /// `lte: Some(value)`.
            pub fn lte(v: impl Into<$rust>) -> Self {
                Self { lte: Some(v.into()), ..Default::default() }
            }
            /// `gt: Some(value)`.
            pub fn gt(v: impl Into<$rust>) -> Self {
                Self { gt: Some(v.into()), ..Default::default() }
            }
            /// `gte: Some(value)`.
            pub fn gte(v: impl Into<$rust>) -> Self {
                Self { gte: Some(v.into()), ..Default::default() }
            }
        }

        impl ScalarFilter for $name {
            fn into_filter(self, column: &str) -> Filter {
                fn to_fv($conv_v: $rust) -> FilterValue $conv
                let col: crate::filter::FieldName = column.to_string().into();
                let mut parts: Vec<Filter> = Vec::new();
                if let Some(v) = self.equals {
                    parts.push(Filter::Equals(col.clone(), to_fv(v)));
                }
                if let Some(boxed) = self.not {
                    let inner = boxed.into_filter(column);
                    parts.push(Filter::Not(Box::new(inner)));
                }
                if let Some(values) = self.in_list {
                    let vs: Vec<FilterValue> = values.into_iter().map(to_fv).collect();
                    parts.push(Filter::In(col.clone(), vs));
                }
                if let Some(values) = self.not_in {
                    let vs: Vec<FilterValue> = values.into_iter().map(to_fv).collect();
                    parts.push(Filter::NotIn(col.clone(), vs));
                }
                if let Some(v) = self.lt { parts.push(Filter::Lt(col.clone(), to_fv(v))); }
                if let Some(v) = self.lte { parts.push(Filter::Lte(col.clone(), to_fv(v))); }
                if let Some(v) = self.gt { parts.push(Filter::Gt(col.clone(), to_fv(v))); }
                if let Some(v) = self.gte { parts.push(Filter::Gte(col, to_fv(v))); }
                combine_filters(parts)
            }
        }

        $(#[$null_meta])*
        #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
        #[serde(rename_all = "snake_case")]
        pub struct $null {
            /// `column = value`
            pub equals: Option<$rust>,
            /// Negation.
            pub not: Option<Box<$null>>,
            /// `column IN (...)`
            pub in_list: Option<Vec<$rust>>,
            /// `column NOT IN (...)`
            pub not_in: Option<Vec<$rust>>,
            /// `column < value`
            pub lt: Option<$rust>,
            /// `column <= value`
            pub lte: Option<$rust>,
            /// `column > value`
            pub gt: Option<$rust>,
            /// `column >= value`
            pub gte: Option<$rust>,
            /// IS NULL / IS NOT NULL.
            pub is_null: Option<bool>,
        }

        impl ScalarFilter for $null {
            fn into_filter(self, column: &str) -> Filter {
                let mut parts: Vec<Filter> = Vec::new();
                if let Some(b) = self.is_null {
                    parts.push(if b {
                        Filter::IsNull(column.to_string().into())
                    } else {
                        Filter::IsNotNull(column.to_string().into())
                    });
                }
                let inner = $name {
                    equals: self.equals,
                    not: self.not.map(|b| Box::new($name {
                        equals: b.equals,
                        in_list: b.in_list,
                        not_in: b.not_in,
                        lt: b.lt, lte: b.lte, gt: b.gt, gte: b.gte,
                        not: None,
                    })),
                    in_list: self.in_list,
                    not_in: self.not_in,
                    lt: self.lt, lte: self.lte, gt: self.gt, gte: self.gte,
                };
                let f = inner.into_filter(column);
                if !matches!(f, Filter::None) { parts.push(f); }
                combine_filters(parts)
            }
        }
    };
}

scalar_filter!(
    /// Filter for non-nullable `Int` (`i32`) columns.
    IntFilter<i32> => |v| { FilterValue::Int(v as i64) },
    /// Filter for nullable `Int` columns.
    nullable IntNullableFilter
);

scalar_filter!(
    /// Filter for non-nullable `BigInt` (`i64`) columns.
    BigIntFilter<i64> => |v| { FilterValue::Int(v) },
    /// Filter for nullable `BigInt` columns.
    nullable BigIntNullableFilter
);

scalar_filter!(
    /// Filter for non-nullable `Float` (`f64`) columns.
    FloatFilter<f64> => |v| { FilterValue::Float(v) },
    /// Filter for nullable `Float` columns.
    nullable FloatNullableFilter
);

scalar_filter!(
    /// Filter for non-nullable `Decimal` (`rust_decimal::Decimal`) columns.
    ///
    /// Lowered as `FilterValue::String` because the runtime IR does not
    /// have a dedicated `Decimal` variant; the driver layer parses it on
    /// the wire.
    DecimalFilter<rust_decimal::Decimal> => |v| { FilterValue::String(v.to_string()) },
    /// Filter for nullable `Decimal` columns.
    nullable DecimalNullableFilter
);

scalar_filter!(
    /// Filter for non-nullable `Uuid` columns.
    UuidFilter<uuid::Uuid> => |v| { FilterValue::String(v.to_string()) },
    /// Filter for nullable `Uuid` columns.
    nullable UuidNullableFilter
);

scalar_filter!(
    /// Filter for non-nullable `Bytes` (`Vec<u8>`) columns.
    ///
    /// Encoded as a base64-of-bytes string in FilterValue::String. The
    /// driver layer decodes back to bytes on the wire.
    BytesFilter<Vec<u8>> => |v| {
        use base64::Engine as _;
        FilterValue::String(base64::engine::general_purpose::STANDARD.encode(&v))
    },
    /// Filter for nullable `Bytes` columns.
    nullable BytesNullableFilter
);

/// Filter operators for a non-nullable `Boolean` column.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct BoolFilter {
    /// `column = value`
    pub equals: Option<bool>,
    /// Negation of the inner filter.
    pub not: Option<Box<BoolFilter>>,
}

impl BoolFilter {
    /// `equals: Some(value)`.
    pub fn equals(v: bool) -> Self {
        Self {
            equals: Some(v),
            ..Default::default()
        }
    }
}

impl From<bool> for BoolFilter {
    fn from(v: bool) -> Self {
        Self::equals(v)
    }
}

impl ScalarFilter for BoolFilter {
    fn into_filter(self, column: &str) -> Filter {
        let col: crate::filter::FieldName = column.to_string().into();
        let mut parts: Vec<Filter> = Vec::new();
        if let Some(v) = self.equals {
            parts.push(Filter::Equals(col.clone(), FilterValue::Bool(v)));
        }
        if let Some(boxed) = self.not {
            parts.push(Filter::Not(Box::new(boxed.into_filter(column))));
        }
        combine_filters(parts)
    }
}

/// Filter operators for a nullable `Boolean` column.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct BoolNullableFilter {
    /// `column = value`
    pub equals: Option<bool>,
    /// Negation.
    pub not: Option<Box<BoolNullableFilter>>,
    /// IS NULL / IS NOT NULL.
    pub is_null: Option<bool>,
}

impl ScalarFilter for BoolNullableFilter {
    fn into_filter(self, column: &str) -> Filter {
        let mut parts: Vec<Filter> = Vec::new();
        if let Some(b) = self.is_null {
            parts.push(if b {
                Filter::IsNull(column.to_string().into())
            } else {
                Filter::IsNotNull(column.to_string().into())
            });
        }
        let inner = BoolFilter {
            equals: self.equals,
            not: self.not.map(|b| {
                Box::new(BoolFilter {
                    equals: b.equals,
                    not: None,
                })
            }),
        };
        let f = inner.into_filter(column);
        if !matches!(f, Filter::None) {
            parts.push(f);
        }
        combine_filters(parts)
    }
}

scalar_filter!(
    /// Filter for non-nullable `DateTime` columns (encoded RFC3339).
    DateTimeFilter<chrono::DateTime<chrono::Utc>> => |v| {
        FilterValue::String(v.to_rfc3339())
    },
    /// Filter for nullable `DateTime` columns.
    nullable DateTimeNullableFilter
);

scalar_filter!(
    /// Filter for non-nullable `Date` columns (encoded YYYY-MM-DD).
    DateFilter<chrono::NaiveDate> => |v| {
        FilterValue::String(v.to_string())
    },
    /// Filter for nullable `Date` columns.
    nullable DateNullableFilter
);

scalar_filter!(
    /// Filter for non-nullable `Time` columns (encoded HH:MM:SS).
    TimeFilter<chrono::NaiveTime> => |v| {
        FilterValue::String(v.format("%H:%M:%S").to_string())
    },
    /// Filter for nullable `Time` columns.
    nullable TimeNullableFilter
);

/// Filter operators for an enum-typed column.
///
/// `E` is the user-defined enum. Codegen emits `impl ToString for Role` so
/// the macro's bare-ident shorthand (`role: Admin`) flows through.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    rename_all = "snake_case",
    bound = "E: Serialize + for<'de2> Deserialize<'de2>"
)]
pub struct EnumFilter<E> {
    /// `column = value`
    pub equals: Option<E>,
    /// Negation.
    pub not: Option<Box<EnumFilter<E>>>,
    /// `column IN (...)`
    pub in_list: Option<Vec<E>>,
    /// `column NOT IN (...)`
    pub not_in: Option<Vec<E>>,
}

impl<E> EnumFilter<E> {
    /// `equals: Some(value)`.
    pub fn equals(v: E) -> Self {
        Self {
            equals: Some(v),
            not: None,
            in_list: None,
            not_in: None,
        }
    }
}

impl<E: ToString> ScalarFilter for EnumFilter<E> {
    fn into_filter(self, column: &str) -> Filter {
        let col: crate::filter::FieldName = column.to_string().into();
        let mut parts: Vec<Filter> = Vec::new();
        if let Some(v) = self.equals {
            parts.push(Filter::Equals(
                col.clone(),
                FilterValue::String(v.to_string()),
            ));
        }
        if let Some(boxed) = self.not {
            parts.push(Filter::Not(Box::new(boxed.into_filter(column))));
        }
        if let Some(values) = self.in_list {
            let vs: Vec<FilterValue> = values
                .into_iter()
                .map(|v| FilterValue::String(v.to_string()))
                .collect();
            parts.push(Filter::In(col.clone(), vs));
        }
        if let Some(values) = self.not_in {
            let vs: Vec<FilterValue> = values
                .into_iter()
                .map(|v| FilterValue::String(v.to_string()))
                .collect();
            parts.push(Filter::NotIn(col, vs));
        }
        combine_filters(parts)
    }
}

/// Filter operators for a nullable enum-typed column.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    rename_all = "snake_case",
    bound = "E: Serialize + for<'de2> Deserialize<'de2>"
)]
pub struct EnumNullableFilter<E> {
    /// `column = value`
    pub equals: Option<E>,
    /// Negation.
    pub not: Option<Box<EnumNullableFilter<E>>>,
    /// `column IN (...)`
    pub in_list: Option<Vec<E>>,
    /// `column NOT IN (...)`
    pub not_in: Option<Vec<E>>,
    /// IS NULL / IS NOT NULL.
    pub is_null: Option<bool>,
}

impl<E: ToString> ScalarFilter for EnumNullableFilter<E> {
    fn into_filter(self, column: &str) -> Filter {
        let mut parts: Vec<Filter> = Vec::new();
        if let Some(b) = self.is_null {
            parts.push(if b {
                Filter::IsNull(column.to_string().into())
            } else {
                Filter::IsNotNull(column.to_string().into())
            });
        }
        let inner = EnumFilter::<E> {
            equals: self.equals,
            not: self.not.map(|b| {
                Box::new(EnumFilter {
                    equals: b.equals,
                    in_list: b.in_list,
                    not_in: b.not_in,
                    not: None,
                })
            }),
            in_list: self.in_list,
            not_in: self.not_in,
        };
        let f = inner.into_filter(column);
        if !matches!(f, Filter::None) {
            parts.push(f);
        }
        combine_filters(parts)
    }
}

/// Filter operators for a non-nullable `Json` column.
///
/// Phase 1 supports `equals`/`not`. JSON-path operators land behind
/// `SupportsJsonPath` in a follow-up.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct JsonFilter {
    /// `column = value`
    pub equals: Option<serde_json::Value>,
    /// Negation.
    pub not: Option<Box<JsonFilter>>,
}

impl ScalarFilter for JsonFilter {
    fn into_filter(self, column: &str) -> Filter {
        let col: crate::filter::FieldName = column.to_string().into();
        let mut parts: Vec<Filter> = Vec::new();
        if let Some(v) = self.equals {
            parts.push(Filter::Equals(col.clone(), FilterValue::Json(v)));
        }
        if let Some(boxed) = self.not {
            parts.push(Filter::Not(Box::new(boxed.into_filter(column))));
        }
        combine_filters(parts)
    }
}

/// Filter operators for a nullable `Json` column.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct JsonNullableFilter {
    /// `column = value`
    pub equals: Option<serde_json::Value>,
    /// Negation.
    pub not: Option<Box<JsonNullableFilter>>,
    /// IS NULL / IS NOT NULL.
    pub is_null: Option<bool>,
}

impl ScalarFilter for JsonNullableFilter {
    fn into_filter(self, column: &str) -> Filter {
        let mut parts: Vec<Filter> = Vec::new();
        if let Some(b) = self.is_null {
            parts.push(if b {
                Filter::IsNull(column.to_string().into())
            } else {
                Filter::IsNotNull(column.to_string().into())
            });
        }
        let inner = JsonFilter {
            equals: self.equals,
            not: self.not.map(|b| {
                Box::new(JsonFilter {
                    equals: b.equals,
                    not: None,
                })
            }),
        };
        let f = inner.into_filter(column);
        if !matches!(f, Filter::None) {
            parts.push(f);
        }
        combine_filters(parts)
    }
}