schema.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. import copy
  2. from decimal import Decimal
  3. from django.apps.registry import Apps
  4. from django.db import NotSupportedError
  5. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  6. from django.db.backends.ddl_references import Statement
  7. from django.db.backends.utils import strip_quotes
  8. from django.db.models import UniqueConstraint
  9. from django.db.transaction import atomic
  10. class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
  11. sql_delete_table = "DROP TABLE %(table)s"
  12. sql_create_fk = None
  13. sql_create_inline_fk = (
  14. "REFERENCES %(to_table)s (%(to_column)s) DEFERRABLE INITIALLY DEFERRED"
  15. )
  16. sql_create_column_inline_fk = sql_create_inline_fk
  17. sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s"
  18. sql_create_unique = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)"
  19. sql_delete_unique = "DROP INDEX %(name)s"
  20. sql_alter_table_comment = None
  21. sql_alter_column_comment = None
  22. def __enter__(self):
  23. # Some SQLite schema alterations need foreign key constraints to be
  24. # disabled. Enforce it here for the duration of the schema edition.
  25. if not self.connection.disable_constraint_checking():
  26. raise NotSupportedError(
  27. "SQLite schema editor cannot be used while foreign key "
  28. "constraint checks are enabled. Make sure to disable them "
  29. "before entering a transaction.atomic() context because "
  30. "SQLite does not support disabling them in the middle of "
  31. "a multi-statement transaction."
  32. )
  33. return super().__enter__()
  34. def __exit__(self, exc_type, exc_value, traceback):
  35. self.connection.check_constraints()
  36. super().__exit__(exc_type, exc_value, traceback)
  37. self.connection.enable_constraint_checking()
  38. def quote_value(self, value):
  39. # The backend "mostly works" without this function and there are use
  40. # cases for compiling Python without the sqlite3 libraries (e.g.
  41. # security hardening).
  42. try:
  43. import sqlite3
  44. value = sqlite3.adapt(value)
  45. except ImportError:
  46. pass
  47. except sqlite3.ProgrammingError:
  48. pass
  49. # Manual emulation of SQLite parameter quoting
  50. if isinstance(value, bool):
  51. return str(int(value))
  52. elif isinstance(value, (Decimal, float, int)):
  53. return str(value)
  54. elif isinstance(value, str):
  55. return "'%s'" % value.replace("'", "''")
  56. elif value is None:
  57. return "NULL"
  58. elif isinstance(value, (bytes, bytearray, memoryview)):
  59. # Bytes are only allowed for BLOB fields, encoded as string
  60. # literals containing hexadecimal data and preceded by a single "X"
  61. # character.
  62. return "X'%s'" % value.hex()
  63. else:
  64. raise ValueError(
  65. "Cannot quote parameter value %r of type %s" % (value, type(value))
  66. )
  67. def prepare_default(self, value):
  68. return self.quote_value(value)
  69. def _is_referenced_by_fk_constraint(
  70. self, table_name, column_name=None, ignore_self=False
  71. ):
  72. """
  73. Return whether or not the provided table name is referenced by another
  74. one. If `column_name` is specified, only references pointing to that
  75. column are considered. If `ignore_self` is True, self-referential
  76. constraints are ignored.
  77. """
  78. with self.connection.cursor() as cursor:
  79. for other_table in self.connection.introspection.get_table_list(cursor):
  80. if ignore_self and other_table.name == table_name:
  81. continue
  82. relations = self.connection.introspection.get_relations(
  83. cursor, other_table.name
  84. )
  85. for constraint_column, constraint_table in relations.values():
  86. if constraint_table == table_name and (
  87. column_name is None or constraint_column == column_name
  88. ):
  89. return True
  90. return False
  91. def alter_db_table(
  92. self, model, old_db_table, new_db_table, disable_constraints=True
  93. ):
  94. if (
  95. not self.connection.features.supports_atomic_references_rename
  96. and disable_constraints
  97. and self._is_referenced_by_fk_constraint(old_db_table)
  98. ):
  99. if self.connection.in_atomic_block:
  100. raise NotSupportedError(
  101. (
  102. "Renaming the %r table while in a transaction is not "
  103. "supported on SQLite < 3.26 because it would break referential "
  104. "integrity. Try adding `atomic = False` to the Migration class."
  105. )
  106. % old_db_table
  107. )
  108. self.connection.enable_constraint_checking()
  109. super().alter_db_table(model, old_db_table, new_db_table)
  110. self.connection.disable_constraint_checking()
  111. else:
  112. super().alter_db_table(model, old_db_table, new_db_table)
  113. def alter_field(self, model, old_field, new_field, strict=False):
  114. if not self._field_should_be_altered(old_field, new_field):
  115. return
  116. old_field_name = old_field.name
  117. table_name = model._meta.db_table
  118. _, old_column_name = old_field.get_attname_column()
  119. if (
  120. new_field.name != old_field_name
  121. and not self.connection.features.supports_atomic_references_rename
  122. and self._is_referenced_by_fk_constraint(
  123. table_name, old_column_name, ignore_self=True
  124. )
  125. ):
  126. if self.connection.in_atomic_block:
  127. raise NotSupportedError(
  128. (
  129. "Renaming the %r.%r column while in a transaction is not "
  130. "supported on SQLite < 3.26 because it would break referential "
  131. "integrity. Try adding `atomic = False` to the Migration class."
  132. )
  133. % (model._meta.db_table, old_field_name)
  134. )
  135. with atomic(self.connection.alias):
  136. super().alter_field(model, old_field, new_field, strict=strict)
  137. # Follow SQLite's documented procedure for performing changes
  138. # that don't affect the on-disk content.
  139. # https://sqlite.org/lang_altertable.html#otheralter
  140. with self.connection.cursor() as cursor:
  141. schema_version = cursor.execute("PRAGMA schema_version").fetchone()[
  142. 0
  143. ]
  144. cursor.execute("PRAGMA writable_schema = 1")
  145. references_template = ' REFERENCES "%s" ("%%s") ' % table_name
  146. new_column_name = new_field.get_attname_column()[1]
  147. search = references_template % old_column_name
  148. replacement = references_template % new_column_name
  149. cursor.execute(
  150. "UPDATE sqlite_master SET sql = replace(sql, %s, %s)",
  151. (search, replacement),
  152. )
  153. cursor.execute("PRAGMA schema_version = %d" % (schema_version + 1))
  154. cursor.execute("PRAGMA writable_schema = 0")
  155. # The integrity check will raise an exception and rollback
  156. # the transaction if the sqlite_master updates corrupt the
  157. # database.
  158. cursor.execute("PRAGMA integrity_check")
  159. # Perform a VACUUM to refresh the database representation from
  160. # the sqlite_master table.
  161. with self.connection.cursor() as cursor:
  162. cursor.execute("VACUUM")
  163. else:
  164. super().alter_field(model, old_field, new_field, strict=strict)
  165. def _remake_table(
  166. self, model, create_field=None, delete_field=None, alter_fields=None
  167. ):
  168. """
  169. Shortcut to transform a model from old_model into new_model
  170. This follows the correct procedure to perform non-rename or column
  171. addition operations based on SQLite's documentation
  172. https://www.sqlite.org/lang_altertable.html#caution
  173. The essential steps are:
  174. 1. Create a table with the updated definition called "new__app_model"
  175. 2. Copy the data from the existing "app_model" table to the new table
  176. 3. Drop the "app_model" table
  177. 4. Rename the "new__app_model" table to "app_model"
  178. 5. Restore any index of the previous "app_model" table.
  179. """
  180. # Self-referential fields must be recreated rather than copied from
  181. # the old model to ensure their remote_field.field_name doesn't refer
  182. # to an altered field.
  183. def is_self_referential(f):
  184. return f.is_relation and f.remote_field.model is model
  185. # Work out the new fields dict / mapping
  186. body = {
  187. f.name: f.clone() if is_self_referential(f) else f
  188. for f in model._meta.local_concrete_fields
  189. }
  190. # Since mapping might mix column names and default values,
  191. # its values must be already quoted.
  192. mapping = {
  193. f.column: self.quote_name(f.column)
  194. for f in model._meta.local_concrete_fields
  195. }
  196. # This maps field names (not columns) for things like unique_together
  197. rename_mapping = {}
  198. # If any of the new or altered fields is introducing a new PK,
  199. # remove the old one
  200. restore_pk_field = None
  201. alter_fields = alter_fields or []
  202. if getattr(create_field, "primary_key", False) or any(
  203. getattr(new_field, "primary_key", False) for _, new_field in alter_fields
  204. ):
  205. for name, field in list(body.items()):
  206. if field.primary_key and not any(
  207. # Do not remove the old primary key when an altered field
  208. # that introduces a primary key is the same field.
  209. name == new_field.name
  210. for _, new_field in alter_fields
  211. ):
  212. field.primary_key = False
  213. restore_pk_field = field
  214. if field.auto_created:
  215. del body[name]
  216. del mapping[field.column]
  217. # Add in any created fields
  218. if create_field:
  219. body[create_field.name] = create_field
  220. # Choose a default and insert it into the copy map
  221. if not create_field.many_to_many and create_field.concrete:
  222. mapping[create_field.column] = self.prepare_default(
  223. self.effective_default(create_field),
  224. )
  225. # Add in any altered fields
  226. for alter_field in alter_fields:
  227. old_field, new_field = alter_field
  228. body.pop(old_field.name, None)
  229. mapping.pop(old_field.column, None)
  230. body[new_field.name] = new_field
  231. if old_field.null and not new_field.null:
  232. case_sql = "coalesce(%(col)s, %(default)s)" % {
  233. "col": self.quote_name(old_field.column),
  234. "default": self.prepare_default(self.effective_default(new_field)),
  235. }
  236. mapping[new_field.column] = case_sql
  237. else:
  238. mapping[new_field.column] = self.quote_name(old_field.column)
  239. rename_mapping[old_field.name] = new_field.name
  240. # Remove any deleted fields
  241. if delete_field:
  242. del body[delete_field.name]
  243. del mapping[delete_field.column]
  244. # Remove any implicit M2M tables
  245. if (
  246. delete_field.many_to_many
  247. and delete_field.remote_field.through._meta.auto_created
  248. ):
  249. return self.delete_model(delete_field.remote_field.through)
  250. # Work inside a new app registry
  251. apps = Apps()
  252. # Work out the new value of unique_together, taking renames into
  253. # account
  254. unique_together = [
  255. [rename_mapping.get(n, n) for n in unique]
  256. for unique in model._meta.unique_together
  257. ]
  258. # Work out the new value for index_together, taking renames into
  259. # account
  260. index_together = [
  261. [rename_mapping.get(n, n) for n in index]
  262. for index in model._meta.index_together
  263. ]
  264. indexes = model._meta.indexes
  265. if delete_field:
  266. indexes = [
  267. index for index in indexes if delete_field.name not in index.fields
  268. ]
  269. constraints = list(model._meta.constraints)
  270. # Provide isolated instances of the fields to the new model body so
  271. # that the existing model's internals aren't interfered with when
  272. # the dummy model is constructed.
  273. body_copy = copy.deepcopy(body)
  274. # Construct a new model with the new fields to allow self referential
  275. # primary key to resolve to. This model won't ever be materialized as a
  276. # table and solely exists for foreign key reference resolution purposes.
  277. # This wouldn't be required if the schema editor was operating on model
  278. # states instead of rendered models.
  279. meta_contents = {
  280. "app_label": model._meta.app_label,
  281. "db_table": model._meta.db_table,
  282. "unique_together": unique_together,
  283. "index_together": index_together,
  284. "indexes": indexes,
  285. "constraints": constraints,
  286. "apps": apps,
  287. }
  288. meta = type("Meta", (), meta_contents)
  289. body_copy["Meta"] = meta
  290. body_copy["__module__"] = model.__module__
  291. type(model._meta.object_name, model.__bases__, body_copy)
  292. # Construct a model with a renamed table name.
  293. body_copy = copy.deepcopy(body)
  294. meta_contents = {
  295. "app_label": model._meta.app_label,
  296. "db_table": "new__%s" % strip_quotes(model._meta.db_table),
  297. "unique_together": unique_together,
  298. "index_together": index_together,
  299. "indexes": indexes,
  300. "constraints": constraints,
  301. "apps": apps,
  302. }
  303. meta = type("Meta", (), meta_contents)
  304. body_copy["Meta"] = meta
  305. body_copy["__module__"] = model.__module__
  306. new_model = type("New%s" % model._meta.object_name, model.__bases__, body_copy)
  307. # Create a new table with the updated schema.
  308. self.create_model(new_model)
  309. # Copy data from the old table into the new table
  310. self.execute(
  311. "INSERT INTO %s (%s) SELECT %s FROM %s"
  312. % (
  313. self.quote_name(new_model._meta.db_table),
  314. ", ".join(self.quote_name(x) for x in mapping),
  315. ", ".join(mapping.values()),
  316. self.quote_name(model._meta.db_table),
  317. )
  318. )
  319. # Delete the old table to make way for the new
  320. self.delete_model(model, handle_autom2m=False)
  321. # Rename the new table to take way for the old
  322. self.alter_db_table(
  323. new_model,
  324. new_model._meta.db_table,
  325. model._meta.db_table,
  326. disable_constraints=False,
  327. )
  328. # Run deferred SQL on correct table
  329. for sql in self.deferred_sql:
  330. self.execute(sql)
  331. self.deferred_sql = []
  332. # Fix any PK-removed field
  333. if restore_pk_field:
  334. restore_pk_field.primary_key = True
  335. def delete_model(self, model, handle_autom2m=True):
  336. if handle_autom2m:
  337. super().delete_model(model)
  338. else:
  339. # Delete the table (and only that)
  340. self.execute(
  341. self.sql_delete_table
  342. % {
  343. "table": self.quote_name(model._meta.db_table),
  344. }
  345. )
  346. # Remove all deferred statements referencing the deleted table.
  347. for sql in list(self.deferred_sql):
  348. if isinstance(sql, Statement) and sql.references_table(
  349. model._meta.db_table
  350. ):
  351. self.deferred_sql.remove(sql)
  352. def add_field(self, model, field):
  353. """Create a field on a model."""
  354. # Special-case implicit M2M tables.
  355. if field.many_to_many and field.remote_field.through._meta.auto_created:
  356. self.create_model(field.remote_field.through)
  357. elif (
  358. # Primary keys and unique fields are not supported in ALTER TABLE
  359. # ADD COLUMN.
  360. field.primary_key
  361. or field.unique
  362. or
  363. # Fields with default values cannot by handled by ALTER TABLE ADD
  364. # COLUMN statement because DROP DEFAULT is not supported in
  365. # ALTER TABLE.
  366. not field.null
  367. or self.effective_default(field) is not None
  368. ):
  369. self._remake_table(model, create_field=field)
  370. else:
  371. super().add_field(model, field)
  372. def remove_field(self, model, field):
  373. """
  374. Remove a field from a model. Usually involves deleting a column,
  375. but for M2Ms may involve deleting a table.
  376. """
  377. # M2M fields are a special case
  378. if field.many_to_many:
  379. # For implicit M2M tables, delete the auto-created table
  380. if field.remote_field.through._meta.auto_created:
  381. self.delete_model(field.remote_field.through)
  382. # For explicit "through" M2M fields, do nothing
  383. elif (
  384. self.connection.features.can_alter_table_drop_column
  385. # Primary keys, unique fields, indexed fields, and foreign keys are
  386. # not supported in ALTER TABLE DROP COLUMN.
  387. and not field.primary_key
  388. and not field.unique
  389. and not field.db_index
  390. and not (field.remote_field and field.db_constraint)
  391. ):
  392. super().remove_field(model, field)
  393. # For everything else, remake.
  394. else:
  395. # It might not actually have a column behind it
  396. if field.db_parameters(connection=self.connection)["type"] is None:
  397. return
  398. self._remake_table(model, delete_field=field)
  399. def _alter_field(
  400. self,
  401. model,
  402. old_field,
  403. new_field,
  404. old_type,
  405. new_type,
  406. old_db_params,
  407. new_db_params,
  408. strict=False,
  409. ):
  410. """Perform a "physical" (non-ManyToMany) field update."""
  411. # Use "ALTER TABLE ... RENAME COLUMN" if only the column name
  412. # changed and there aren't any constraints.
  413. if (
  414. self.connection.features.can_alter_table_rename_column
  415. and old_field.column != new_field.column
  416. and self.column_sql(model, old_field) == self.column_sql(model, new_field)
  417. and not (
  418. old_field.remote_field
  419. and old_field.db_constraint
  420. or new_field.remote_field
  421. and new_field.db_constraint
  422. )
  423. ):
  424. return self.execute(
  425. self._rename_field_sql(
  426. model._meta.db_table, old_field, new_field, new_type
  427. )
  428. )
  429. # Alter by remaking table
  430. self._remake_table(model, alter_fields=[(old_field, new_field)])
  431. # Rebuild tables with FKs pointing to this field.
  432. old_collation = old_db_params.get("collation")
  433. new_collation = new_db_params.get("collation")
  434. if new_field.unique and (
  435. old_type != new_type or old_collation != new_collation
  436. ):
  437. related_models = set()
  438. opts = new_field.model._meta
  439. for remote_field in opts.related_objects:
  440. # Ignore self-relationship since the table was already rebuilt.
  441. if remote_field.related_model == model:
  442. continue
  443. if not remote_field.many_to_many:
  444. if remote_field.field_name == new_field.name:
  445. related_models.add(remote_field.related_model)
  446. elif new_field.primary_key and remote_field.through._meta.auto_created:
  447. related_models.add(remote_field.through)
  448. if new_field.primary_key:
  449. for many_to_many in opts.many_to_many:
  450. # Ignore self-relationship since the table was already rebuilt.
  451. if many_to_many.related_model == model:
  452. continue
  453. if many_to_many.remote_field.through._meta.auto_created:
  454. related_models.add(many_to_many.remote_field.through)
  455. for related_model in related_models:
  456. self._remake_table(related_model)
  457. def _alter_many_to_many(self, model, old_field, new_field, strict):
  458. """Alter M2Ms to repoint their to= endpoints."""
  459. if (
  460. old_field.remote_field.through._meta.db_table
  461. == new_field.remote_field.through._meta.db_table
  462. ):
  463. # The field name didn't change, but some options did, so we have to
  464. # propagate this altering.
  465. self._remake_table(
  466. old_field.remote_field.through,
  467. alter_fields=[
  468. (
  469. # The field that points to the target model is needed,
  470. # so that table can be remade with the new m2m field -
  471. # this is m2m_reverse_field_name().
  472. old_field.remote_field.through._meta.get_field(
  473. old_field.m2m_reverse_field_name()
  474. ),
  475. new_field.remote_field.through._meta.get_field(
  476. new_field.m2m_reverse_field_name()
  477. ),
  478. ),
  479. (
  480. # The field that points to the model itself is needed,
  481. # so that table can be remade with the new self field -
  482. # this is m2m_field_name().
  483. old_field.remote_field.through._meta.get_field(
  484. old_field.m2m_field_name()
  485. ),
  486. new_field.remote_field.through._meta.get_field(
  487. new_field.m2m_field_name()
  488. ),
  489. ),
  490. ],
  491. )
  492. return
  493. # Make a new through table
  494. self.create_model(new_field.remote_field.through)
  495. # Copy the data across
  496. self.execute(
  497. "INSERT INTO %s (%s) SELECT %s FROM %s"
  498. % (
  499. self.quote_name(new_field.remote_field.through._meta.db_table),
  500. ", ".join(
  501. [
  502. "id",
  503. new_field.m2m_column_name(),
  504. new_field.m2m_reverse_name(),
  505. ]
  506. ),
  507. ", ".join(
  508. [
  509. "id",
  510. old_field.m2m_column_name(),
  511. old_field.m2m_reverse_name(),
  512. ]
  513. ),
  514. self.quote_name(old_field.remote_field.through._meta.db_table),
  515. )
  516. )
  517. # Delete the old through table
  518. self.delete_model(old_field.remote_field.through)
  519. def add_constraint(self, model, constraint):
  520. if isinstance(constraint, UniqueConstraint) and (
  521. constraint.condition
  522. or constraint.contains_expressions
  523. or constraint.include
  524. or constraint.deferrable
  525. ):
  526. super().add_constraint(model, constraint)
  527. else:
  528. self._remake_table(model)
  529. def remove_constraint(self, model, constraint):
  530. if isinstance(constraint, UniqueConstraint) and (
  531. constraint.condition
  532. or constraint.contains_expressions
  533. or constraint.include
  534. or constraint.deferrable
  535. ):
  536. super().remove_constraint(model, constraint)
  537. else:
  538. self._remake_table(model)
  539. def _collate_sql(self, collation):
  540. return "COLLATE " + collation