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
use crate::prelude::*;

use toasty_core::driver::{Operation, operation::Transaction};

// ===== Transaction wrapping =====

/// A multi-op create (user + associated todo) should be wrapped in
/// BEGIN ... COMMIT so the driver sees all three transaction operations.
#[driver_test(id(ID), requires(sql), scenario(crate::scenarios::has_many_belongs_to))]
pub async fn multi_op_create_wraps_in_transaction(t: &mut Test) -> Result<()> {
    let mut db = setup(t).await;

    t.log().clear();
    let user = User::create()
        .name("Alice")
        .todo(Todo::create().title("task"))
        .exec(&mut db)
        .await?;

    assert_struct!(
        t.log().pop_op(),
        Operation::Transaction(Transaction::Start {
            isolation: None,
            read_only: false
        })
    );
    assert_struct!(t.log().pop_op(), Operation::QuerySql(_)); // INSERT user
    assert_struct!(t.log().pop_op(), Operation::QuerySql(_)); // INSERT todo
    assert_struct!(
        t.log().pop_op(),
        Operation::Transaction(Transaction::Commit)
    );
    assert!(t.log().is_empty());

    let todos = user.todos().exec(&mut db).await?;
    assert_eq!(1, todos.len());

    Ok(())
}

/// A single-op create (no associations) must NOT be wrapped in a transaction —
/// the engine skips the overhead for plans with only one DB operation.
#[driver_test(id(ID), requires(sql), scenario(crate::scenarios::two_models))]
pub async fn single_op_skips_transaction(t: &mut Test) -> Result<()> {
    let mut db = setup(t).await;

    t.log().clear();
    User::create().name("x").exec(&mut db).await?;

    // Only the INSERT — no Transaction::Start { isolation: None, read_only: false } bookending it
    assert_struct!(t.log().pop_op(), Operation::QuerySql(_));
    assert!(t.log().is_empty());

    Ok(())
}

// ===== Rollback on partial failure =====

/// When the second INSERT in a has_many create plan fails (unique constraint),
/// the driver should receive Transaction::Rollback and no orphaned user should
/// remain in the database.
///
/// Uses u64 (auto-increment) IDs so that the engine always generates two
/// separate DB operations (INSERT user then INSERT todo), ensuring the
/// explicit transaction wrapping is exercised. With uuid::Uuid IDs the engine
/// reorders execution (INSERT todo before INSERT user due to the Const
/// optimization), which produces a different but equally valid log pattern.
#[driver_test(requires(and(sql, auto_increment)))]
pub async fn create_with_has_many_rolls_back_on_failure(t: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: u64,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    struct Todo {
        #[key]
        #[auto]
        id: u64,

        #[index]
        user_id: u64,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,

        #[unique]
        title: String,
    }

    let mut db = t.setup_db(models!(User, Todo)).await;

    // Seed the title that will cause the second INSERT to fail.
    User::create()
        .todo(Todo::create().title("taken"))
        .exec(&mut db)
        .await?;

    t.log().clear();
    assert_err!(
        User::create()
            .todo(Todo::create().title("taken"))
            .exec(&mut db)
            .await
    );

    // Transaction::Start { isolation: None, read_only: false } → INSERT user (succeeds, logged) →
    // INSERT todo (fails on unique constraint, NOT logged) → Transaction::Rollback
    assert_struct!(
        t.log().pop_op(),
        Operation::Transaction(Transaction::Start {
            isolation: None,
            read_only: false
        })
    );
    assert_struct!(t.log().pop_op(), Operation::QuerySql(_)); // INSERT user
    assert_struct!(
        t.log().pop_op(),
        Operation::Transaction(Transaction::Rollback)
    );
    assert!(t.log().is_empty());

    // No orphaned user — count unchanged from pre-seed
    let users = User::all().exec(&mut db).await?;
    assert_eq!(1, users.len());

    Ok(())
}

/// Same rollback guarantee for a has_one association create.
///
/// Uses u64 (auto-increment) IDs so that the engine always generates two
/// separate DB operations (INSERT user then INSERT profile), ensuring the
/// explicit transaction wrapping is exercised. With uuid::Uuid IDs the engine
/// can combine both inserts into a single atomic SQL statement, which provides
/// atomicity without an explicit transaction.
#[driver_test(requires(and(sql, auto_increment)))]
pub async fn create_with_has_one_rolls_back_on_failure(t: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: u64,

        #[has_one]
        profile: toasty::HasOne<Option<Profile>>,
    }

    #[derive(Debug, toasty::Model)]
    struct Profile {
        #[key]
        #[auto]
        id: u64,

        #[unique]
        bio: String,

        #[unique]
        user_id: u64,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,
    }

    let mut db = t.setup_db(models!(User, Profile)).await;

    // Seed the bio that will cause the second INSERT to fail.
    User::create()
        .profile(Profile::create().bio("taken"))
        .exec(&mut db)
        .await?;

    t.log().clear();
    assert_err!(
        User::create()
            .profile(Profile::create().bio("taken"))
            .exec(&mut db)
            .await
    );

    assert_struct!(
        t.log().pop_op(),
        Operation::Transaction(Transaction::Start {
            isolation: None,
            read_only: false
        })
    );
    assert_struct!(t.log().pop_op(), Operation::QuerySql(_)); // INSERT user
    assert_struct!(
        t.log().pop_op(),
        Operation::Transaction(Transaction::Rollback)
    );
    assert!(t.log().is_empty());

    // No orphaned user — count unchanged from pre-seed
    let users = User::all().exec(&mut db).await?;
    assert_eq!(1, users.len());

    Ok(())
}

