schema.py 20 KB

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