toasty 0.6.0

An async ORM for Rust supporting SQL and NoSQL databases
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
use crate as toasty;
use crate::engine::simplify::Simplify;
use crate::schema::Register;
use toasty_core::{
    driver::Capability,
    schema::{Builder, app},
    stmt::{BinaryOp, Expr, ExprCast, ExprReference, MatchArm, Type, Value, ValueRecord, VisitMut},
};

#[derive(toasty::Model)]
struct User {
    #[key]
    id: String,

    #[allow(dead_code)]
    name: Option<String>,
}

fn test_schema() -> toasty_core::Schema {
    let app_schema =
        app::Schema::from_macro([User::schema()]).expect("schema should build from macro");

    Builder::new()
        .build(app_schema, &Capability::SQLITE)
        .expect("schema should build")
}

#[test]
fn non_id_cast_not_unwrapped() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // `eq(cast(arg(0), String), "test")`, non-Id cast is not unwrapped
    let mut lhs = Expr::Cast(ExprCast {
        expr: Box::new(Expr::arg(0)),
        ty: Type::String,
    });
    let mut rhs = Expr::Value(Value::from("test"));

    let result = simplify.simplify_expr_binary_op(BinaryOp::Eq, &mut lhs, &mut rhs);

    assert!(result.is_none());
    assert!(matches!(lhs, Expr::Cast(_)));
}

#[test]
fn self_comparison_eq_non_nullable_becomes_true() {
    let schema = test_schema();
    let model = schema.app.model(User::id());
    let simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);
    let mut simplify = simplify.scope(model.as_root_unwrap());

    // `id = id` → `true` (non-nullable field)
    let mut lhs = Expr::Reference(ExprReference::Field {
        nesting: 0,
        index: 0,
    });
    let mut rhs = Expr::Reference(ExprReference::Field {
        nesting: 0,
        index: 0,
    });

    let result = simplify.simplify_expr_binary_op(BinaryOp::Eq, &mut lhs, &mut rhs);

    assert!(matches!(result, Some(Expr::Value(Value::Bool(true)))));
}

#[test]
fn self_comparison_ne_non_nullable_becomes_false() {
    let schema = test_schema();
    let model = schema.app.model(User::id());
    let simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);
    let mut simplify = simplify.scope(model.as_root_unwrap());

    // `id != id` → `false` (non-nullable field)
    let mut lhs = Expr::Reference(ExprReference::Field {
        nesting: 0,
        index: 0,
    });
    let mut rhs = Expr::Reference(ExprReference::Field {
        nesting: 0,
        index: 0,
    });

    let result = simplify.simplify_expr_binary_op(BinaryOp::Ne, &mut lhs, &mut rhs);

    assert!(matches!(result, Some(Expr::Value(Value::Bool(false)))));
}

#[test]
fn self_comparison_nullable_not_simplified() {
    let schema = test_schema();
    let model = schema.app.model(User::id());
    let simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);
    let mut simplify = simplify.scope(model.as_root_unwrap());

    // `name = name` is not simplified (nullable field)
    let mut lhs = Expr::Reference(ExprReference::Field {
        nesting: 0,
        index: 1,
    });
    let mut rhs = Expr::Reference(ExprReference::Field {
        nesting: 0,
        index: 1,
    });

    let result = simplify.simplify_expr_binary_op(BinaryOp::Eq, &mut lhs, &mut rhs);

    assert!(result.is_none());
}

#[test]
fn different_fields_not_simplified() {
    let schema = test_schema();
    let model = schema.app.model(User::id());
    let simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);
    let mut simplify = simplify.scope(model.as_root_unwrap());

    // `id = name` is not simplified (different fields)
    let mut lhs = Expr::Reference(ExprReference::Field {
        nesting: 0,
        index: 0,
    });
    let mut rhs = Expr::Reference(ExprReference::Field {
        nesting: 0,
        index: 1,
    });

    let result = simplify.simplify_expr_binary_op(BinaryOp::Eq, &mut lhs, &mut rhs);

    assert!(result.is_none());
}

#[test]
fn tuple_eq_decomposition_two_elements() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // `(a, b) = (x, y)` → `a = x and b = y`
    let mut lhs = Expr::record([Expr::arg(0), Expr::arg(1)]);
    let mut rhs = Expr::record([Expr::arg(2), Expr::arg(3)]);

    let result = simplify.simplify_expr_binary_op(BinaryOp::Eq, &mut lhs, &mut rhs);

    let Some(Expr::And(and_expr)) = result else {
        panic!("expected And expression");
    };
    assert_eq!(and_expr.len(), 2);
    assert!(matches!(&and_expr[0], Expr::BinaryOp(op) if op.op.is_eq()));
    assert!(matches!(&and_expr[1], Expr::BinaryOp(op) if op.op.is_eq()));
}

