toasty 0.7.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
use crate as toasty;
use crate::engine::test_util::*;
use crate::schema::Register;
use toasty_core::{
    schema::db,
    stmt::{self, Expr, Value},
};

use super::{Param, Ty, binary_like_prefix_pattern, extract_params, glob_prefix_pattern};

// ============================================================================
// Basic extraction
// ============================================================================

#[test]
fn extract_scalar_from_simple_insert() {
    #[derive(toasty::Model)]
    struct Item {
        #[key]
        id: String,
        name: String,
    }

    let schema = test_schema_with(&[Item::schema()]);

    // Build: INSERT INTO items (id, name) VALUES ('abc', 'hello')
    let mut stmt = stmt::Statement::Insert(stmt::Insert {
        target: insert_target(&schema, "items"),
        source: stmt::Query::values(stmt::Values::new(vec![Expr::from(Value::Record(
            stmt::ValueRecord::from_vec(vec![Value::from("abc"), Value::from("hello")]),
        ))])),
        returning: None,
    });

    let params = extract_params(&mut stmt, &schema, &toasty_core::driver::Capability::SQLITE);

    assert_eq!(params.len(), 2);
    assert_eq!(params[0].value, Value::from("abc"));
    assert_eq!(params[1].value, Value::from("hello"));

    // Statement should have Arg placeholders
    if let stmt::Statement::Insert(insert) = &stmt
        && let stmt::ExprSet::Values(values) = &insert.source.body
    {
        let row = &values.rows[0];
        assert!(matches!(row, Expr::Record(_)));
        if let Expr::Record(record) = row {
            assert!(matches!(record.fields[0], Expr::Arg(_)));
            assert!(matches!(record.fields[1], Expr::Arg(_)));
        }
    }
}

#[test]
fn null_values_not_extracted() {
    #[derive(toasty::Model)]
    struct Item {
        #[key]
        id: String,
        name: Option<String>,
    }

    let schema = test_schema_with(&[Item::schema()]);

    let mut stmt = stmt::Statement::Insert(stmt::Insert {
        target: insert_target(&schema, "items"),
        source: stmt::Query::values(stmt::Values::new(vec![Expr::from(Value::Record(
            stmt::ValueRecord::from_vec(vec![Value::from("abc"), Value::Null]),
        ))])),
        returning: None,
    });

    let params = extract_params(&mut stmt, &schema, &toasty_core::driver::Capability::SQLITE);

    // Only 'abc' should be extracted; NULL stays as literal
    assert_eq!(params.len(), 1);
    assert_eq!(params[0].value, Value::from("abc"));
}

#[test]
fn extract_from_where_clause() {
    let schema = test_schema();

    // Build: SELECT ... WHERE col = 'hello'
    let _filter_expr = Expr::BinaryOp(stmt::ExprBinaryOp {
        lhs: Box::new(Expr::Value(Value::from("hello"))),
        op: stmt::BinaryOp::Eq,
        rhs: Box::new(Expr::Value(Value::from(42i64))),
    });

    let mut stmt = stmt::Statement::Query(stmt::Query {
        with: None,
        body: stmt::ExprSet::Values(stmt::Values::new(vec![])),
        single: false,
        order_by: None,
        limit: None,
        locks: vec![],
    });

    // Can't easily build a full SELECT with filter without a schema,
    // but we can test that extract_params handles an empty query
    let params = extract_params(&mut stmt, &schema, &toasty_core::driver::Capability::SQLITE);
    assert_eq!(params.len(), 0);
}

// ============================================================================
// Type refinement for enums
// ============================================================================

#[test]
fn enum_insert_refines_type_to_enum() {
    #[derive(Debug, toasty::Embed)]
    enum Status {
        Active,
        Inactive,
    }

    #[derive(toasty::Model)]
    struct Task {
        #[key]
        id: String,
        status: Status,
    }

    let schema = test_schema_postgresql(&[Task::schema(), Status::schema()]);

    let mut stmt = stmt::Statement::Insert(stmt::Insert {
        target: insert_target(&schema, "tasks"),
        source: stmt::Query::values(stmt::Values::new(vec![Expr::from(Value::Record(
            stmt::ValueRecord::from_vec(vec![Value::from("task-1"), Value::from("active")]),
        ))])),
        returning: None,
    });

    let params = extract_params(&mut stmt, &schema, &toasty_core::driver::Capability::SQLITE);

    assert_eq!(params.len(), 2);

    // The status param should be refined to Enum type, not plain Text
    assert!(
        matches!(&params[1].ty, db::Type::Enum(_)),
        "expected Enum type for status param, got {:?}",
        params[1].ty
    );
}

