From: Mike Bayer Date: Thu, 25 Jun 2026 14:53:58 +0000 (-0400) Subject: fix inline_references to emit FK referential actions X-Git-Tag: rel_1_18_5~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=b99b54c8bd48ce145fe664e36853c68e0d03bb8b;p=thirdparty%2Fsqlalchemy%2Falembic.git fix inline_references to emit FK referential actions Fixed bug where :paramref:`.Operations.add_column.inline_references` did not render ``ON DELETE``, ``ON UPDATE``, ``DEFERRABLE``, ``INITIALLY``, or ``MATCH`` clauses when emitting the inline ``REFERENCES`` clause. Fixes: #1820 Change-Id: I71c94cd1ba6dec0fcb31fe2958be8bfb8c5c5505 --- diff --git a/alembic/ddl/base.py b/alembic/ddl/base.py index 30a3a15a..b3904949 100644 --- a/alembic/ddl/base.py +++ b/alembic/ddl/base.py @@ -396,6 +396,9 @@ def add_column( table_name, compiler.preparer.quote(ref_col.name), ) + text += compiler.define_constraint_match(fk.constraint) + text += compiler.define_constraint_cascades(fk.constraint) + text += compiler.define_constraint_deferrability(fk.constraint) const = " ".join( compiler.process(constraint) for constraint in column.constraints diff --git a/docs/build/unreleased/1820.rst b/docs/build/unreleased/1820.rst new file mode 100644 index 00000000..f8f07913 --- /dev/null +++ b/docs/build/unreleased/1820.rst @@ -0,0 +1,9 @@ +.. change:: + :tags: bug, operations + :tickets: 1820 + + Fixed bug where the ``inline_references`` parameter of + :meth:`.Operations.add_column` did not include foreign key referential + actions such as ``ON DELETE``, ``ON UPDATE``, ``DEFERRABLE``, + ``INITIALLY``, and ``MATCH`` when rendering the inline ``REFERENCES`` + clause. diff --git a/tests/test_op.py b/tests/test_op.py index 704e2e91..e3fbf253 100644 --- a/tests/test_op.py +++ b/tests/test_op.py @@ -388,6 +388,37 @@ class OpTest(TestBase): f"ALTER TABLE t1 ADD COLUMN c1 INTEGER NOT NULL {expected_ref}" ) + @combinations( + ({"ondelete": "SET NULL"}, "ON DELETE SET NULL"), + ({"onupdate": "CASCADE"}, "ON UPDATE CASCADE"), + ( + {"ondelete": "SET NULL", "onupdate": "CASCADE"}, + "ON DELETE SET NULL ON UPDATE CASCADE", + ), + ( + {"deferrable": True, "initially": "DEFERRED"}, + "DEFERRABLE INITIALLY DEFERRED", + ), + ({"deferrable": False}, "NOT DEFERRABLE"), + ({"match": "FULL"}, "MATCH FULL"), + argnames="fk_kwargs,expected_suffix", + ) + def test_add_column_fk_inline_references_referential_actions( + self, fk_kwargs, expected_suffix + ): + context = op_fixture() + op.add_column( + "t1", + Column( + "c1", Integer, ForeignKey("c2.id", **fk_kwargs), nullable=True + ), + inline_references=True, + ) + context.assert_( + f"ALTER TABLE t1 ADD COLUMN c1 INTEGER " + f"REFERENCES c2 (id) {expected_suffix}" + ) + def test_add_column_multiple_fk_inline_references(self): """Test that inline_references is ignored when a column has multiple ForeignKey objects to avoid non-deterministic behavior."""