toasty-driver-integration-suite 0.5.0

Integration test suite for Toasty database drivers
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
use crate::prelude::*;

/// Verifies that a data-carrying enum has its variant fields registered in the app
/// schema with globally-assigned field indices (indices are unique across all variants).
#[driver_test]
pub async fn data_carrying_enum_schema(test: &mut Test) {
    #[allow(dead_code)]
    #[derive(toasty::Embed)]
    enum ContactInfo {
        #[column(variant = 1)]
        Email { address: String },
        #[column(variant = 2)]
        Phone { number: String },
    }

    let db = test.setup_db(models!(ContactInfo)).await;
    let schema = db.schema();

    assert_struct!(schema.app.models, #{
        ContactInfo::id(): toasty::schema::app::Model::EmbeddedEnum({
            name.upper_camel_case(): "ContactInfo",
            variants: [
                {
                    name.upper_camel_case(): "Email",
                    discriminant: toasty_core::stmt::Value::I64(1),
                    ..
                },
                {
                    name.upper_camel_case(): "Phone",
                    discriminant: toasty_core::stmt::Value::I64(2),
                    ..
                },
            ],
            fields: [
                { id.index: 0, name.app: Some("address") },
                { id.index: 1, name.app: Some("number") },
            ],
        }),
    });
}

/// Verifies that a mixed enum (some unit variants, some data variants) registers
/// correctly: unit variants have empty `fields`, data variants have their fields
/// with indices assigned starting from 0 and continuing globally across variants.
#[driver_test]
pub async fn mixed_enum_schema(test: &mut Test) {
    #[allow(dead_code)]
    #[derive(toasty::Embed)]
    enum Status {
        #[column(variant = 1)]
        Pending,
        #[column(variant = 2)]
        Failed { reason: String },
        #[column(variant = 3)]
        Done,
    }

    let db = test.setup_db(models!(Status)).await;
    let schema = db.schema();

    assert_struct!(schema.app.models, #{
        Status::id(): toasty::schema::app::Model::EmbeddedEnum({
            variants: [
                {
                    name.upper_camel_case(): "Pending",
                    discriminant: toasty_core::stmt::Value::I64(1),
                    ..
                },
                {
                    name.upper_camel_case(): "Failed",
                    discriminant: toasty_core::stmt::Value::I64(2),
                    ..
                },
                {
                    name.upper_camel_case(): "Done",
                    discriminant: toasty_core::stmt::Value::I64(3),
                    ..
                },
            ],
            fields: [
                { id.index: 0, name.app: Some("reason") },
            ],
        }),
    });
}

/// Verifies DB columns for a data-carrying enum: discriminant column + one nullable
/// column per variant field, named `{disc_col}_{field_name}`.
#[driver_test]
pub async fn data_carrying_enum_db_schema(test: &mut Test) {
    #[allow(dead_code)]
    #[derive(toasty::Embed)]
    enum ContactInfo {
        #[column(variant = 1)]
        Email { address: String },
        #[column(variant = 2)]
        Phone { number: String },
    }

    #[derive(toasty::Model)]
    struct User {
        #[key]
        id: String,
        #[allow(dead_code)]
        contact: ContactInfo,
    }

    let db = test.setup_db(models!(User, ContactInfo)).await;
    let schema = db.schema();

    // The DB table has disc col + one col per variant field (2 variants × 1 field each).
    assert_struct!(schema.db.tables, [
        {
            name: =~ r"users$",
            columns: [
                { name: "id" },
                { name: "contact", nullable: false },
                { name: "contact_address", nullable: true },
                { name: "contact_number", nullable: true },
            ],
        },
    ]);
}

/// End-to-end CRUD test for a data-carrying enum (all variants have fields).
/// Creates records with different variants, reads them back, and verifies roundtrip.
#[driver_test]
pub async fn data_variant_roundtrip(test: &mut Test) -> Result<()> {
    #[derive(Debug, PartialEq, toasty::Embed)]
    enum ContactInfo {
        #[column(variant = 1)]
        Email { address: String },
        #[column(variant = 2)]
        Phone { number: String },
    }

    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: uuid::Uuid,
        name: String,
        contact: ContactInfo,
    }

    let mut db = test.setup_db(models!(User, ContactInfo)).await;

    let alice = User::create()
        .name("Alice")
        .contact(ContactInfo::Email {
            address: "alice@example.com".to_string(),
        })
        .exec(&mut db)
        .await?;

    let bob = User::create()
        .name("Bob")
        .contact(ContactInfo::Phone {
            number: "555-1234".to_string(),
        })
        .exec(&mut db)
        .await?;

    // Read back and check values are reconstructed correctly.
    let found_alice = User::get_by_id(&mut db, &alice.id).await?;
    assert_eq!(
        found_alice.contact,
        ContactInfo::Email {
            address: "alice@example.com".to_string()
        }
    );

    let found_bob = User::get_by_id(&mut db, &bob.id).await?;
    assert_eq!(
        found_bob.contact,
        ContactInfo::Phone {
            number: "555-1234".to_string()
        }
    );

    // Clean up.
    alice.delete().exec(&mut db).await?;
    bob.delete().exec(&mut db).await?;
    Ok(())
}