#[test]
fn non_enum_insert_keeps_default_types() {
    #[derive(toasty::Model)]
    struct Item {
        #[key]
        id: String,
        count: i64,
    }

    let schema = test_schema_with(&[Item::schema()]);

    let mut stmt = stmt::Statement::Insert(stmt::Insert {
        target: insert_target(&schema, "items"),
        source: stmt::Query::values(stmt::Values::new(vec![Expr::from(Value::Record(
            stmt::ValueRecord::from_vec(vec![Value::from("item-1"), Value::from(42i64)]),
        ))])),
        returning: None,
    });

    let params = extract_params(&mut stmt, &schema, &toasty_core::driver::Capability::SQLITE);

    assert_eq!(params.len(), 2);
    assert!(matches!(&params[0].ty, db::Type::Text));
    assert!(matches!(&params[1].ty, db::Type::Integer(8)));
}

// ============================================================================
// Projection type inference
// ============================================================================

#[test]
fn synthesize_multi_step_projection() {
    // Test that a multi-step projection like project(record, [1, 0])
    // correctly walks through nested record types.
    //
    // Given: Record([Text, Record([Integer(4), Boolean])])
    // Project [1, 0] should yield Integer(4)

    use super::synthesize;

    let schema = test_schema();

    // Directly test the synthesize function with a constructed expression
    // that has a multi-step projection
    let mut params = vec![
        Param {
            value: Value::from("a"),
            ty: Ty::Inferred(db::Type::Text),
        },
        Param {
            value: Value::from(1i32),
            ty: Ty::Inferred(db::Type::Integer(4)),
        },
        Param {
            value: Value::from(true),
            ty: Ty::Inferred(db::Type::Boolean),
        },
    ];

    // Build: Record([Arg(0), Record([Arg(1), Arg(2)])])
    let expr = Expr::Record(stmt::ExprRecord::from_vec(vec![
        Expr::arg(0),
        Expr::Record(stmt::ExprRecord::from_vec(vec![Expr::arg(1), Expr::arg(2)])),
    ]));

    // Project with steps [1, 0] — field 1 of outer (inner record), then field 0 (Integer)
    let mut projection = stmt::Projection::single(1);
    projection.push(0);
    let project_expr = Expr::Project(stmt::ExprProject {
        base: Box::new(expr),
        projection,
    });

    let cx = stmt::ExprContext::new(&schema.db);
    let ty = synthesize(&project_expr, &cx, &mut params);

    assert!(
        matches!(ty, Ty::Inferred(db::Type::Integer(4))),
        "expected Inferred(Integer(4)), got {:?}",
        ty
    );
}

// ============================================================================
// Invalid state panics
// ============================================================================

#[test]
#[should_panic(expected = "index out of bounds")]
fn synthesize_arg_out_of_range_panics() {
    use super::synthesize;

    let schema = test_schema();
    let cx = stmt::ExprContext::new(&schema.db);
    let mut params = vec![];

    // Arg(5) but params is empty
    synthesize(&Expr::arg(5), &cx, &mut params);
}

#[test]
#[should_panic(expected = "out of range")]
fn synthesize_project_step_out_of_bounds_panics() {
    use super::synthesize;

    let schema = test_schema();
    let cx = stmt::ExprContext::new(&schema.db);
    let mut params = vec![Param {
        value: Value::from("a"),
        ty: Ty::Inferred(db::Type::Text),
    }];

    // Record with 1 field, projecting step 5
    let expr = Expr::Project(stmt::ExprProject {
        base: Box::new(Expr::Record(stmt::ExprRecord::from_vec(vec![Expr::arg(0)]))),
        projection: stmt::Projection::single(5),
    });

    synthesize(&expr, &cx, &mut params);
}

