| 1 | // vtest retry: 3 |
| 2 | import db.sqlite |
| 3 | |
| 4 | struct Boat { |
| 5 | id int @[primary; sql: serial] |
| 6 | color_id int @[references] |
| 7 | another1_id int @[references: 'size'] |
| 8 | another2_id int @[references: 'size(secondary_id)'] |
| 9 | } |
| 10 | |
| 11 | struct Color { |
| 12 | id int @[primary; sql: serial] |
| 13 | hex string |
| 14 | } |
| 15 | |
| 16 | struct Size { |
| 17 | id int @[primary; sql: serial] |
| 18 | secondary_id int |
| 19 | } |
| 20 | |
| 21 | fn test_references_constraint() { |
| 22 | db := sqlite.connect(':memory:') or { panic(err) } |
| 23 | |
| 24 | sql db { |
| 25 | create table Boat |
| 26 | create table Color |
| 27 | create table Size |
| 28 | } or { panic(err) } |
| 29 | |
| 30 | // this pragma returns a row for each foreign key constraint on a table |
| 31 | pragma_result := db.exec('pragma foreign_key_list(boat)') or { panic('nope') } |
| 32 | |
| 33 | assert pragma_result.len == 3 |
| 34 | } |
| 35 | |
| 36 | struct Member { |
| 37 | id int @[primary; sql: serial] |
| 38 | name string |
| 39 | } |
| 40 | |
| 41 | struct Team { |
| 42 | id int @[primary; sql: serial] |
| 43 | name string |
| 44 | member_id int @[references: 'Member(id)'] |
| 45 | } |
| 46 | |
| 47 | fn test_omitted_references_field_inserts_null() { |
| 48 | mut db := sqlite.connect(':memory:')! |
| 49 | defer { |
| 50 | db.close() or {} |
| 51 | } |
| 52 | db.exec('PRAGMA foreign_keys=ON')! |
| 53 | |
| 54 | sql db { |
| 55 | create table Member |
| 56 | create table Team |
| 57 | }! |
| 58 | |
| 59 | team := Team{ |
| 60 | name: 'unassigned' |
| 61 | } |
| 62 | |
| 63 | sql db { |
| 64 | insert team into Team |
| 65 | }! |
| 66 | |
| 67 | rows := db.exec('select member_id from Team where id = 1')! |
| 68 | assert rows.len == 1 |
| 69 | assert rows[0].vals[0] == '' |
| 70 | |
| 71 | invalid_team := Team{ |
| 72 | name: 'invalid' |
| 73 | member_id: 0 |
| 74 | } |
| 75 | |
| 76 | mut failed := false |
| 77 | sql db { |
| 78 | insert invalid_team into Team |
| 79 | } or { failed = true } |
| 80 | assert failed |
| 81 | } |
| 82 | |