sqlmodel 0.4.3

SQL databases in Rust, designed to be intuitive and type-safe
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
#![cfg(feature = "c-sqlite-tests")]

use asupersync::runtime::RuntimeBuilder;
use asupersync::{Cx, Outcome};
use serde::{Deserialize, Serialize};

use sqlmodel::SchemaBuilder;
use sqlmodel::prelude::*;
use sqlmodel_query::{DeleteBuilder, UpdateBuilder};
use sqlmodel_sqlite::SqliteConnection;

fn unwrap_outcome<T>(outcome: Outcome<T, Error>) -> T {
    match outcome {
        Outcome::Ok(v) => v,
        Outcome::Err(e) => panic!("unexpected error: {e} // DEBUG {e:?}"),
        Outcome::Cancelled(r) => panic!("cancelled: {r:?}"),
        Outcome::Panicked(p) => panic!("panicked: {p:?}"),
    }
}

// Joined table inheritance base model (auto-increment PK).
#[derive(sqlmodel::Model, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[sqlmodel(table, inheritance = "joined")]
struct Person {
    #[sqlmodel(primary_key, auto_increment)]
    id: Option<i64>,
    // UNIQUE so it can serve as a non-PK conflict target for the upserts.
    #[sqlmodel(unique)]
    name: String,
}

// Joined table inheritance child model.
#[derive(sqlmodel::Model, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[sqlmodel(table, inherits = "Person")]
struct Student {
    #[sqlmodel(parent)]
    person: Person,

    // Child PK/FK to parent PK.
    #[sqlmodel(primary_key)]
    id: Option<i64>,

    grade: String,
}