#[test]
#[should_panic(expected = "non-record")]
fn synthesize_project_from_scalar_panics() {
    use super::synthesize;

    let schema = test_schema();
    let cx = stmt::ExprContext::new(&schema.db);
    let mut params = vec![Param {
        value: Value::from(42i64),
        ty: Ty::Inferred(db::Type::Integer(8)),
    }];

    // Project from a scalar Arg (not a record)
    let expr = Expr::Project(stmt::ExprProject {
        base: Box::new(Expr::arg(0)),
        projection: stmt::Projection::single(0),
    });

    synthesize(&expr, &cx, &mut params);
}

#[test]
#[should_panic(expected = "incompatible")]
fn merge_incompatible_structures_panics() {
    use super::{Ty, merge};

    // Record vs Inferred scalar
    let a = Ty::Record(vec![Ty::Inferred(db::Type::Text)]);
    let b = Ty::Inferred(db::Type::Integer(8));

    merge(&a, &b);
}

#[test]
#[should_panic(expected = "incompatible")]
fn merge_records_different_lengths_panics() {
    use super::{Ty, merge};

    let a = Ty::Record(vec![Ty::Inferred(db::Type::Text)]);
    let b = Ty::Record(vec![
        Ty::Inferred(db::Type::Text),
        Ty::Inferred(db::Type::Integer(8)),
    ]);

    merge(&a, &b);
}

#[test]
fn merge_column_wins_over_inferred() {
    use super::{Ty, merge};

    let col = Ty::Column(db::Type::Enum(db::TypeEnum {
        name: Some("status".to_string()),
        variants: vec![],
    }));
    let inferred = Ty::Inferred(db::Type::Text);

    // Column should win regardless of argument order
    let result = merge(&col, &inferred);
    assert!(result.is_column(), "expected Column, got {:?}", result);

    let result = merge(&inferred, &col);
    assert!(result.is_column(), "expected Column, got {:?}", result);
}

// ============================================================================
// Helpers
// ============================================================================

/// Build an InsertTarget::Table for the named table in the schema.
fn insert_target(schema: &toasty_core::Schema, table_name: &str) -> stmt::InsertTarget {
    let table = schema
        .db
        .tables
        .iter()
        .find(|t| t.name.ends_with(table_name))
        .unwrap_or_else(|| panic!("table '{table_name}' not found in schema"));

    stmt::InsertTarget::Table(stmt::InsertTable {
        table: table.id,
        columns: table.columns.iter().map(|c| c.id).collect(),
    })
}

// ============================================================================
// glob_prefix_pattern
// ============================================================================

#[test]
fn glob_plain_prefix() {
    assert_eq!(glob_prefix_pattern("alpha"), "alpha*");
}

#[test]
fn glob_empty_prefix() {
    assert_eq!(glob_prefix_pattern(""), "*");
}

#[test]
fn glob_escapes_star() {
    assert_eq!(glob_prefix_pattern("100*off"), "100[*]off*");
}

#[test]
fn glob_escapes_question_mark() {
    assert_eq!(glob_prefix_pattern("a?b"), "a[?]b*");
}

#[test]
fn glob_escapes_open_bracket() {
    assert_eq!(glob_prefix_pattern("a[b"), "a[[]b*");
}

#[test]
fn glob_like_wildcards_are_literal() {
    // `%` and `_` are LIKE wildcards but not GLOB metacharacters.
    assert_eq!(glob_prefix_pattern("100%"), "100%*");
    assert_eq!(glob_prefix_pattern("a_b"), "a_b*");
}

// ============================================================================
// binary_like_prefix_pattern
// ============================================================================

#[test]
fn binary_like_plain_prefix() {
    assert_eq!(binary_like_prefix_pattern("alpha"), "alpha%");
}

#[test]
fn binary_like_empty_prefix() {
    assert_eq!(binary_like_prefix_pattern(""), "%");
}

#[test]
fn binary_like_escapes_percent() {
    assert_eq!(binary_like_prefix_pattern("100%"), "100!%%");
}

#[test]
fn binary_like_escapes_underscore() {
    assert_eq!(binary_like_prefix_pattern("a_b"), "a!_b%");
}

#[test]
fn binary_like_escapes_escape_char() {
    assert_eq!(binary_like_prefix_pattern("!bang"), "!!bang%");
}

#[test]
fn binary_like_glob_wildcards_are_literal() {
    // `*` and `?` are GLOB metacharacters but not LIKE metacharacters.
    assert_eq!(binary_like_prefix_pattern("foo*"), "foo*%");
    assert_eq!(binary_like_prefix_pattern("a?b"), "a?b%");
}