/// End-to-end CRUD test for a mixed enum (unit variants and data variants).
/// Verifies that both kinds round-trip correctly through the DB.
#[driver_test]
pub async fn mixed_enum_roundtrip(test: &mut Test) -> Result<()> {
    #[derive(Debug, PartialEq, toasty::Embed)]
    enum Status {
        #[column(variant = 1)]
        Pending,
        #[column(variant = 2)]
        Failed { reason: String },
        #[column(variant = 3)]
        Done,
    }

    #[derive(Debug, toasty::Model)]
    struct Task {
        #[key]
        #[auto]
        id: uuid::Uuid,
        title: String,
        status: Status,
    }

    let mut db = test.setup_db(models!(Task, Status)).await;

    let pending = Task::create()
        .title("Pending task")
        .status(Status::Pending)
        .exec(&mut db)
        .await?;

    let failed = Task::create()
        .title("Failed task")
        .status(Status::Failed {
            reason: "out of memory".to_string(),
        })
        .exec(&mut db)
        .await?;

    let done = Task::create()
        .title("Done task")
        .status(Status::Done)
        .exec(&mut db)
        .await?;

    let found_pending = Task::get_by_id(&mut db, &pending.id).await?;
    assert_eq!(found_pending.status, Status::Pending);

    let found_failed = Task::get_by_id(&mut db, &failed.id).await?;
    assert_eq!(
        found_failed.status,
        Status::Failed {
            reason: "out of memory".to_string()
        }
    );

    let found_done = Task::get_by_id(&mut db, &done.id).await?;
    assert_eq!(found_done.status, Status::Done);

    Ok(())
}

/// Tests that UUID fields inside data-carrying enum variants round-trip correctly.
/// UUID is a non-trivial primitive that requires type casting on some databases.
#[driver_test]
pub async fn data_variant_with_uuid_field(test: &mut Test) -> Result<()> {
    #[derive(Debug, PartialEq, toasty::Embed)]
    enum OrderRef {
        #[column(variant = 1)]
        Internal { id: uuid::Uuid },
        #[column(variant = 2)]
        External { code: String },
    }

    #[derive(Debug, toasty::Model)]
    struct Order {
        #[key]
        #[auto]
        id: uuid::Uuid,
        order_ref: OrderRef,
    }

    let mut db = test.setup_db(models!(Order, OrderRef)).await;

    let internal_id = uuid::Uuid::new_v4();

    let o1 = Order::create()
        .order_ref(OrderRef::Internal { id: internal_id })
        .exec(&mut db)
        .await?;

    let o2 = Order::create()
        .order_ref(OrderRef::External {
            code: "EXT-001".to_string(),
        })
        .exec(&mut db)
        .await?;

    let found_o1 = Order::get_by_id(&mut db, &o1.id).await?;
    assert_eq!(found_o1.order_ref, OrderRef::Internal { id: internal_id });

    let found_o2 = Order::get_by_id(&mut db, &o2.id).await?;
    assert_eq!(
        found_o2.order_ref,
        OrderRef::External {
            code: "EXT-001".to_string()
        }
    );

    Ok(())
}

/// Tests that jiff::Timestamp fields inside data-carrying enum variants round-trip correctly.
/// Also covers a mixed enum (one unit variant, one data variant) to verify null handling.
#[driver_test]
pub async fn data_variant_with_jiff_timestamp(test: &mut Test) -> Result<()> {
    #[derive(Debug, PartialEq, toasty::Embed)]
    enum EventTime {
        #[column(variant = 1)]
        Scheduled { at: jiff::Timestamp },
        #[column(variant = 2)]
        Unscheduled,
    }

    #[derive(Debug, toasty::Model)]
    struct Event {
        #[key]
        #[auto]
        id: uuid::Uuid,
        name: String,
        time: EventTime,
    }

    let mut db = test.setup_db(models!(Event, EventTime)).await;

    let ts = jiff::Timestamp::from_second(1_700_000_000).unwrap();

    let scheduled = Event::create()
        .name("launch")
        .time(EventTime::Scheduled { at: ts })
        .exec(&mut db)
        .await?;

    let unscheduled = Event::create()
        .name("tbd")
        .time(EventTime::Unscheduled)
        .exec(&mut db)
        .await?;

    let found_scheduled = Event::get_by_id(&mut db, &scheduled.id).await?;
    assert_eq!(found_scheduled.time, EventTime::Scheduled { at: ts });

    let found_unscheduled = Event::get_by_id(&mut db, &unscheduled.id).await?;
    assert_eq!(found_unscheduled.time, EventTime::Unscheduled);

    Ok(())
}

