aip-160 0.1.1

A Rust implementation of Google AIP-160 filtering standard.
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
/// SeaORM integration
#[cfg(feature = "sea-orm")]
use sea_orm::{sea_query::{SimpleExpr, ExprTrait}, Condition};

use crate::ast::{Comparator, Expression, Filter, Restriction, Value};
use crate::error::{FilterError, Result};

/// Helper function to convert a field name to a column
///
/// Supports both exact matches and snake_case to PascalCase conversion.
pub fn column_from_str<C>(field: &str) -> Result<SimpleExpr>
where
    C: std::str::FromStr + sea_orm::IntoSimpleExpr,
    <C as std::str::FromStr>::Err: std::fmt::Display,
{
    // Try direct conversion first
    if let Ok(column) = field.parse::<C>() {
        return Ok(column.into_simple_expr());
    }

    // Try PascalCase conversion: "user_name" -> "UserName"
    let pascal_case = field
        .split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect::<String>();

    pascal_case
        .parse::<C>()
        .map(|c| c.into_simple_expr())
        .map_err(|e| FilterError::InvalidField(format!("{}: {}", field, e)))
}

/// Convert a filter to a SeaORM Condition
///
/// # Example
///
/// ```ignore
/// use aip_160::{parse_filter, ToSeaOrmCondition};
/// use sea_orm::entity::prelude::*;
///
/// let filter = parse_filter("name = \"Alice\" AND age > 18")?;
/// let condition = filter.to_condition::<Column>()?;
///
/// Entity::find().filter(condition).all(db).await?;
/// ```
pub trait ToSeaOrmCondition {
    fn to_condition<C>(&self) -> Result<Condition>
    where
        C: std::str::FromStr + sea_orm::IntoSimpleExpr,
        <C as std::str::FromStr>::Err: std::fmt::Display;
}

impl ToSeaOrmCondition for Filter {
    fn to_condition<C>(&self) -> Result<Condition>
    where
        C: std::str::FromStr + sea_orm::IntoSimpleExpr,
        <C as std::str::FromStr>::Err: std::fmt::Display,
    {
        expression_to_condition::<C>(&self.expression)
    }
}

fn expression_to_condition<C>(expr: &Expression) -> Result<Condition>
where
    C: std::str::FromStr + sea_orm::IntoSimpleExpr,
    <C as std::str::FromStr>::Err: std::fmt::Display,
{
    match expr {
        Expression::And(left, right) => {
            let left_cond = expression_to_condition::<C>(left)?;
            let right_cond = expression_to_condition::<C>(right)?;
            Ok(Condition::all().add(left_cond).add(right_cond))
        }
        Expression::Or(left, right) => {
            let left_cond = expression_to_condition::<C>(left)?;
            let right_cond = expression_to_condition::<C>(right)?;
            Ok(Condition::any().add(left_cond).add(right_cond))
        }
        Expression::Not(inner) => {
            let inner_cond = expression_to_condition::<C>(inner)?;
            Ok(inner_cond.not())
        }
        Expression::Restriction(restriction) => {
            restriction_to_condition::<C>(restriction)
        }
        Expression::Sequence(_) => {
            Err(FilterError::UnsupportedOperation(
                "Sequences are not yet supported in SeaORM conversion".to_string(),
            ))
        }
    }
}

