|
5 | 5 | from piccolo.apps.migrations.auto import MigrationManager |
6 | 6 | from piccolo.apps.migrations.commands.base import BaseMigrationManager |
7 | 7 | from piccolo.columns import Varchar |
| 8 | +from piccolo.columns.base import OnDelete, OnUpdate |
8 | 9 |
|
9 | 10 | from tests.example_app.tables import Manager |
10 | 11 | from tests.base import DBTestCase |
@@ -145,6 +146,51 @@ def test_add_column(self): |
145 | 146 | response = self.run_sync("SELECT * FROM manager;") |
146 | 147 | self.assertEqual(response, [{"id": 1, "name": "Dave"}]) |
147 | 148 |
|
| 149 | + @postgres_only |
| 150 | + def test_add_foreign_key_self_column(self): |
| 151 | + """ |
| 152 | + Test adding a ForeignKey column to a MigrationManager, with a |
| 153 | + references argument of 'self'. |
| 154 | + """ |
| 155 | + manager = MigrationManager() |
| 156 | + manager.add_column( |
| 157 | + table_class_name="Manager", |
| 158 | + tablename="manager", |
| 159 | + column_name="advisor", |
| 160 | + column_class_name="ForeignKey", |
| 161 | + params={ |
| 162 | + "references": "self", |
| 163 | + "on_delete": OnDelete.cascade, |
| 164 | + "on_update": OnUpdate.cascade, |
| 165 | + "default": None, |
| 166 | + "null": True, |
| 167 | + "primary": False, |
| 168 | + "key": False, |
| 169 | + "unique": False, |
| 170 | + "index": False, |
| 171 | + }, |
| 172 | + ) |
| 173 | + asyncio.run(manager.run()) |
| 174 | + |
| 175 | + self.run_sync("INSERT INTO manager VALUES (default, 'Alice', null);") |
| 176 | + self.run_sync("INSERT INTO manager VALUES (default, 'Dave', 1);") |
| 177 | + |
| 178 | + response = self.run_sync("SELECT * FROM manager;") |
| 179 | + self.assertEqual( |
| 180 | + response, |
| 181 | + [ |
| 182 | + {"id": 1, "name": "Alice", "advisor": None}, |
| 183 | + {"id": 2, "name": "Dave", "advisor": 1}, |
| 184 | + ], |
| 185 | + ) |
| 186 | + |
| 187 | + # Reverse |
| 188 | + asyncio.run(manager.run_backwards()) |
| 189 | + response = self.run_sync("SELECT * FROM manager;") |
| 190 | + self.assertEqual( |
| 191 | + response, [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Dave"}], |
| 192 | + ) |
| 193 | + |
148 | 194 | @postgres_only |
149 | 195 | def test_add_non_nullable_column(self): |
150 | 196 | """ |
|
0 commit comments