#[driver_test]
pub async fn struct_in_data_variant(test: &mut Test) -> Result<()> {
    #[derive(Debug, PartialEq, toasty::Embed)]
    struct Address {
        street: String,
        city: String,
    }

    #[derive(Debug, PartialEq, toasty::Embed)]
    enum Destination {
        #[column(variant = 1)]
        Digital { email: String },
        #[column(variant = 2)]
        Physical { address: Address },
    }

    #[derive(Debug, toasty::Model)]
    struct Shipment {
        #[key]
        #[auto]
        id: uuid::Uuid,
        destination: Destination,
    }

    let mut db = test.setup_db(models!(Shipment, Destination, Address)).await;

    let digital = Shipment::create()
        .destination(Destination::Digital {
            email: "user@example.com".to_string(),
        })
        .exec(&mut db)
        .await?;

    let physical = Shipment::create()
        .destination(Destination::Physical {
            address: Address {
                street: "123 Main St".to_string(),
                city: "Seattle".to_string(),
            },
        })
        .exec(&mut db)
        .await?;

    let found_digital = Shipment::get_by_id(&mut db, &digital.id).await?;
    assert_eq!(
        found_digital.destination,
        Destination::Digital {
            email: "user@example.com".to_string()
        }
    );

    let found_physical = Shipment::get_by_id(&mut db, &physical.id).await?;
    assert_eq!(
        found_physical.destination,
        Destination::Physical {
            address: Address {
                street: "123 Main St".to_string(),
                city: "Seattle".to_string(),
            },
        }
    );

    Ok(())
}

/// Roundtrip test for an enum embedded inside a variant field of another enum (enum-in-enum).
/// The inner enum is unit-only; the outer has one data variant and one unit variant.
#[driver_test]
pub async fn enum_in_enum_roundtrip(test: &mut Test) -> Result<()> {
    #[derive(Debug, PartialEq, toasty::Embed)]
    enum Channel {
        #[column(variant = 1)]
        Email,
        #[column(variant = 2)]
        Sms,
    }

    #[derive(Debug, PartialEq, toasty::Embed)]
    enum Notification {
        #[column(variant = 1)]
        Send { channel: Channel, message: String },
        #[column(variant = 2)]
        Suppress,
    }

    #[derive(Debug, toasty::Model)]
    struct Alert {
        #[key]
        #[auto]
        id: uuid::Uuid,
        notification: Notification,
    }

    let mut db = test.setup_db(models!(Alert, Notification, Channel)).await;

    let a1 = Alert::create()
        .notification(Notification::Send {
            channel: Channel::Email,
            message: "hello".to_string(),
        })
        .exec(&mut db)
        .await?;

    let a2 = Alert::create()
        .notification(Notification::Send {
            channel: Channel::Sms,
            message: "world".to_string(),
        })
        .exec(&mut db)
        .await?;

    let a3 = Alert::create()
        .notification(Notification::Suppress)
        .exec(&mut db)
        .await?;

    let found_a1 = Alert::get_by_id(&mut db, &a1.id).await?;
    assert_eq!(
        found_a1.notification,
        Notification::Send {
            channel: Channel::Email,
            message: "hello".to_string(),
        }
    );

    let found_a2 = Alert::get_by_id(&mut db, &a2.id).await?;
    assert_eq!(
        found_a2.notification,
        Notification::Send {
            channel: Channel::Sms,
            message: "world".to_string(),
        }
    );

    let found_a3 = Alert::get_by_id(&mut db, &a3.id).await?;
    assert_eq!(found_a3.notification, Notification::Suppress);

    Ok(())
}

/// Verifies field indices are assigned globally across multiple data variants.
/// With two variants having two fields each, indices should be 0, 1, 2, 3.
#[driver_test]
pub async fn global_field_indices(test: &mut Test) {
    #[allow(dead_code)]
    #[derive(toasty::Embed)]
    enum Event {
        #[column(variant = 1)]
        Login { user_id: String, ip: String },
        #[column(variant = 2)]
        Purchase { item_id: String, amount: i64 },
    }

    let db = test.setup_db(models!(Event)).await;
    let schema = db.schema();

    assert_struct!(schema.app.models, #{
        Event::id(): toasty::schema::app::Model::EmbeddedEnum({
            fields: [
                { id.index: 0, name.app: Some("user_id") },
                { id.index: 1, name.app: Some("ip") },
                { id.index: 2, name.app: Some("item_id") },
                { id.index: 3, name.app: Some("amount") },
            ],
        }),
    });
}