#[test]
fn tuple_eq_decomposition_three_elements() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // `(a, b, c) = (x, y, z)` → `a = x and b = y and c = z`
    let mut lhs = Expr::record([Expr::arg(0), Expr::arg(1), Expr::arg(2)]);
    let mut rhs = Expr::record([Expr::arg(3), Expr::arg(4), Expr::arg(5)]);

    let result = simplify.simplify_expr_binary_op(BinaryOp::Eq, &mut lhs, &mut rhs);

    let Some(Expr::And(and_expr)) = result else {
        panic!("expected And expression");
    };
    assert_eq!(and_expr.len(), 3);
}

#[test]
fn tuple_ne_decomposition() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // `(a, b) != (x, y)` → `a != x or b != y`
    let mut lhs = Expr::record([Expr::arg(0), Expr::arg(1)]);
    let mut rhs = Expr::record([Expr::arg(2), Expr::arg(3)]);

    let result = simplify.simplify_expr_binary_op(BinaryOp::Ne, &mut lhs, &mut rhs);

    let Some(Expr::Or(or_expr)) = result else {
        panic!("expected Or expression");
    };
    assert_eq!(or_expr.len(), 2);
    assert!(matches!(&or_expr[0], Expr::BinaryOp(op) if op.op.is_ne()));
    assert!(matches!(&or_expr[1], Expr::BinaryOp(op) if op.op.is_ne()));
}

#[test]
fn single_element_tuple_eq() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // `(a) = (x)` → `a = x`
    let mut lhs = Expr::record([Expr::arg(0)]);
    let mut rhs = Expr::record([Expr::arg(1)]);

    let result = simplify.simplify_expr_binary_op(BinaryOp::Eq, &mut lhs, &mut rhs);
    assert!(matches!(result, Some(Expr::BinaryOp(op)) if op.op.is_eq()));
}

// --- Match elimination tests ---

#[test]
fn match_eq_constant_value() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // Match(col, [1 => Record([col, addr]), 2 => Record([col, num])],
    //       else: Record([col, Error])) == Value(Record([I64(1), "alice"]))
    // → col == 1 AND addr == "alice"
    //
    // The else branch uses Record([col, Error]) matching the real-world
    // data-carrying enum pattern. Tuple decomposition produces col == I64(1)
    // which contradicts the NOT(col == 1) guard, so the complement law
    // folds the else term to false.
    let mut expr = Expr::binary_op(
        Expr::match_expr(
            Expr::arg(0),
            vec![
                MatchArm {
                    pattern: Value::from(1i64),
                    expr: Expr::record([Expr::arg(0), Expr::arg(1)]),
                },
                MatchArm {
                    pattern: Value::from(2i64),
                    expr: Expr::record([Expr::arg(0), Expr::arg(2)]),
                },
            ],
            Expr::record([Expr::arg(0), Expr::error("unreachable")]),
        ),
        BinaryOp::Eq,
        Expr::from(Value::Record(ValueRecord::from_vec(vec![
            Value::from(1i64),
            Value::from("alice"),
        ]))),
    );

    simplify.visit_expr_mut(&mut expr);

    // Should be: arg(0) == 1 AND arg(1) == "alice"
    let Expr::And(and) = &expr else {
        panic!("expected And, got {expr:?}");
    };
    assert_eq!(and.len(), 2);
}

#[test]
fn match_eq_scalar_folds_matching_arm() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // Match(arg(0), [1 => "a", 2 => "b"], else: "__") == "a" → arg(0) == 1
    // The else value "__" != "a" folds to false, pruning the else term.
    let mut expr = Expr::binary_op(
        Expr::match_expr(
            Expr::arg(0),
            vec![
                MatchArm {
                    pattern: Value::from(1i64),
                    expr: Expr::from("a"),
                },
                MatchArm {
                    pattern: Value::from(2i64),
                    expr: Expr::from("b"),
                },
            ],
            Expr::from("__"),
        ),
        BinaryOp::Eq,
        Expr::from("a"),
    );

    simplify.visit_expr_mut(&mut expr);

    // Only arm 1 survives (arm 2: "b" == "a" → false, pruned)
    // Result: arg(0) == 1
    let Expr::BinaryOp(binop) = &expr else {
        panic!("expected BinaryOp, got {expr:?}");
    };
    assert!(binop.op.is_eq());
    assert!(matches!(*binop.lhs, Expr::Arg(_)));
    assert!(matches!(*binop.rhs, Expr::Value(Value::I64(1))));
}

