6 let mut test = Test::new("Add foreign key");
10 name = "create_user_table"
36 test.second_migration(
38 name = "add_foreign_key"
41 type = "add_foreign_key"
46 referenced_table = "users"
47 referenced_columns = ["id"]
51 test.after_first(|db| {
52 // Insert some test users
53 db.simple_query("INSERT INTO users (id) VALUES (1), (2)")
57 test.intermediate(|db, _| {
58 // Ensure items can be inserted if they reference valid users
59 db.simple_query("INSERT INTO items (id, user_id) VALUES (1, 1), (2, 2)")
62 // Ensure items can't be inserted if they don't reference valid users
63 let result = db.simple_query("INSERT INTO items (id, user_id) VALUES (3, 3)");
64 assert!(result.is_err(), "expected insert to fail");
67 test.after_completion(|db| {
68 // Ensure items can be inserted if they reference valid users
69 db.simple_query("INSERT INTO items (id, user_id) VALUES (3, 1), (4, 2)")
72 // Ensure items can't be inserted if they don't reference valid users
73 let result = db.simple_query("INSERT INTO items (id, user_id) VALUES (5, 3)");
74 assert!(result.is_err(), "expected insert to fail");
76 // Ensure foreign key exists with the right name
77 let foreign_key_name: Option<String> = db
80 SELECT tc.constraint_name
81 FROM information_schema.table_constraints AS tc
82 WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='items';
88 .map(|row| row.get(0));
89 assert_eq!(Some("items_user_id_fkey".to_string()), foreign_key_name);
92 test.after_abort(|db| {
93 // Ensure foreign key doesn't exist
94 let fk_does_not_exist = db
97 SELECT tc.constraint_name
98 FROM information_schema.table_constraints AS tc
99 WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='items';
105 assert!(fk_does_not_exist);
112fn add_invalid_foreign_key() {
113 let mut test = Test::new("Add invalid foreign key");
115 test.first_migration(
117 name = "create_user_table"
120 type = "create_table"
129 type = "create_table"
143 test.second_migration(
145 name = "add_foreign_key"
148 type = "add_foreign_key"
151 [actions.foreign_key]
152 columns = ["user_id"]
153 referenced_table = "users"
154 referenced_columns = ["id"]
158 test.after_first(|db| {
159 // Insert some items which don't reference a valid user
160 db.simple_query("INSERT INTO items (id, user_id) VALUES (1, 1), (2, 2)")
164 test.expect_failure();
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list