Skip to content

Commit 8f04473

Browse files
David-Wobrockfelixxm
authored andcommitted
Fixed #25105 -- Checked deferred constraints before updating rows on PostgreSQL.
1 parent fde946d commit 8f04473

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

django/db/backends/postgresql/schema.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@
77

88
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
99

10+
# Setting all constraints to IMMEDIATE to allow changing data in the same
11+
# transaction.
12+
sql_update_with_default = (
13+
"UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL"
14+
"; SET CONSTRAINTS ALL IMMEDIATE"
15+
)
16+
1017
sql_delete_sequence = "DROP SEQUENCE IF EXISTS %(sequence)s CASCADE"
1118

1219
sql_create_index = (

tests/schema/tests.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -973,6 +973,38 @@ def test_alter_fk_checks_deferred_constraints(self):
973973
Node.objects.update(parent=parent)
974974
editor.alter_field(Node, old_field, new_field, strict=True)
975975

976+
@isolate_apps("schema")
977+
def test_alter_null_with_default_value_deferred_constraints(self):
978+
class Publisher(Model):
979+
class Meta:
980+
app_label = "schema"
981+
982+
class Article(Model):
983+
publisher = ForeignKey(Publisher, CASCADE)
984+
title = CharField(max_length=50, null=True)
985+
description = CharField(max_length=100, null=True)
986+
987+
class Meta:
988+
app_label = "schema"
989+
990+
with connection.schema_editor() as editor:
991+
editor.create_model(Publisher)
992+
editor.create_model(Article)
993+
self.isolated_local_models = [Article, Publisher]
994+
995+
publisher = Publisher.objects.create()
996+
Article.objects.create(publisher=publisher)
997+
998+
old_title = Article._meta.get_field("title")
999+
new_title = CharField(max_length=50, null=False, default="")
1000+
new_title.set_attributes_from_name("title")
1001+
old_description = Article._meta.get_field("description")
1002+
new_description = CharField(max_length=100, null=False, default="")
1003+
new_description.set_attributes_from_name("description")
1004+
with connection.schema_editor() as editor:
1005+
editor.alter_field(Article, old_title, new_title, strict=True)
1006+
editor.alter_field(Article, old_description, new_description, strict=True)
1007+
9761008
def test_alter_text_field_to_date_field(self):
9771009
"""
9781010
#25002 - Test conversion of text field to date field.

0 commit comments

Comments
 (0)