#[test]
fn match_eq_no_matching_arm_folds_to_false() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // Match(arg(0), [1 => "a", 2 => "b"], else: "__") == "c" → false (all arms pruned)
    // The else value "__" != "c" folds to false, pruning the else term too.
    let mut expr = Expr::binary_op(
        Expr::match_expr(
            Expr::arg(0),
            vec![
                MatchArm {
                    pattern: Value::from(1i64),
                    expr: Expr::from("a"),
                },
                MatchArm {
                    pattern: Value::from(2i64),
                    expr: Expr::from("b"),
                },
            ],
            Expr::from("__"),
        ),
        BinaryOp::Eq,
        Expr::from("c"),
    );

    simplify.visit_expr_mut(&mut expr);

    assert!(expr.is_false(), "expected false, got {expr:?}");
}

#[test]
fn match_on_rhs() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // "a" == Match(arg(0), [1 => "a", 2 => "b"], else: "__") → arg(0) == 1
    let mut expr = Expr::binary_op(
        Expr::from("a"),
        BinaryOp::Eq,
        Expr::match_expr(
            Expr::arg(0),
            vec![
                MatchArm {
                    pattern: Value::from(1i64),
                    expr: Expr::from("a"),
                },
                MatchArm {
                    pattern: Value::from(2i64),
                    expr: Expr::from("b"),
                },
            ],
            Expr::from("__"),
        ),
    );

    simplify.visit_expr_mut(&mut expr);

    // Only arm 1 survives
    let Expr::BinaryOp(binop) = &expr else {
        panic!("expected BinaryOp, got {expr:?}");
    };
    assert!(binop.op.is_eq());
    assert!(matches!(*binop.lhs, Expr::Arg(_)));
    assert!(matches!(*binop.rhs, Expr::Value(Value::I64(1))));
}

#[test]
fn match_ne_preserves_non_matching_arms() {
    let schema = test_schema();
    let mut simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);

    // Match(arg(0), [1 => "a", 2 => "b"], else: "a") != "a"
    // arm 1: arg(0) == 1 AND "a" != "a" → false → pruned
    // arm 2: arg(0) == 2 AND "b" != "a" → arg(0) == 2
    // else:  NOT(arg(0)==1) AND NOT(arg(0)==2) AND "a" != "a" → false → pruned
    let mut expr = Expr::binary_op(
        Expr::match_expr(
            Expr::arg(0),
            vec![
                MatchArm {
                    pattern: Value::from(1i64),
                    expr: Expr::from("a"),
                },
                MatchArm {
                    pattern: Value::from(2i64),
                    expr: Expr::from("b"),
                },
            ],
            Expr::from("a"),
        ),
        BinaryOp::Ne,
        Expr::from("a"),
    );

    simplify.visit_expr_mut(&mut expr);

    // Only arm 2 survives → arg(0) == 2
    let Expr::BinaryOp(binop) = &expr else {
        panic!("expected BinaryOp, got {expr:?}");
    };
    assert!(binop.op.is_eq());
    assert!(matches!(*binop.lhs, Expr::Arg(_)));
    assert!(matches!(*binop.rhs, Expr::Value(Value::I64(2))));
}

#[test]
fn match_with_non_constant_subject() {
    let schema = test_schema();
    let model = schema.app.model(User::id());
    let simplify = Simplify::new(&schema, &toasty_core::driver::Capability::SQLITE);
    let mut simplify = simplify.scope(model.as_root_unwrap());

    // Match over a column reference (the real-world case)
    // Match(field[0], [1 => "a", 2 => "b"], else: "__") == "a"
    let subject = Expr::Reference(ExprReference::Field {
        nesting: 0,
        index: 0,
    });

    let mut expr = Expr::binary_op(
        Expr::match_expr(
            subject,
            vec![
                MatchArm {
                    pattern: Value::from(1i64),
                    expr: Expr::from("a"),
                },
                MatchArm {
                    pattern: Value::from(2i64),
                    expr: Expr::from("b"),
                },
            ],
            Expr::from("__"),
        ),
        BinaryOp::Eq,
        Expr::from("a"),
    );

    simplify.visit_expr_mut(&mut expr);

    // Only arm 1 survives. The guard becomes field[0] == 1.
    // The exact shape depends on canonicalization, but there should be no Match left.
    assert!(
        !matches!(&expr, Expr::Match(_)),
        "Match should be eliminated, got {expr:?}"
    );
}