#[test]
fn sqlite_joined_inheritance_dml_inserts_updates_deletes_base_and_child() {
    let rt = RuntimeBuilder::current_thread()
        .build()
        .expect("create asupersync runtime");
    let cx = Cx::for_testing();

    rt.block_on(async {
        let conn = SqliteConnection::open_memory().expect("open sqlite memory db");

        // DDL
        let stmts = SchemaBuilder::new()
            .create_table::<Person>()
            .create_table::<Student>()
            .build();
        for stmt in stmts {
            unwrap_outcome(conn.execute(&cx, &stmt, &[]).await);
        }

        // INSERT joined child: must insert base then child in one transaction, propagating id.
        let student0 = Student {
            person: Person {
                id: None,
                name: "Alice".to_string(),
            },
            id: None,
            grade: "A".to_string(),
        };

        let id = unwrap_outcome(insert!(&student0).execute(&cx, &conn).await);
        assert!(id > 0);

        // Verify both tables have the row.
        let person_table = sqlmodel_core::quote_ident(<Person as Model>::TABLE_NAME);
        let student_table = sqlmodel_core::quote_ident(<Student as Model>::TABLE_NAME);

        let people = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT id, name FROM {person_table} WHERE id = ?1"),
                &[Value::BigInt(id)],
            )
            .await,
        );
        assert_eq!(people.len(), 1);
        assert_eq!(people[0].get_as::<i64>(0).unwrap(), id);
        assert_eq!(people[0].get_named::<String>("name").unwrap(), "Alice");

        let student_rows = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT id, grade FROM {student_table} WHERE id = ?1"),
                &[Value::BigInt(id)],
            )
            .await,
        );
        assert_eq!(student_rows.len(), 1);
        assert_eq!(student_rows[0].get_as::<i64>(0).unwrap(), id);
        assert_eq!(student_rows[0].get_named::<String>("grade").unwrap(), "A");

        // UPDATE joined child: must update both base and child rows.
        let student1 = Student {
            person: Person {
                id: Some(id),
                name: "Alice2".to_string(),
            },
            id: Some(id),
            grade: "B".to_string(),
        };

        let updated = unwrap_outcome(update!(&student1).execute(&cx, &conn).await);
        // One row updated in each table (sum semantics).
        assert_eq!(updated, 2);

        let people2 = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT name FROM {person_table} WHERE id = ?1"),
                &[Value::BigInt(id)],
            )
            .await,
        );
        assert_eq!(people2[0].get_as::<String>(0).unwrap(), "Alice2");

        let students2 = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT grade FROM {student_table} WHERE id = ?1"),
                &[Value::BigInt(id)],
            )
            .await,
        );
        assert_eq!(students2[0].get_as::<String>(0).unwrap(), "B");

        // UPDATE joined child (explicit WHERE/SET): base+child table targeting with qualification.
        let updated_explicit = unwrap_outcome(
            UpdateBuilder::<Student>::empty()
                .set(&format!("{}.name", <Person as Model>::TABLE_NAME), "Alice3")
                .set("grade", "A+")
                .filter(Expr::qualified(<Student as Model>::TABLE_NAME, "id").eq(id))
                .execute(&cx, &conn)
                .await,
        );
        assert_eq!(updated_explicit, 2);

        let explicit_rows = unwrap_outcome(
            UpdateBuilder::<Student>::empty()
                .set("grade", "A++")
                .filter(Expr::qualified(<Student as Model>::TABLE_NAME, "id").eq(id))
                .returning()
                .execute_returning(&cx, &conn)
                .await,
        );
        assert_eq!(explicit_rows.len(), 1);
        assert_eq!(
            explicit_rows[0]
                .get_named::<String>(&format!("{}__name", <Person as Model>::TABLE_NAME))
                .unwrap(),
            "Alice3"
        );
        assert_eq!(
            explicit_rows[0]
                .get_named::<String>(&format!("{}__grade", <Student as Model>::TABLE_NAME))
                .unwrap(),
            "A++"
        );

        // Joined insert ON CONFLICT: explicit PK upsert updates both base and child tables.
        let upsert_model = Student {
            person: Person {
                id: Some(id),
                name: "Alice4".to_string(),
            },
            id: Some(id),
            grade: "A*".to_string(),
        };
        eprintln!("PHASE: explicit-pk upsert");
        let upsert_id = match insert!(&upsert_model)
            .on_conflict_do_update(&["name", "grade"])
            .execute(&cx, &conn)
            .await
        {
            Outcome::Ok(v) => v,
            Outcome::Err(ref e) => {
                eprintln!("FULL ERROR DEBUG: {e:?}");
                panic!("upsert failed: {e}");
            }
            Outcome::Cancelled(r) => panic!("cancelled: {r:?}"),
            Outcome::Panicked(p) => panic!("panicked: {p:?}"),
        };
        assert_eq!(upsert_id, id);

        let people_after_upsert = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT name FROM {person_table} WHERE id = ?1"),
                &[Value::BigInt(id)],
            )
            .await,
        );
        assert_eq!(
            people_after_upsert[0].get_as::<String>(0).unwrap(),
            "Alice4"
        );
        let students_after_upsert = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT grade FROM {student_table} WHERE id = ?1"),
                &[Value::BigInt(id)],
            )
            .await,
        );
        assert_eq!(students_after_upsert[0].get_as::<String>(0).unwrap(), "A*");

        // Ambiguous unqualified joined column in explicit SET should fail with a clear error.
        let ambiguous_update = UpdateBuilder::<Student>::empty()
            .set("id", 123_i64)
            .filter(Expr::qualified(<Student as Model>::TABLE_NAME, "id").eq(id))
            .execute(&cx, &conn)
            .await;
        match ambiguous_update {
            Outcome::Err(e) => assert!(
                e.to_string()
                    .contains("ambiguous joined-table inheritance column 'id'"),
                "unexpected error: {e}"
            ),
            other => panic!("expected ambiguity error, got {other:?}"),
        }

        // RETURNING with ON CONFLICT now works for joined inheritance and
        // returns the joined parent__*/child__* row shape. DO NOTHING on an
        // existing row returns no row (the insert was skipped).
        let conflict_returning = unwrap_outcome(
            insert!(&upsert_model)
                .on_conflict_do_nothing()
                .execute_returning(&cx, &conn)
                .await,
        );
        assert!(
            conflict_returning.is_none(),
            "DO NOTHING skips: {conflict_returning:?}"
        );

        // DO UPDATE + RETURNING re-reads the surviving joined row.
        let upsert_rows = unwrap_outcome(
            insert!(&upsert_model)
                .on_conflict_do_update(&["name", "grade"])
                .execute_returning(&cx, &conn)
                .await,
        );
        let upsert_row = upsert_rows.expect("DO UPDATE returns the surviving row");
        assert_eq!(
            upsert_row
                .get_named::<String>(&format!("{}__name", <Person as Model>::TABLE_NAME))
                .unwrap(),
            "Alice4"
        );
        assert_eq!(
            upsert_row
                .get_named::<String>(&format!("{}__grade", <Student as Model>::TABLE_NAME))
                .unwrap(),
            "A*"
        );

        // Auto-increment upsert keyed by a non-PK parent UNIQUE column
        // (person.name): the surviving parent id is learned via the conflict
        // clause and propagated to the child row; parent and child columns
        // both update. Person 1's name is "Alice4" at this point (the
        // explicit-PK upsert above renamed it), so this conflicts on that
        // row and must reuse id 1.
        let auto_upsert = Student {
            person: Person {
                id: None,
                name: "Alice4".to_string(),
            },
            id: None,
            grade: "B".to_string(),
        };
        let upsert_by_name_id = unwrap_outcome(
            insert!(&auto_upsert)
                .on_conflict_target_do_update(&["name"], &["grade"])
                .execute(&cx, &conn)
                .await,
        );
        assert_eq!(upsert_by_name_id, id, "surviving parent id is reused");
        let name_after = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT grade FROM {student_table} WHERE id = ?1"),
                &[Value::BigInt(id)],
            )
            .await,
        );
        assert_eq!(name_after[0].get_as::<String>(0).unwrap(), "B");

        // Auto-increment upsert that lands on an unused unique value inserts
        // a brand-new parent+child pair and returns the generated id.
        let auto_insert = Student {
            person: Person {
                id: None,
                name: "Newname".to_string(),
            },
            id: None,
            grade: "F".to_string(),
        };
        let fresh_id = unwrap_outcome(
            insert!(&auto_insert)
                .on_conflict_target_do_update(&["name"], &["grade"])
                .execute(&cx, &conn)
                .await,
        );
        assert!(fresh_id > 0 && fresh_id != id, "new row got a new id");

        // The child-table column cannot be a conflict target: uniqueness
        // cannot be resolved before the parent id is known.
        let child_target = insert!(&auto_insert)
            .on_conflict_target_do_update(&["grade"], &["grade"])
            .execute(&cx, &conn)
            .await;
        match child_target {
            Outcome::Err(e) => assert!(
                e.to_string()
                    .contains("is a child-table column; child uniqueness cannot be resolved"),
                "unexpected error: {e}"
            ),
            other => panic!("expected child-target rejection, got {other:?}"),
        }

        // Insert two more rows for explicit DELETE semantics checks.
        let student_c = Student {
            person: Person {
                id: None,
                name: "Bob".to_string(),
            },
            id: None,
            grade: "C".to_string(),
        };
        let id2 = unwrap_outcome(insert!(&student_c).execute(&cx, &conn).await);
        let student_d = Student {
            person: Person {
                id: None,
                name: "Dana".to_string(),
            },
            id: None,
            grade: "D".to_string(),
        };
        let id3 = unwrap_outcome(insert!(&student_d).execute(&cx, &conn).await);

        // DELETE joined child (explicit WHERE): filter by child table and delete both child+parent.
        let deleted_explicit = unwrap_outcome(
            DeleteBuilder::<Student>::new()
                .filter(Expr::qualified(<Student as Model>::TABLE_NAME, "grade").eq("C"))
                .execute(&cx, &conn)
                .await,
        );
        assert_eq!(deleted_explicit, 2);
        let people_deleted_explicit = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT id FROM {person_table} WHERE id = ?1"),
                &[Value::BigInt(id2)],
            )
            .await,
        );
        assert_eq!(people_deleted_explicit.len(), 0);
        let students_deleted_explicit = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT id FROM {student_table} WHERE id = ?1"),
                &[Value::BigInt(id2)],
            )
            .await,
        );
        assert_eq!(students_deleted_explicit.len(), 0);

        // DELETE joined child returning uses base+child prefixed row shape.
        let deleted_rows = unwrap_outcome(
            DeleteBuilder::<Student>::new()
                .filter(Expr::qualified(<Student as Model>::TABLE_NAME, "grade").eq("D"))
                .returning()
                .execute_returning(&cx, &conn)
                .await,
        );
        assert_eq!(deleted_rows.len(), 1);
        assert_eq!(
            deleted_rows[0]
                .get_named::<String>(&format!("{}__name", <Person as Model>::TABLE_NAME))
                .unwrap(),
            "Dana"
        );
        assert_eq!(
            deleted_rows[0]
                .get_named::<String>(&format!("{}__grade", <Student as Model>::TABLE_NAME))
                .unwrap(),
            "D"
        );
        let people_after_returning_delete = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT id FROM {person_table} WHERE id = ?1"),
                &[Value::BigInt(id3)],
            )
            .await,
        );
        assert_eq!(people_after_returning_delete.len(), 0);
        let students_after_returning_delete = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT id FROM {student_table} WHERE id = ?1"),
                &[Value::BigInt(id3)],
            )
            .await,
        );
        assert_eq!(students_after_returning_delete.len(), 0);

        // DELETE joined child: must delete child then base.
        let deleted = unwrap_outcome(
            DeleteBuilder::from_model(&student1)
                .execute(&cx, &conn)
                .await,
        );
        // One row deleted in each table (sum semantics).
        assert_eq!(deleted, 2);

        let people3 = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT id FROM {person_table} WHERE id = ?1"),
                &[Value::BigInt(id)],
            )
            .await,
        );
        assert_eq!(people3.len(), 0);

        let deleted_student_rows = unwrap_outcome(
            conn.query(
                &cx,
                &format!("SELECT id FROM {student_table} WHERE id = ?1"),
                &[Value::BigInt(id)],
            )
            .await,
        );
        assert_eq!(deleted_student_rows.len(), 0);
    });
}