|
| 1 | +""" |
| 2 | +Helpers for ensuring that existing SQLite foreign key constraints are |
| 3 | +``DEFERRABLE INITIALLY DEFERRED``. |
| 4 | +
|
| 5 | +Prior to Django 3.1, SQLite tables were created with immediate foreign key constraints, e.g.:: |
| 6 | +
|
| 7 | + "store_model_id" char(32) NOT NULL REFERENCES "morango_store" ("id") |
| 8 | +
|
| 9 | +Since Django 3.1 the same column is created as:: |
| 10 | +
|
| 11 | + "store_model_id" char(32) NOT NULL REFERENCES "morango_store" ("id") DEFERRABLE INITIALLY DEFERRED |
| 12 | +
|
| 13 | +Django relies on deferred constraint checking for correct cascade-deletion ordering. Databases |
| 14 | +created before Morango 0.8 (with Django 1.11) therefore retain immediate constraints, which can |
| 15 | +raise ``IntegrityError: FOREIGN KEY constraint failed`` during operations such as sync |
| 16 | +deserialization once foreign key enforcement is enabled at the database level (the default since |
| 17 | +Django 3.2). |
| 18 | +
|
| 19 | +The migration framework does not regenerate these constraints on its own because the deferrable |
| 20 | +clause is not part of the field definition that migrations track. This module rebuilds the affected |
| 21 | +tables so that a migrated database ends up with the same schema as a freshly created one. |
| 22 | +""" |
| 23 | + |
| 24 | +import logging |
| 25 | +from typing import List |
| 26 | +from typing import Optional |
| 27 | + |
| 28 | +from django.apps import apps as global_apps |
| 29 | +from django.apps.registry import Apps |
| 30 | +from django.db import connection |
| 31 | +from django.db import DatabaseError |
| 32 | +from django.db import router |
| 33 | +from django.db.backends.base.schema import BaseDatabaseSchemaEditor |
| 34 | +from django.db.backends.sqlite3.schema import DatabaseSchemaEditor |
| 35 | + |
| 36 | +logger = logging.getLogger(__name__) |
| 37 | + |
| 38 | + |
| 39 | +def _get_table_sql(conn, table_name: str) -> Optional[str]: |
| 40 | + """ |
| 41 | + Return the ``CREATE TABLE`` statement stored by SQLite for ``table_name``, or ``None`` if the |
| 42 | + table does not exist. |
| 43 | + """ |
| 44 | + with conn.cursor() as cursor: |
| 45 | + cursor.execute( |
| 46 | + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s", |
| 47 | + [table_name], |
| 48 | + ) |
| 49 | + row = cursor.fetchone() |
| 50 | + return row[0] if row else None |
| 51 | + |
| 52 | + |
| 53 | +def _table_has_immediate_foreign_key(conn, table_name: str) -> bool: |
| 54 | + """ |
| 55 | + Determine whether ``table_name`` has at least one foreign key constraint that is not deferrable. |
| 56 | + Tables are created with all constraints in the same style, so the presence of a ``REFERENCES`` |
| 57 | + clause without ``DEFERRABLE`` indicates an immediate constraint that needs to be rebuilt. |
| 58 | + """ |
| 59 | + sql = _get_table_sql(conn, table_name) |
| 60 | + if not sql: |
| 61 | + return False |
| 62 | + references_count = sql.count("REFERENCES") |
| 63 | + if references_count == 0: |
| 64 | + return False |
| 65 | + # make sure that all FK columns (identified by references) have a deferrable constraint |
| 66 | + return references_count != sql.count("DEFERRABLE") |
| 67 | + |
| 68 | + |
| 69 | +class MakeForeignKeysDeferrable: |
| 70 | + """ |
| 71 | + Invokable utility class that rebuilds of any table belonging to one of ``*app_labels`` whose |
| 72 | + foreign key constraints are still immediate, so that they become |
| 73 | + ``DEFERRABLE INITIALLY DEFERRED``. |
| 74 | +
|
| 75 | + This can be utilized by passing this class to ``RunPython`` in a Django migration, or by |
| 76 | + manually invoking its ``run`` method. |
| 77 | +
|
| 78 | + This is a no-op on non-SQLite backends (PostgreSQL already creates deferrable |
| 79 | + constraints) and on tables that already use deferrable constraints, so it is |
| 80 | + safe to apply to any database. |
| 81 | + """ |
| 82 | + |
| 83 | + def __init__( |
| 84 | + self, |
| 85 | + include_app_labels: Optional[List[str]] = None, |
| 86 | + exclude_app_labels: Optional[List[str]] = None, |
| 87 | + ): |
| 88 | + self.include_app_labels = include_app_labels |
| 89 | + self.exclude_app_labels = exclude_app_labels |
| 90 | + |
| 91 | + def _iter_apps(self, apps: Apps): |
| 92 | + for app_config in apps.get_app_configs(): |
| 93 | + if self.exclude_app_labels is not None and app_config.label in self.exclude_app_labels: |
| 94 | + continue |
| 95 | + if self.include_app_labels is None or app_config.label in self.include_app_labels: |
| 96 | + yield app_config |
| 97 | + |
| 98 | + def __call__(self, apps: Apps, schema_editor: BaseDatabaseSchemaEditor): |
| 99 | + """ |
| 100 | + Loops through all relevant django apps and their models, checking if the model's table has |
| 101 | + FKs, and if so, runs the schema editor's utility that synchronizes the schema to the model, |
| 102 | + which will make FKs deferrable |
| 103 | + """ |
| 104 | + conn = schema_editor.connection |
| 105 | + # these should be in sync, but since we call `_remake_table`, specific to this schema editor |
| 106 | + # class, we ensure we have the correct instance to begin with |
| 107 | + if conn.vendor != "sqlite" or not isinstance(schema_editor, DatabaseSchemaEditor): |
| 108 | + return |
| 109 | + |
| 110 | + for app_config in self._iter_apps(apps): |
| 111 | + for model in app_config.get_models(include_auto_created=True): |
| 112 | + if not router.allow_migrate_model(conn.alias, model): |
| 113 | + continue |
| 114 | + table_name = model._meta.db_table |
| 115 | + if not _table_has_immediate_foreign_key(conn, table_name): |
| 116 | + continue |
| 117 | + logger.info( |
| 118 | + "Rebuilding table %s to make foreign key constraints deferrable", |
| 119 | + table_name, |
| 120 | + ) |
| 121 | + try: |
| 122 | + # Rebuilding the table from the current model state regenerates the column |
| 123 | + # definitions, which SQLite always emits with the deferrable clause (see |
| 124 | + # DatabaseSchemaEditor.sql_create_inline_fk). Only tested with Django 3.2 |
| 125 | + schema_editor._remake_table(model) |
| 126 | + except DatabaseError as e: |
| 127 | + logger.error("Failed to rebuild table %s", table_name) |
| 128 | + logger.exception(e) |
| 129 | + |
| 130 | + def run(self): |
| 131 | + """ |
| 132 | + Invoke this utility outside of Django migrations, manually passing in Django's app registry |
| 133 | + and schema editor. |
| 134 | + """ |
| 135 | + # since this method is meant for manual invocation, we let the editor create a transaction |
| 136 | + with connection.schema_editor(atomic=True) as schema_editor: |
| 137 | + self.__call__(global_apps, schema_editor) |
0 commit comments