/// When an update + new-association plan fails on the UPDATE (after the
/// INSERT succeeds), the INSERT must also be rolled back.
///
/// The engine always executes INSERT before UPDATE in such plans (INSERT is
/// a dependency of the UPDATE's returning clause). So the collision is placed
/// on the User's name field (not the Todo), ensuring the INSERT succeeds first
/// and is then rolled back when the subsequent UPDATE fails.
#[driver_test(id(ID), requires(sql))]
pub async fn update_with_new_association_rolls_back_on_failure(t: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        #[unique]
        name: String,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        #[index]
        user_id: ID,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<User>,

        title: String,
    }

    let mut db = t.setup_db(models!(User, Todo)).await;

    let mut user = User::create().name("original").exec(&mut db).await?;
    // Seed the name collision — this user's name will be duplicated by the failing UPDATE.
    User::create().name("taken").exec(&mut db).await?;

    t.log().clear();
    assert_err!(
        user.update()
            .name("taken") // UPDATE will fail: unique name
            .todos(toasty::stmt::insert(Todo::create().title("new-todo"))) // INSERT runs first and succeeds
            .exec(&mut db)
            .await
    );

    // INSERT todo runs first (succeeds, logged), then UPDATE user fails on unique
    // name → Transaction::Rollback undoes the INSERT.
    assert_struct!(
        t.log().pop_op(),
        Operation::Transaction(Transaction::Start {
            isolation: None,
            read_only: false
        })
    );
    assert_struct!(t.log().pop_op(), Operation::QuerySql(_)); // INSERT todo (rolled back)
    assert_struct!(
        t.log().pop_op(),
        Operation::Transaction(Transaction::Rollback)
    );
    assert!(t.log().is_empty());

    // INSERT was rolled back — no orphaned todo
    let todos = user.todos().exec(&mut db).await?;
    assert!(todos.is_empty());

    Ok(())
}

// ===== ReadModifyWrite transaction behavior =====

/// A successful standalone conditional update (link/unlink) wraps itself in
/// its own BEGIN...COMMIT on drivers that don't support CTE-with-update
/// (SQLite, MySQL). When nested inside an outer transaction it uses savepoints
/// instead. On PostgreSQL the same operation is a single CTE-based QuerySql.
#[driver_test(id(ID), requires(sql))]
pub async fn rmw_uses_savepoints(t: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        #[index]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    let mut db = t.setup_db(models!(User, Todo)).await;

    let user = User::create().todo(Todo::create()).exec(&mut db).await?;
    let todos: Vec<_> = user.todos().exec(&mut db).await?;

    t.log().clear();
    user.todos().remove(&mut db, &todos[0]).await?;

    if t.capability().cte_with_update {
        // PostgreSQL: single CTE bundles the condition + update
        assert_struct!(t.log().pop_op(), Operation::QuerySql(_));
    } else {
        // SQLite / MySQL: standalone RMW starts its own transaction
        assert_struct!(
            t.log().pop_op(),
            Operation::Transaction(Transaction::Start {
                isolation: None,
                read_only: false
            })
        );
        assert_struct!(t.log().pop_op(), Operation::QuerySql(_)); // read
        assert_struct!(t.log().pop_op(), Operation::QuerySql(_)); // write
        assert_struct!(
            t.log().pop_op(),
            Operation::Transaction(Transaction::Commit)
        );
    }
    assert!(t.log().is_empty());

    Ok(())
}

/// When a standalone RMW condition fails (todo doesn't belong to this user),
/// the driver should receive ROLLBACK on the RMW's own transaction.
/// On PostgreSQL the CTE handles this in a single statement.
#[driver_test(id(ID), requires(sql))]
pub async fn rmw_condition_failure_issues_rollback_to_savepoint(t: &mut Test) -> Result<()> {
    #[derive(Debug, toasty::Model)]
    struct User {
        #[key]
        #[auto]
        id: ID,

        #[has_many]
        todos: toasty::HasMany<Todo>,
    }

    #[derive(Debug, toasty::Model)]
    struct Todo {
        #[key]
        #[auto]
        id: ID,

        #[index]
        user_id: Option<ID>,

        #[belongs_to(key = user_id, references = id)]
        user: toasty::BelongsTo<Option<User>>,
    }

    let mut db = t.setup_db(models!(User, Todo)).await;

    let user1 = User::create().exec(&mut db).await?;
    let user2 = User::create().todo(Todo::create()).exec(&mut db).await?;
    let u2_todos: Vec<_> = user2.todos().exec(&mut db).await?;

    t.log().clear();
    // Remove u2's todo via user1 — condition (user_id = user1.id) won't match
    assert_err!(user1.todos().remove(&mut db, &u2_todos[0]).await);

    if t.capability().cte_with_update {
        // PostgreSQL: a single QuerySql; condition handled inside the CTE
        assert_struct!(t.log().pop_op(), Operation::QuerySql(_));
    } else {
        // SQLite / MySQL: standalone RMW starts its own transaction;
        // condition failure rolls it back
        assert_struct!(
            t.log().pop_op(),
            Operation::Transaction(Transaction::Start {
                isolation: None,
                read_only: false
            })
        );
        assert_struct!(t.log().pop_op(), Operation::QuerySql(_)); // read
        assert_struct!(
            t.log().pop_op(),
            Operation::Transaction(Transaction::Rollback)
        );
    }
    assert!(t.log().is_empty());

    // The todo is untouched — still belongs to user2
    let reloaded = Todo::get_by_id(&mut db, u2_todos[0].id).await?;
    assert_struct!(reloaded, { user_id: Some(== user2.id) });

    Ok(())
}