fn restriction_to_condition<C>(restriction: &Restriction) -> Result<Condition>
where
    C: std::str::FromStr + sea_orm::IntoSimpleExpr,
    <C as std::str::FromStr>::Err: std::fmt::Display,
{
    let column = column_from_str::<C>(&restriction.field)?;

    let condition = match (&restriction.comparator, &restriction.value) {
        (Comparator::Equal, Value::String(s)) => {
            Condition::all().add(column.eq(s.as_str()))
        }
        (Comparator::Equal, Value::Number(n)) => {
            if n.fract() == 0.0 {
                Condition::all().add(column.eq(*n as i64))
            } else {
                Condition::all().add(column.eq(*n))
            }
        }
        (Comparator::Equal, Value::Boolean(b)) => {
            Condition::all().add(column.eq(*b))
        }
        (Comparator::Equal, Value::Null) => {
            Condition::all().add(column.is_null())
        }

        (Comparator::NotEqual, Value::String(s)) => {
            Condition::all().add(column.ne(s.as_str()))
        }
        (Comparator::NotEqual, Value::Number(n)) => {
            if n.fract() == 0.0 {
                Condition::all().add(column.ne(*n as i64))
            } else {
                Condition::all().add(column.ne(*n))
            }
        }
        (Comparator::NotEqual, Value::Boolean(b)) => {
            Condition::all().add(column.ne(*b))
        }
        (Comparator::NotEqual, Value::Null) => {
            Condition::all().add(column.is_not_null())
        }

        (Comparator::GreaterThan, Value::Number(n)) => {
            if n.fract() == 0.0 {
                Condition::all().add(column.gt(*n as i64))
            } else {
                Condition::all().add(column.gt(*n))
            }
        }
        (Comparator::GreaterThan, Value::String(s)) => {
            Condition::all().add(column.gt(s.as_str()))
        }

        (Comparator::GreaterThanOrEqual, Value::Number(n)) => {
            if n.fract() == 0.0 {
                Condition::all().add(column.gte(*n as i64))
            } else {
                Condition::all().add(column.gte(*n))
            }
        }
        (Comparator::GreaterThanOrEqual, Value::String(s)) => {
            Condition::all().add(column.gte(s.as_str()))
        }

        (Comparator::LessThan, Value::Number(n)) => {
            if n.fract() == 0.0 {
                Condition::all().add(column.lt(*n as i64))
            } else {
                Condition::all().add(column.lt(*n))
            }
        }
        (Comparator::LessThan, Value::String(s)) => {
            Condition::all().add(column.lt(s.as_str()))
        }

        (Comparator::LessThanOrEqual, Value::Number(n)) => {
            if n.fract() == 0.0 {
                Condition::all().add(column.lte(*n as i64))
            } else {
                Condition::all().add(column.lte(*n))
            }
        }
        (Comparator::LessThanOrEqual, Value::String(s)) => {
            Condition::all().add(column.lte(s.as_str()))
        }

        (Comparator::Has, Value::String(s)) => {
            Condition::all().add(column.like(format!("%{}%", s)))
        }

        _ => {
            return Err(FilterError::UnsupportedOperation(format!(
                "Unsupported combination: {} with {:?}",
                restriction.comparator, restriction.value
            )))
        }
    };

    Ok(condition)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse_filter;
    use sea_orm::sea_query::{Iden, SimpleExpr};

    // Mock Column enum for testing
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Column {
        Id,
        Name,
        Email,
        Age,
        Active,
        CreatedAt,
        UserName,  // For testing snake_case to PascalCase conversion
    }

    impl std::str::FromStr for Column {
        type Err = String;

        fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
            match s {
                "Id" => Ok(Column::Id),
                "Name" => Ok(Column::Name),
                "Email" => Ok(Column::Email),
                "Age" => Ok(Column::Age),
                "Active" => Ok(Column::Active),
                "CreatedAt" => Ok(Column::CreatedAt),
                "UserName" => Ok(Column::UserName),
                _ => Err(format!("Unknown column: {}", s)),
            }
        }
    }

    impl Iden for Column {
        fn unquoted(&self, s: &mut dyn std::fmt::Write) {
            write!(
                s,
                "{}",
                match self {
                    Column::Id => "id",
                    Column::Name => "name",
                    Column::Email => "email",
                    Column::Age => "age",
                    Column::Active => "active",
                    Column::CreatedAt => "created_at",
                    Column::UserName => "user_name",
                }
            )
            .unwrap();
        }
    }

    impl sea_orm::IntoSimpleExpr for Column {
        fn into_simple_expr(self) -> SimpleExpr {
            SimpleExpr::Column(sea_orm::sea_query::ColumnRef::Column(
                sea_orm::sea_query::DynIden::new(self),
            ))
        }
    }

    #[test]
    fn test_simple_string_filter() {
        let filter = parse_filter("name = \"John\"").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_number_filter() {
        let filter = parse_filter("age > 18").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_float_number_filter() {
        let filter = parse_filter("age > 18.5").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_boolean_filter() {
        let filter = parse_filter("active = true").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_null_filter() {
        let filter = parse_filter("email = NULL").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_not_null_filter() {
        let filter = parse_filter("email != NULL").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_and_expression() {
        let filter = parse_filter("age > 18 AND active = true").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_or_expression() {
        let filter = parse_filter("name = \"John\" OR name = \"Jane\"").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_not_expression() {
        let filter = parse_filter("NOT active = false").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_has_operator() {
        let filter = parse_filter("email : \"@example.com\"").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_complex_filter() {
        let filter = parse_filter(
            "(name = \"Alice\" OR name = \"Bob\") AND age >= 21 AND active = true",
        )
        .unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_all_comparators() {
        let test_cases = vec![
            ("age = 25", true),
            ("age != 30", true),
            ("age > 20", true),
            ("age >= 21", true),
            ("age < 50", true),
            ("age <= 49", true),
            ("name : \"John\"", true),
        ];

        for (filter_str, should_succeed) in test_cases {
            let filter = parse_filter(filter_str).unwrap();
            let result = filter.to_condition::<Column>();
            assert_eq!(result.is_ok(), should_succeed, "Failed on: {}", filter_str);
        }
    }

    #[test]
    fn test_snake_case_to_pascal_case_conversion() {
        let filter = parse_filter("user_name = \"test\"").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_created_at_snake_case() {
        let filter = parse_filter("created_at > \"2024-01-01\"").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_ok());
    }

    #[test]
    fn test_invalid_field() {
        let filter = parse_filter("invalid_field = \"value\"").unwrap();
        let condition = filter.to_condition::<Column>();
        assert!(condition.is_err());
    }

    #[test]
    fn test_unsupported_sequence() {
        // Currently, the parser doesn't support dot notation for nested fields
        // This should fail at the parsing stage
        let result = parse_filter("user.profile.name = \"John\"");
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.to_string().contains("expected comparator"));
        }
    }

    #[test]
    fn test_not_equal_variations() {
        let test_cases = vec![
            "name != \"John\"",
            "age != 25",
            "active != true",
            "email != NULL",
        ];

        for filter_str in test_cases {
            let filter = parse_filter(filter_str).unwrap();
            let condition = filter.to_condition::<Column>();
            assert!(condition.is_ok(), "Failed on: {}", filter_str);
        }
    }

    #[test]
    fn test_string_comparisons() {
        let test_cases = vec![
            "name > \"Alice\"",
            "name >= \"Bob\"",
            "name < \"Zebra\"",
            "name <= \"Zoe\"",
        ];

        for filter_str in test_cases {
            let filter = parse_filter(filter_str).unwrap();
            let condition = filter.to_condition::<Column>();
            assert!(condition.is_ok(), "Failed on: {}", filter_str);
        }
    }
}