diff --git a/docs/cli.rst b/docs/cli.rst index a608160..b93868c 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -2113,6 +2113,9 @@ Every option for this table (with the exception of ``--pk-none``) can be specifi ``--add-foreign-key column other_table other_column`` Add a foreign key constraint to ``column`` pointing to ``other_table.other_column``. +``--update-incoming-fks`` + When renaming columns, automatically update foreign key constraints in other tables that reference the renamed columns. For example, if ``books.author_id`` references ``authors.id`` and you rename ``authors.id`` to ``authors.author_pk``, this flag will also update the foreign key in ``books`` to reference the new column name. + If you want to see the SQL that will be executed to make the change without actually executing it, add the ``--sql`` flag. For example: .. code-block:: bash diff --git a/docs/python-api.rst b/docs/python-api.rst index 267591a..2fe2aeb 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -1631,6 +1631,31 @@ This example drops two foreign keys - the one from ``places.country`` to ``count drop_foreign_keys=("country", "continent") ) +.. _python_api_transform_update_incoming_fks: + +Updating foreign keys in other tables +------------------------------------- + +When renaming columns that are referenced by foreign keys in other tables, you can use the ``update_incoming_fks=True`` parameter to automatically update those foreign key constraints. + +For example, if you have a ``books`` table with a foreign key from ``books.author_id`` to ``authors.id``, and you want to rename ``authors.id`` to ``authors.author_pk``: + +.. code-block:: python + + db["authors"].transform( + rename={"id": "author_pk"}, + update_incoming_fks=True, + ) + +This will rename the column in the ``authors`` table and also update the foreign key constraint in the ``books`` table to reference ``authors.author_pk`` instead of ``authors.id``. + +Without ``update_incoming_fks=True``, this operation would fail with a foreign key mismatch error (if foreign key enforcement is enabled) because the ``books`` table would still reference the old column name. + +This parameter also correctly handles: + +- Multiple tables referencing the renamed column +- Self-referential foreign keys (e.g., an ``employees.manager_id`` column referencing ``employees.id``) + .. _python_api_transform_sql: Custom transformations with .transform_sql()