Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions piccolo/apps/migrations/auto/migration_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,14 @@ async def _run_alter_columns(self, backwards: bool = False):

assert isinstance(fk_column, ForeignKey)

# Auto migrations only list the rule which changed. The
# new constraint still needs the other one, otherwise
# the database falls back to NO ACTION.
if on_delete is None:
on_delete = fk_column._foreign_key_meta.on_delete
if on_update is None:
on_update = fk_column._foreign_key_meta.on_update

# First drop the existing foreign key constraint
constraint_name = await get_fk_constraint_name(
column=fk_column
Expand Down
54 changes: 54 additions & 0 deletions tests/apps/migrations/auto/test_migration_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -1107,6 +1107,60 @@ def test_alter_fk_on_delete_on_update(self):
OnDelete.no_action,
)

@engines_only("postgres", "cockroach")
def test_alter_fk_on_delete_keeps_on_update(self):
"""
Auto migrations only include the rule which changed. Altering
``on_delete`` mustn't reset ``on_update`` to ``NO ACTION``.
"""
# Start with the rules the example app's migrations declare.
manager = MigrationManager(app_name="music")
manager.alter_column(
table_class_name="Band",
tablename="band",
column_name="manager",
db_column_name="manager",
params={
"on_delete": OnDelete.cascade,
"on_update": OnUpdate.cascade,
},
old_params={
"on_delete": OnDelete.no_action,
"on_update": OnUpdate.no_action,
},
column_class=ForeignKey,
old_column_class=ForeignKey,
schema=None,
)
asyncio.run(manager.run())

# This is what `piccolo migrations new --auto` generates when only
# `on_delete` changes.
manager = MigrationManager(app_name="music")
manager.alter_column(
table_class_name="Band",
tablename="band",
column_name="manager",
db_column_name="manager",
params={"on_delete": OnDelete.set_null},
old_params={"on_delete": OnDelete.cascade},
column_class=ForeignKey,
old_column_class=ForeignKey,
schema=None,
)
asyncio.run(manager.run())

rules = run_sync(get_fk_constraint_rules(column=Band.manager))
self.assertEqual(rules.on_delete, OnDelete.set_null)
self.assertEqual(rules.on_update, OnUpdate.cascade)

# Reverse
asyncio.run(manager.run(backwards=True))

rules = run_sync(get_fk_constraint_rules(column=Band.manager))
self.assertEqual(rules.on_delete, OnDelete.cascade)
self.assertEqual(rules.on_update, OnUpdate.cascade)

@engines_only("postgres")
def test_alter_column_unique(self):
"""
Expand Down