schema.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. import logging
  2. from datetime import datetime
  3. from django.db.backends.ddl_references import (
  4. Columns, ForeignKeyName, IndexName, Statement, Table,
  5. )
  6. from django.db.backends.utils import names_digest, split_identifier
  7. from django.db.models import Deferrable, Index
  8. from django.db.transaction import TransactionManagementError, atomic
  9. from django.utils import timezone
  10. logger = logging.getLogger('django.db.backends.schema')
  11. def _is_relevant_relation(relation, altered_field):
  12. """
  13. When altering the given field, must constraints on its model from the given
  14. relation be temporarily dropped?
  15. """
  16. field = relation.field
  17. if field.many_to_many:
  18. # M2M reverse field
  19. return False
  20. if altered_field.primary_key and field.to_fields == [None]:
  21. # Foreign key constraint on the primary key, which is being altered.
  22. return True
  23. # Is the constraint targeting the field being altered?
  24. return altered_field.name in field.to_fields
  25. def _all_related_fields(model):
  26. return model._meta._get_fields(forward=False, reverse=True, include_hidden=True)
  27. def _related_non_m2m_objects(old_field, new_field):
  28. # Filter out m2m objects from reverse relations.
  29. # Return (old_relation, new_relation) tuples.
  30. return zip(
  31. (obj for obj in _all_related_fields(old_field.model) if _is_relevant_relation(obj, old_field)),
  32. (obj for obj in _all_related_fields(new_field.model) if _is_relevant_relation(obj, new_field)),
  33. )
  34. class BaseDatabaseSchemaEditor:
  35. """
  36. This class and its subclasses are responsible for emitting schema-changing
  37. statements to the databases - model creation/removal/alteration, field
  38. renaming, index fiddling, and so on.
  39. """
  40. # Overrideable SQL templates
  41. sql_create_table = "CREATE TABLE %(table)s (%(definition)s)"
  42. sql_rename_table = "ALTER TABLE %(old_table)s RENAME TO %(new_table)s"
  43. sql_retablespace_table = "ALTER TABLE %(table)s SET TABLESPACE %(new_tablespace)s"
  44. sql_delete_table = "DROP TABLE %(table)s CASCADE"
  45. sql_create_column = "ALTER TABLE %(table)s ADD COLUMN %(column)s %(definition)s"
  46. sql_alter_column = "ALTER TABLE %(table)s %(changes)s"
  47. sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s"
  48. sql_alter_column_null = "ALTER COLUMN %(column)s DROP NOT NULL"
  49. sql_alter_column_not_null = "ALTER COLUMN %(column)s SET NOT NULL"
  50. sql_alter_column_default = "ALTER COLUMN %(column)s SET DEFAULT %(default)s"
  51. sql_alter_column_no_default = "ALTER COLUMN %(column)s DROP DEFAULT"
  52. sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s CASCADE"
  53. sql_rename_column = "ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s"
  54. sql_update_with_default = "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL"
  55. sql_unique_constraint = "UNIQUE (%(columns)s)%(deferrable)s"
  56. sql_check_constraint = "CHECK (%(check)s)"
  57. sql_delete_constraint = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
  58. sql_constraint = "CONSTRAINT %(name)s %(constraint)s"
  59. sql_create_check = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)"
  60. sql_delete_check = sql_delete_constraint
  61. sql_create_unique = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s UNIQUE (%(columns)s)%(deferrable)s"
  62. sql_delete_unique = sql_delete_constraint
  63. sql_create_fk = (
  64. "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) "
  65. "REFERENCES %(to_table)s (%(to_column)s)%(deferrable)s"
  66. )
  67. sql_create_inline_fk = None
  68. sql_create_column_inline_fk = None
  69. sql_delete_fk = sql_delete_constraint
  70. sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(include)s%(extra)s%(condition)s"
  71. sql_create_unique_index = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(include)s%(condition)s"
  72. sql_delete_index = "DROP INDEX %(name)s"
  73. sql_create_pk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
  74. sql_delete_pk = sql_delete_constraint
  75. sql_delete_procedure = 'DROP PROCEDURE %(procedure)s'
  76. def __init__(self, connection, collect_sql=False, atomic=True):
  77. self.connection = connection
  78. self.collect_sql = collect_sql
  79. if self.collect_sql:
  80. self.collected_sql = []
  81. self.atomic_migration = self.connection.features.can_rollback_ddl and atomic
  82. # State-managing methods
  83. def __enter__(self):
  84. self.deferred_sql = []
  85. if self.atomic_migration:
  86. self.atomic = atomic(self.connection.alias)
  87. self.atomic.__enter__()
  88. return self
  89. def __exit__(self, exc_type, exc_value, traceback):
  90. if exc_type is None:
  91. for sql in self.deferred_sql:
  92. self.execute(sql)
  93. if self.atomic_migration:
  94. self.atomic.__exit__(exc_type, exc_value, traceback)
  95. # Core utility functions
  96. def execute(self, sql, params=()):
  97. """Execute the given SQL statement, with optional parameters."""
  98. # Don't perform the transactional DDL check if SQL is being collected
  99. # as it's not going to be executed anyway.
  100. if not self.collect_sql and self.connection.in_atomic_block and not self.connection.features.can_rollback_ddl:
  101. raise TransactionManagementError(
  102. "Executing DDL statements while in a transaction on databases "
  103. "that can't perform a rollback is prohibited."
  104. )
  105. # Account for non-string statement objects.
  106. sql = str(sql)
  107. # Log the command we're running, then run it
  108. logger.debug("%s; (params %r)", sql, params, extra={'params': params, 'sql': sql})
  109. if self.collect_sql:
  110. ending = "" if sql.endswith(";") else ";"
  111. if params is not None:
  112. self.collected_sql.append((sql % tuple(map(self.quote_value, params))) + ending)
  113. else:
  114. self.collected_sql.append(sql + ending)
  115. else:
  116. with self.connection.cursor() as cursor:
  117. cursor.execute(sql, params)
  118. def quote_name(self, name):
  119. return self.connection.ops.quote_name(name)
  120. def table_sql(self, model):
  121. """Take a model and return its table definition."""
  122. # Add any unique_togethers (always deferred, as some fields might be
  123. # created afterwards, like geometry fields with some backends).
  124. for fields in model._meta.unique_together:
  125. columns = [model._meta.get_field(field).column for field in fields]
  126. self.deferred_sql.append(self._create_unique_sql(model, columns))
  127. # Create column SQL, add FK deferreds if needed.
  128. column_sqls = []
  129. params = []
  130. for field in model._meta.local_fields:
  131. # SQL.
  132. definition, extra_params = self.column_sql(model, field)
  133. if definition is None:
  134. continue
  135. # Check constraints can go on the column SQL here.
  136. db_params = field.db_parameters(connection=self.connection)
  137. if db_params['check']:
  138. definition += ' ' + self.sql_check_constraint % db_params
  139. # Autoincrement SQL (for backends with inline variant).
  140. col_type_suffix = field.db_type_suffix(connection=self.connection)
  141. if col_type_suffix:
  142. definition += ' %s' % col_type_suffix
  143. params.extend(extra_params)
  144. # FK.
  145. if field.remote_field and field.db_constraint:
  146. to_table = field.remote_field.model._meta.db_table
  147. to_column = field.remote_field.model._meta.get_field(field.remote_field.field_name).column
  148. if self.sql_create_inline_fk:
  149. definition += ' ' + self.sql_create_inline_fk % {
  150. 'to_table': self.quote_name(to_table),
  151. 'to_column': self.quote_name(to_column),
  152. }
  153. elif self.connection.features.supports_foreign_keys:
  154. self.deferred_sql.append(self._create_fk_sql(model, field, '_fk_%(to_table)s_%(to_column)s'))
  155. # Add the SQL to our big list.
  156. column_sqls.append('%s %s' % (
  157. self.quote_name(field.column),
  158. definition,
  159. ))
  160. # Autoincrement SQL (for backends with post table definition
  161. # variant).
  162. if field.get_internal_type() in ('AutoField', 'BigAutoField', 'SmallAutoField'):
  163. autoinc_sql = self.connection.ops.autoinc_sql(model._meta.db_table, field.column)
  164. if autoinc_sql:
  165. self.deferred_sql.extend(autoinc_sql)
  166. constraints = [constraint.constraint_sql(model, self) for constraint in model._meta.constraints]
  167. sql = self.sql_create_table % {
  168. 'table': self.quote_name(model._meta.db_table),
  169. 'definition': ', '.join(constraint for constraint in (*column_sqls, *constraints) if constraint),
  170. }
  171. if model._meta.db_tablespace:
  172. tablespace_sql = self.connection.ops.tablespace_sql(model._meta.db_tablespace)
  173. if tablespace_sql:
  174. sql += ' ' + tablespace_sql
  175. return sql, params
  176. # Field <-> database mapping functions
  177. def column_sql(self, model, field, include_default=False):
  178. """
  179. Take a field and return its column definition.
  180. The field must already have had set_attributes_from_name() called.
  181. """
  182. # Get the column's type and use that as the basis of the SQL
  183. db_params = field.db_parameters(connection=self.connection)
  184. sql = db_params['type']
  185. params = []
  186. # Check for fields that aren't actually columns (e.g. M2M)
  187. if sql is None:
  188. return None, None
  189. # Work out nullability
  190. null = field.null
  191. # If we were told to include a default value, do so
  192. include_default = include_default and not self.skip_default(field)
  193. if include_default:
  194. default_value = self.effective_default(field)
  195. column_default = ' DEFAULT ' + self._column_default_sql(field)
  196. if default_value is not None:
  197. if self.connection.features.requires_literal_defaults:
  198. # Some databases can't take defaults as a parameter (oracle)
  199. # If this is the case, the individual schema backend should
  200. # implement prepare_default
  201. sql += column_default % self.prepare_default(default_value)
  202. else:
  203. sql += column_default
  204. params += [default_value]
  205. # Oracle treats the empty string ('') as null, so coerce the null
  206. # option whenever '' is a possible value.
  207. if (field.empty_strings_allowed and not field.primary_key and
  208. self.connection.features.interprets_empty_strings_as_nulls):
  209. null = True
  210. if null and not self.connection.features.implied_column_null:
  211. sql += " NULL"
  212. elif not null:
  213. sql += " NOT NULL"
  214. # Primary key/unique outputs
  215. if field.primary_key:
  216. sql += " PRIMARY KEY"
  217. elif field.unique:
  218. sql += " UNIQUE"
  219. # Optionally add the tablespace if it's an implicitly indexed column
  220. tablespace = field.db_tablespace or model._meta.db_tablespace
  221. if tablespace and self.connection.features.supports_tablespaces and field.unique:
  222. sql += " %s" % self.connection.ops.tablespace_sql(tablespace, inline=True)
  223. # Return the sql
  224. return sql, params
  225. def skip_default(self, field):
  226. """
  227. Some backends don't accept default values for certain columns types
  228. (i.e. MySQL longtext and longblob).
  229. """
  230. return False
  231. def prepare_default(self, value):
  232. """
  233. Only used for backends which have requires_literal_defaults feature
  234. """
  235. raise NotImplementedError(
  236. 'subclasses of BaseDatabaseSchemaEditor for backends which have '
  237. 'requires_literal_defaults must provide a prepare_default() method'
  238. )
  239. def _column_default_sql(self, field):
  240. """
  241. Return the SQL to use in a DEFAULT clause. The resulting string should
  242. contain a '%s' placeholder for a default value.
  243. """
  244. return '%s'
  245. @staticmethod
  246. def _effective_default(field):
  247. # This method allows testing its logic without a connection.
  248. if field.has_default():
  249. default = field.get_default()
  250. elif not field.null and field.blank and field.empty_strings_allowed:
  251. if field.get_internal_type() == "BinaryField":
  252. default = b''
  253. else:
  254. default = ''
  255. elif getattr(field, 'auto_now', False) or getattr(field, 'auto_now_add', False):
  256. default = datetime.now()
  257. internal_type = field.get_internal_type()
  258. if internal_type == 'DateField':
  259. default = default.date()
  260. elif internal_type == 'TimeField':
  261. default = default.time()
  262. elif internal_type == 'DateTimeField':
  263. default = timezone.now()
  264. else:
  265. default = None
  266. return default
  267. def effective_default(self, field):
  268. """Return a field's effective database default value."""
  269. return field.get_db_prep_save(self._effective_default(field), self.connection)
  270. def quote_value(self, value):
  271. """
  272. Return a quoted version of the value so it's safe to use in an SQL
  273. string. This is not safe against injection from user code; it is
  274. intended only for use in making SQL scripts or preparing default values
  275. for particularly tricky backends (defaults are not user-defined, though,
  276. so this is safe).
  277. """
  278. raise NotImplementedError()
  279. # Actions
  280. def create_model(self, model):
  281. """
  282. Create a table and any accompanying indexes or unique constraints for
  283. the given `model`.
  284. """
  285. sql, params = self.table_sql(model)
  286. # Prevent using [] as params, in the case a literal '%' is used in the definition
  287. self.execute(sql, params or None)
  288. # Add any field index and index_together's (deferred as SQLite _remake_table needs it)
  289. self.deferred_sql.extend(self._model_indexes_sql(model))
  290. # Make M2M tables
  291. for field in model._meta.local_many_to_many:
  292. if field.remote_field.through._meta.auto_created:
  293. self.create_model(field.remote_field.through)
  294. def delete_model(self, model):
  295. """Delete a model from the database."""
  296. # Handle auto-created intermediary models
  297. for field in model._meta.local_many_to_many:
  298. if field.remote_field.through._meta.auto_created:
  299. self.delete_model(field.remote_field.through)
  300. # Delete the table
  301. self.execute(self.sql_delete_table % {
  302. "table": self.quote_name(model._meta.db_table),
  303. })
  304. # Remove all deferred statements referencing the deleted table.
  305. for sql in list(self.deferred_sql):
  306. if isinstance(sql, Statement) and sql.references_table(model._meta.db_table):
  307. self.deferred_sql.remove(sql)
  308. def add_index(self, model, index):
  309. """Add an index on a model."""
  310. self.execute(index.create_sql(model, self), params=None)
  311. def remove_index(self, model, index):
  312. """Remove an index from a model."""
  313. self.execute(index.remove_sql(model, self))
  314. def add_constraint(self, model, constraint):
  315. """Add a constraint to a model."""
  316. sql = constraint.create_sql(model, self)
  317. if sql:
  318. self.execute(sql)
  319. def remove_constraint(self, model, constraint):
  320. """Remove a constraint from a model."""
  321. sql = constraint.remove_sql(model, self)
  322. if sql:
  323. self.execute(sql)
  324. def alter_unique_together(self, model, old_unique_together, new_unique_together):
  325. """
  326. Deal with a model changing its unique_together. The input
  327. unique_togethers must be doubly-nested, not the single-nested
  328. ["foo", "bar"] format.
  329. """
  330. olds = {tuple(fields) for fields in old_unique_together}
  331. news = {tuple(fields) for fields in new_unique_together}
  332. # Deleted uniques
  333. for fields in olds.difference(news):
  334. self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)
  335. # Created uniques
  336. for fields in news.difference(olds):
  337. columns = [model._meta.get_field(field).column for field in fields]
  338. self.execute(self._create_unique_sql(model, columns))
  339. def alter_index_together(self, model, old_index_together, new_index_together):
  340. """
  341. Deal with a model changing its index_together. The input
  342. index_togethers must be doubly-nested, not the single-nested
  343. ["foo", "bar"] format.
  344. """
  345. olds = {tuple(fields) for fields in old_index_together}
  346. news = {tuple(fields) for fields in new_index_together}
  347. # Deleted indexes
  348. for fields in olds.difference(news):
  349. self._delete_composed_index(
  350. model,
  351. fields,
  352. {'index': True, 'unique': False},
  353. self.sql_delete_index,
  354. )
  355. # Created indexes
  356. for field_names in news.difference(olds):
  357. fields = [model._meta.get_field(field) for field in field_names]
  358. self.execute(self._create_index_sql(model, fields, suffix="_idx"))
  359. def _delete_composed_index(self, model, fields, constraint_kwargs, sql):
  360. meta_constraint_names = {constraint.name for constraint in model._meta.constraints}
  361. meta_index_names = {constraint.name for constraint in model._meta.indexes}
  362. columns = [model._meta.get_field(field).column for field in fields]
  363. constraint_names = self._constraint_names(
  364. model, columns, exclude=meta_constraint_names | meta_index_names,
  365. **constraint_kwargs
  366. )
  367. if len(constraint_names) != 1:
  368. raise ValueError("Found wrong number (%s) of constraints for %s(%s)" % (
  369. len(constraint_names),
  370. model._meta.db_table,
  371. ", ".join(columns),
  372. ))
  373. self.execute(self._delete_constraint_sql(sql, model, constraint_names[0]))
  374. def alter_db_table(self, model, old_db_table, new_db_table):
  375. """Rename the table a model points to."""
  376. if (old_db_table == new_db_table or
  377. (self.connection.features.ignores_table_name_case and
  378. old_db_table.lower() == new_db_table.lower())):
  379. return
  380. self.execute(self.sql_rename_table % {
  381. "old_table": self.quote_name(old_db_table),
  382. "new_table": self.quote_name(new_db_table),
  383. })
  384. # Rename all references to the old table name.
  385. for sql in self.deferred_sql:
  386. if isinstance(sql, Statement):
  387. sql.rename_table_references(old_db_table, new_db_table)
  388. def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):
  389. """Move a model's table between tablespaces."""
  390. self.execute(self.sql_retablespace_table % {
  391. "table": self.quote_name(model._meta.db_table),
  392. "old_tablespace": self.quote_name(old_db_tablespace),
  393. "new_tablespace": self.quote_name(new_db_tablespace),
  394. })
  395. def add_field(self, model, field):
  396. """
  397. Create a field on a model. Usually involves adding a column, but may
  398. involve adding a table instead (for M2M fields).
  399. """
  400. # Special-case implicit M2M tables
  401. if field.many_to_many and field.remote_field.through._meta.auto_created:
  402. return self.create_model(field.remote_field.through)
  403. # Get the column's definition
  404. definition, params = self.column_sql(model, field, include_default=True)
  405. # It might not actually have a column behind it
  406. if definition is None:
  407. return
  408. # Check constraints can go on the column SQL here
  409. db_params = field.db_parameters(connection=self.connection)
  410. if db_params['check']:
  411. definition += " " + self.sql_check_constraint % db_params
  412. if field.remote_field and self.connection.features.supports_foreign_keys and field.db_constraint:
  413. constraint_suffix = '_fk_%(to_table)s_%(to_column)s'
  414. # Add FK constraint inline, if supported.
  415. if self.sql_create_column_inline_fk:
  416. to_table = field.remote_field.model._meta.db_table
  417. to_column = field.remote_field.model._meta.get_field(field.remote_field.field_name).column
  418. definition += " " + self.sql_create_column_inline_fk % {
  419. 'name': self._fk_constraint_name(model, field, constraint_suffix),
  420. 'column': self.quote_name(field.column),
  421. 'to_table': self.quote_name(to_table),
  422. 'to_column': self.quote_name(to_column),
  423. 'deferrable': self.connection.ops.deferrable_sql()
  424. }
  425. # Otherwise, add FK constraints later.
  426. else:
  427. self.deferred_sql.append(self._create_fk_sql(model, field, constraint_suffix))
  428. # Build the SQL and run it
  429. sql = self.sql_create_column % {
  430. "table": self.quote_name(model._meta.db_table),
  431. "column": self.quote_name(field.column),
  432. "definition": definition,
  433. }
  434. self.execute(sql, params)
  435. # Drop the default if we need to
  436. # (Django usually does not use in-database defaults)
  437. if not self.skip_default(field) and self.effective_default(field) is not None:
  438. changes_sql, params = self._alter_column_default_sql(model, None, field, drop=True)
  439. sql = self.sql_alter_column % {
  440. "table": self.quote_name(model._meta.db_table),
  441. "changes": changes_sql,
  442. }
  443. self.execute(sql, params)
  444. # Add an index, if required
  445. self.deferred_sql.extend(self._field_indexes_sql(model, field))
  446. # Reset connection if required
  447. if self.connection.features.connection_persists_old_columns:
  448. self.connection.close()
  449. def remove_field(self, model, field):
  450. """
  451. Remove a field from a model. Usually involves deleting a column,
  452. but for M2Ms may involve deleting a table.
  453. """
  454. # Special-case implicit M2M tables
  455. if field.many_to_many and field.remote_field.through._meta.auto_created:
  456. return self.delete_model(field.remote_field.through)
  457. # It might not actually have a column behind it
  458. if field.db_parameters(connection=self.connection)['type'] is None:
  459. return
  460. # Drop any FK constraints, MySQL requires explicit deletion
  461. if field.remote_field:
  462. fk_names = self._constraint_names(model, [field.column], foreign_key=True)
  463. for fk_name in fk_names:
  464. self.execute(self._delete_fk_sql(model, fk_name))
  465. # Delete the column
  466. sql = self.sql_delete_column % {
  467. "table": self.quote_name(model._meta.db_table),
  468. "column": self.quote_name(field.column),
  469. }
  470. self.execute(sql)
  471. # Reset connection if required
  472. if self.connection.features.connection_persists_old_columns:
  473. self.connection.close()
  474. # Remove all deferred statements referencing the deleted column.
  475. for sql in list(self.deferred_sql):
  476. if isinstance(sql, Statement) and sql.references_column(model._meta.db_table, field.column):
  477. self.deferred_sql.remove(sql)
  478. def alter_field(self, model, old_field, new_field, strict=False):
  479. """
  480. Allow a field's type, uniqueness, nullability, default, column,
  481. constraints, etc. to be modified.
  482. `old_field` is required to compute the necessary changes.
  483. If `strict` is True, raise errors if the old column does not match
  484. `old_field` precisely.
  485. """
  486. # Ensure this field is even column-based
  487. old_db_params = old_field.db_parameters(connection=self.connection)
  488. old_type = old_db_params['type']
  489. new_db_params = new_field.db_parameters(connection=self.connection)
  490. new_type = new_db_params['type']
  491. if ((old_type is None and old_field.remote_field is None) or
  492. (new_type is None and new_field.remote_field is None)):
  493. raise ValueError(
  494. "Cannot alter field %s into %s - they do not properly define "
  495. "db_type (are you using a badly-written custom field?)" %
  496. (old_field, new_field),
  497. )
  498. elif old_type is None and new_type is None and (
  499. old_field.remote_field.through and new_field.remote_field.through and
  500. old_field.remote_field.through._meta.auto_created and
  501. new_field.remote_field.through._meta.auto_created):
  502. return self._alter_many_to_many(model, old_field, new_field, strict)
  503. elif old_type is None and new_type is None and (
  504. old_field.remote_field.through and new_field.remote_field.through and
  505. not old_field.remote_field.through._meta.auto_created and
  506. not new_field.remote_field.through._meta.auto_created):
  507. # Both sides have through models; this is a no-op.
  508. return
  509. elif old_type is None or new_type is None:
  510. raise ValueError(
  511. "Cannot alter field %s into %s - they are not compatible types "
  512. "(you cannot alter to or from M2M fields, or add or remove "
  513. "through= on M2M fields)" % (old_field, new_field)
  514. )
  515. self._alter_field(model, old_field, new_field, old_type, new_type,
  516. old_db_params, new_db_params, strict)
  517. def _alter_field(self, model, old_field, new_field, old_type, new_type,
  518. old_db_params, new_db_params, strict=False):
  519. """Perform a "physical" (non-ManyToMany) field update."""
  520. # Drop any FK constraints, we'll remake them later
  521. fks_dropped = set()
  522. if (
  523. self.connection.features.supports_foreign_keys and
  524. old_field.remote_field and
  525. old_field.db_constraint
  526. ):
  527. fk_names = self._constraint_names(model, [old_field.column], foreign_key=True)
  528. if strict and len(fk_names) != 1:
  529. raise ValueError("Found wrong number (%s) of foreign key constraints for %s.%s" % (
  530. len(fk_names),
  531. model._meta.db_table,
  532. old_field.column,
  533. ))
  534. for fk_name in fk_names:
  535. fks_dropped.add((old_field.column,))
  536. self.execute(self._delete_fk_sql(model, fk_name))
  537. # Has unique been removed?
  538. if old_field.unique and (not new_field.unique or self._field_became_primary_key(old_field, new_field)):
  539. # Find the unique constraint for this field
  540. meta_constraint_names = {constraint.name for constraint in model._meta.constraints}
  541. constraint_names = self._constraint_names(
  542. model, [old_field.column], unique=True, primary_key=False,
  543. exclude=meta_constraint_names,
  544. )
  545. if strict and len(constraint_names) != 1:
  546. raise ValueError("Found wrong number (%s) of unique constraints for %s.%s" % (
  547. len(constraint_names),
  548. model._meta.db_table,
  549. old_field.column,
  550. ))
  551. for constraint_name in constraint_names:
  552. self.execute(self._delete_unique_sql(model, constraint_name))
  553. # Drop incoming FK constraints if the field is a primary key or unique,
  554. # which might be a to_field target, and things are going to change.
  555. drop_foreign_keys = (
  556. self.connection.features.supports_foreign_keys and (
  557. (old_field.primary_key and new_field.primary_key) or
  558. (old_field.unique and new_field.unique)
  559. ) and old_type != new_type
  560. )
  561. if drop_foreign_keys:
  562. # '_meta.related_field' also contains M2M reverse fields, these
  563. # will be filtered out
  564. for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):
  565. rel_fk_names = self._constraint_names(
  566. new_rel.related_model, [new_rel.field.column], foreign_key=True
  567. )
  568. for fk_name in rel_fk_names:
  569. self.execute(self._delete_fk_sql(new_rel.related_model, fk_name))
  570. # Removed an index? (no strict check, as multiple indexes are possible)
  571. # Remove indexes if db_index switched to False or a unique constraint
  572. # will now be used in lieu of an index. The following lines from the
  573. # truth table show all True cases; the rest are False:
  574. #
  575. # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
  576. # ------------------------------------------------------------------------------
  577. # True | False | False | False
  578. # True | False | False | True
  579. # True | False | True | True
  580. if old_field.db_index and not old_field.unique and (not new_field.db_index or new_field.unique):
  581. # Find the index for this field
  582. meta_index_names = {index.name for index in model._meta.indexes}
  583. # Retrieve only BTREE indexes since this is what's created with
  584. # db_index=True.
  585. index_names = self._constraint_names(
  586. model, [old_field.column], index=True, type_=Index.suffix,
  587. exclude=meta_index_names,
  588. )
  589. for index_name in index_names:
  590. # The only way to check if an index was created with
  591. # db_index=True or with Index(['field'], name='foo')
  592. # is to look at its name (refs #28053).
  593. self.execute(self._delete_index_sql(model, index_name))
  594. # Change check constraints?
  595. if old_db_params['check'] != new_db_params['check'] and old_db_params['check']:
  596. meta_constraint_names = {constraint.name for constraint in model._meta.constraints}
  597. constraint_names = self._constraint_names(
  598. model, [old_field.column], check=True,
  599. exclude=meta_constraint_names,
  600. )
  601. if strict and len(constraint_names) != 1:
  602. raise ValueError("Found wrong number (%s) of check constraints for %s.%s" % (
  603. len(constraint_names),
  604. model._meta.db_table,
  605. old_field.column,
  606. ))
  607. for constraint_name in constraint_names:
  608. self.execute(self._delete_check_sql(model, constraint_name))
  609. # Have they renamed the column?
  610. if old_field.column != new_field.column:
  611. self.execute(self._rename_field_sql(model._meta.db_table, old_field, new_field, new_type))
  612. # Rename all references to the renamed column.
  613. for sql in self.deferred_sql:
  614. if isinstance(sql, Statement):
  615. sql.rename_column_references(model._meta.db_table, old_field.column, new_field.column)
  616. # Next, start accumulating actions to do
  617. actions = []
  618. null_actions = []
  619. post_actions = []
  620. # Type change?
  621. if old_type != new_type:
  622. fragment, other_actions = self._alter_column_type_sql(model, old_field, new_field, new_type)
  623. actions.append(fragment)
  624. post_actions.extend(other_actions)
  625. # When changing a column NULL constraint to NOT NULL with a given
  626. # default value, we need to perform 4 steps:
  627. # 1. Add a default for new incoming writes
  628. # 2. Update existing NULL rows with new default
  629. # 3. Replace NULL constraint with NOT NULL
  630. # 4. Drop the default again.
  631. # Default change?
  632. needs_database_default = False
  633. if old_field.null and not new_field.null:
  634. old_default = self.effective_default(old_field)
  635. new_default = self.effective_default(new_field)
  636. if (
  637. not self.skip_default(new_field) and
  638. old_default != new_default and
  639. new_default is not None
  640. ):
  641. needs_database_default = True
  642. actions.append(self._alter_column_default_sql(model, old_field, new_field))
  643. # Nullability change?
  644. if old_field.null != new_field.null:
  645. fragment = self._alter_column_null_sql(model, old_field, new_field)
  646. if fragment:
  647. null_actions.append(fragment)
  648. # Only if we have a default and there is a change from NULL to NOT NULL
  649. four_way_default_alteration = (
  650. new_field.has_default() and
  651. (old_field.null and not new_field.null)
  652. )
  653. if actions or null_actions:
  654. if not four_way_default_alteration:
  655. # If we don't have to do a 4-way default alteration we can
  656. # directly run a (NOT) NULL alteration
  657. actions = actions + null_actions
  658. # Combine actions together if we can (e.g. postgres)
  659. if self.connection.features.supports_combined_alters and actions:
  660. sql, params = tuple(zip(*actions))
  661. actions = [(", ".join(sql), sum(params, []))]
  662. # Apply those actions
  663. for sql, params in actions:
  664. self.execute(
  665. self.sql_alter_column % {
  666. "table": self.quote_name(model._meta.db_table),
  667. "changes": sql,
  668. },
  669. params,
  670. )
  671. if four_way_default_alteration:
  672. # Update existing rows with default value
  673. self.execute(
  674. self.sql_update_with_default % {
  675. "table": self.quote_name(model._meta.db_table),
  676. "column": self.quote_name(new_field.column),
  677. "default": "%s",
  678. },
  679. [new_default],
  680. )
  681. # Since we didn't run a NOT NULL change before we need to do it
  682. # now
  683. for sql, params in null_actions:
  684. self.execute(
  685. self.sql_alter_column % {
  686. "table": self.quote_name(model._meta.db_table),
  687. "changes": sql,
  688. },
  689. params,
  690. )
  691. if post_actions:
  692. for sql, params in post_actions:
  693. self.execute(sql, params)
  694. # If primary_key changed to False, delete the primary key constraint.
  695. if old_field.primary_key and not new_field.primary_key:
  696. self._delete_primary_key(model, strict)
  697. # Added a unique?
  698. if self._unique_should_be_added(old_field, new_field):
  699. self.execute(self._create_unique_sql(model, [new_field.column]))
  700. # Added an index? Add an index if db_index switched to True or a unique
  701. # constraint will no longer be used in lieu of an index. The following
  702. # lines from the truth table show all True cases; the rest are False:
  703. #
  704. # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
  705. # ------------------------------------------------------------------------------
  706. # False | False | True | False
  707. # False | True | True | False
  708. # True | True | True | False
  709. if (not old_field.db_index or old_field.unique) and new_field.db_index and not new_field.unique:
  710. self.execute(self._create_index_sql(model, [new_field]))
  711. # Type alteration on primary key? Then we need to alter the column
  712. # referring to us.
  713. rels_to_update = []
  714. if drop_foreign_keys:
  715. rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
  716. # Changed to become primary key?
  717. if self._field_became_primary_key(old_field, new_field):
  718. # Make the new one
  719. self.execute(self._create_primary_key_sql(model, new_field))
  720. # Update all referencing columns
  721. rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
  722. # Handle our type alters on the other end of rels from the PK stuff above
  723. for old_rel, new_rel in rels_to_update:
  724. rel_db_params = new_rel.field.db_parameters(connection=self.connection)
  725. rel_type = rel_db_params['type']
  726. fragment, other_actions = self._alter_column_type_sql(
  727. new_rel.related_model, old_rel.field, new_rel.field, rel_type
  728. )
  729. self.execute(
  730. self.sql_alter_column % {
  731. "table": self.quote_name(new_rel.related_model._meta.db_table),
  732. "changes": fragment[0],
  733. },
  734. fragment[1],
  735. )
  736. for sql, params in other_actions:
  737. self.execute(sql, params)
  738. # Does it have a foreign key?
  739. if (self.connection.features.supports_foreign_keys and new_field.remote_field and
  740. (fks_dropped or not old_field.remote_field or not old_field.db_constraint) and
  741. new_field.db_constraint):
  742. self.execute(self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s"))
  743. # Rebuild FKs that pointed to us if we previously had to drop them
  744. if drop_foreign_keys:
  745. for rel in new_field.model._meta.related_objects:
  746. if _is_relevant_relation(rel, new_field) and rel.field.db_constraint:
  747. self.execute(self._create_fk_sql(rel.related_model, rel.field, "_fk"))
  748. # Does it have check constraints we need to add?
  749. if old_db_params['check'] != new_db_params['check'] and new_db_params['check']:
  750. constraint_name = self._create_index_name(model._meta.db_table, [new_field.column], suffix='_check')
  751. self.execute(self._create_check_sql(model, constraint_name, new_db_params['check']))
  752. # Drop the default if we need to
  753. # (Django usually does not use in-database defaults)
  754. if needs_database_default:
  755. changes_sql, params = self._alter_column_default_sql(model, old_field, new_field, drop=True)
  756. sql = self.sql_alter_column % {
  757. "table": self.quote_name(model._meta.db_table),
  758. "changes": changes_sql,
  759. }
  760. self.execute(sql, params)
  761. # Reset connection if required
  762. if self.connection.features.connection_persists_old_columns:
  763. self.connection.close()
  764. def _alter_column_null_sql(self, model, old_field, new_field):
  765. """
  766. Hook to specialize column null alteration.
  767. Return a (sql, params) fragment to set a column to null or non-null
  768. as required by new_field, or None if no changes are required.
  769. """
  770. if (self.connection.features.interprets_empty_strings_as_nulls and
  771. new_field.get_internal_type() in ("CharField", "TextField")):
  772. # The field is nullable in the database anyway, leave it alone.
  773. return
  774. else:
  775. new_db_params = new_field.db_parameters(connection=self.connection)
  776. sql = self.sql_alter_column_null if new_field.null else self.sql_alter_column_not_null
  777. return (
  778. sql % {
  779. 'column': self.quote_name(new_field.column),
  780. 'type': new_db_params['type'],
  781. },
  782. [],
  783. )
  784. def _alter_column_default_sql(self, model, old_field, new_field, drop=False):
  785. """
  786. Hook to specialize column default alteration.
  787. Return a (sql, params) fragment to add or drop (depending on the drop
  788. argument) a default to new_field's column.
  789. """
  790. new_default = self.effective_default(new_field)
  791. default = self._column_default_sql(new_field)
  792. params = [new_default]
  793. if drop:
  794. params = []
  795. elif self.connection.features.requires_literal_defaults:
  796. # Some databases (Oracle) can't take defaults as a parameter
  797. # If this is the case, the SchemaEditor for that database should
  798. # implement prepare_default().
  799. default = self.prepare_default(new_default)
  800. params = []
  801. new_db_params = new_field.db_parameters(connection=self.connection)
  802. sql = self.sql_alter_column_no_default if drop else self.sql_alter_column_default
  803. return (
  804. sql % {
  805. 'column': self.quote_name(new_field.column),
  806. 'type': new_db_params['type'],
  807. 'default': default,
  808. },
  809. params,
  810. )
  811. def _alter_column_type_sql(self, model, old_field, new_field, new_type):
  812. """
  813. Hook to specialize column type alteration for different backends,
  814. for cases when a creation type is different to an alteration type
  815. (e.g. SERIAL in PostgreSQL, PostGIS fields).
  816. Return a two-tuple of: an SQL fragment of (sql, params) to insert into
  817. an ALTER TABLE statement and a list of extra (sql, params) tuples to
  818. run once the field is altered.
  819. """
  820. return (
  821. (
  822. self.sql_alter_column_type % {
  823. "column": self.quote_name(new_field.column),
  824. "type": new_type,
  825. },
  826. [],
  827. ),
  828. [],
  829. )
  830. def _alter_many_to_many(self, model, old_field, new_field, strict):
  831. """Alter M2Ms to repoint their to= endpoints."""
  832. # Rename the through table
  833. if old_field.remote_field.through._meta.db_table != new_field.remote_field.through._meta.db_table:
  834. self.alter_db_table(old_field.remote_field.through, old_field.remote_field.through._meta.db_table,
  835. new_field.remote_field.through._meta.db_table)
  836. # Repoint the FK to the other side
  837. self.alter_field(
  838. new_field.remote_field.through,
  839. # We need the field that points to the target model, so we can tell alter_field to change it -
  840. # this is m2m_reverse_field_name() (as opposed to m2m_field_name, which points to our model)
  841. old_field.remote_field.through._meta.get_field(old_field.m2m_reverse_field_name()),
  842. new_field.remote_field.through._meta.get_field(new_field.m2m_reverse_field_name()),
  843. )
  844. self.alter_field(
  845. new_field.remote_field.through,
  846. # for self-referential models we need to alter field from the other end too
  847. old_field.remote_field.through._meta.get_field(old_field.m2m_field_name()),
  848. new_field.remote_field.through._meta.get_field(new_field.m2m_field_name()),
  849. )
  850. def _create_index_name(self, table_name, column_names, suffix=""):
  851. """
  852. Generate a unique name for an index/unique constraint.
  853. The name is divided into 3 parts: the table name, the column names,
  854. and a unique digest and suffix.
  855. """
  856. _, table_name = split_identifier(table_name)
  857. hash_suffix_part = '%s%s' % (names_digest(table_name, *column_names, length=8), suffix)
  858. max_length = self.connection.ops.max_name_length() or 200
  859. # If everything fits into max_length, use that name.
  860. index_name = '%s_%s_%s' % (table_name, '_'.join(column_names), hash_suffix_part)
  861. if len(index_name) <= max_length:
  862. return index_name
  863. # Shorten a long suffix.
  864. if len(hash_suffix_part) > max_length / 3:
  865. hash_suffix_part = hash_suffix_part[:max_length // 3]
  866. other_length = (max_length - len(hash_suffix_part)) // 2 - 1
  867. index_name = '%s_%s_%s' % (
  868. table_name[:other_length],
  869. '_'.join(column_names)[:other_length],
  870. hash_suffix_part,
  871. )
  872. # Prepend D if needed to prevent the name from starting with an
  873. # underscore or a number (not permitted on Oracle).
  874. if index_name[0] == "_" or index_name[0].isdigit():
  875. index_name = "D%s" % index_name[:-1]
  876. return index_name
  877. def _get_index_tablespace_sql(self, model, fields, db_tablespace=None):
  878. if db_tablespace is None:
  879. if len(fields) == 1 and fields[0].db_tablespace:
  880. db_tablespace = fields[0].db_tablespace
  881. elif model._meta.db_tablespace:
  882. db_tablespace = model._meta.db_tablespace
  883. if db_tablespace is not None:
  884. return ' ' + self.connection.ops.tablespace_sql(db_tablespace)
  885. return ''
  886. def _index_condition_sql(self, condition):
  887. if condition:
  888. return ' WHERE ' + condition
  889. return ''
  890. def _index_include_sql(self, model, columns):
  891. if not columns or not self.connection.features.supports_covering_indexes:
  892. return ''
  893. return Statement(
  894. ' INCLUDE (%(columns)s)',
  895. columns=Columns(model._meta.db_table, columns, self.quote_name),
  896. )
  897. def _create_index_sql(self, model, fields, *, name=None, suffix='', using='',
  898. db_tablespace=None, col_suffixes=(), sql=None, opclasses=(),
  899. condition=None, include=None):
  900. """
  901. Return the SQL statement to create the index for one or several fields.
  902. `sql` can be specified if the syntax differs from the standard (GIS
  903. indexes, ...).
  904. """
  905. tablespace_sql = self._get_index_tablespace_sql(model, fields, db_tablespace=db_tablespace)
  906. columns = [field.column for field in fields]
  907. sql_create_index = sql or self.sql_create_index
  908. table = model._meta.db_table
  909. def create_index_name(*args, **kwargs):
  910. nonlocal name
  911. if name is None:
  912. name = self._create_index_name(*args, **kwargs)
  913. return self.quote_name(name)
  914. return Statement(
  915. sql_create_index,
  916. table=Table(table, self.quote_name),
  917. name=IndexName(table, columns, suffix, create_index_name),
  918. using=using,
  919. columns=self._index_columns(table, columns, col_suffixes, opclasses),
  920. extra=tablespace_sql,
  921. condition=self._index_condition_sql(condition),
  922. include=self._index_include_sql(model, include),
  923. )
  924. def _delete_index_sql(self, model, name, sql=None):
  925. return Statement(
  926. sql or self.sql_delete_index,
  927. table=Table(model._meta.db_table, self.quote_name),
  928. name=self.quote_name(name),
  929. )
  930. def _index_columns(self, table, columns, col_suffixes, opclasses):
  931. return Columns(table, columns, self.quote_name, col_suffixes=col_suffixes)
  932. def _model_indexes_sql(self, model):
  933. """
  934. Return a list of all index SQL statements (field indexes,
  935. index_together, Meta.indexes) for the specified model.
  936. """
  937. if not model._meta.managed or model._meta.proxy or model._meta.swapped:
  938. return []
  939. output = []
  940. for field in model._meta.local_fields:
  941. output.extend(self._field_indexes_sql(model, field))
  942. for field_names in model._meta.index_together:
  943. fields = [model._meta.get_field(field) for field in field_names]
  944. output.append(self._create_index_sql(model, fields, suffix="_idx"))
  945. for index in model._meta.indexes:
  946. output.append(index.create_sql(model, self))
  947. return output
  948. def _field_indexes_sql(self, model, field):
  949. """
  950. Return a list of all index SQL statements for the specified field.
  951. """
  952. output = []
  953. if self._field_should_be_indexed(model, field):
  954. output.append(self._create_index_sql(model, [field]))
  955. return output
  956. def _field_should_be_indexed(self, model, field):
  957. return field.db_index and not field.unique
  958. def _field_became_primary_key(self, old_field, new_field):
  959. return not old_field.primary_key and new_field.primary_key
  960. def _unique_should_be_added(self, old_field, new_field):
  961. return (not old_field.unique and new_field.unique) or (
  962. old_field.primary_key and not new_field.primary_key and new_field.unique
  963. )
  964. def _rename_field_sql(self, table, old_field, new_field, new_type):
  965. return self.sql_rename_column % {
  966. "table": self.quote_name(table),
  967. "old_column": self.quote_name(old_field.column),
  968. "new_column": self.quote_name(new_field.column),
  969. "type": new_type,
  970. }
  971. def _create_fk_sql(self, model, field, suffix):
  972. table = Table(model._meta.db_table, self.quote_name)
  973. name = self._fk_constraint_name(model, field, suffix)
  974. column = Columns(model._meta.db_table, [field.column], self.quote_name)
  975. to_table = Table(field.target_field.model._meta.db_table, self.quote_name)
  976. to_column = Columns(field.target_field.model._meta.db_table, [field.target_field.column], self.quote_name)
  977. deferrable = self.connection.ops.deferrable_sql()
  978. return Statement(
  979. self.sql_create_fk,
  980. table=table,
  981. name=name,
  982. column=column,
  983. to_table=to_table,
  984. to_column=to_column,
  985. deferrable=deferrable,
  986. )
  987. def _fk_constraint_name(self, model, field, suffix):
  988. def create_fk_name(*args, **kwargs):
  989. return self.quote_name(self._create_index_name(*args, **kwargs))
  990. return ForeignKeyName(
  991. model._meta.db_table,
  992. [field.column],
  993. split_identifier(field.target_field.model._meta.db_table)[1],
  994. [field.target_field.column],
  995. suffix,
  996. create_fk_name,
  997. )
  998. def _delete_fk_sql(self, model, name):
  999. return self._delete_constraint_sql(self.sql_delete_fk, model, name)
  1000. def _deferrable_constraint_sql(self, deferrable):
  1001. if deferrable is None:
  1002. return ''
  1003. if deferrable == Deferrable.DEFERRED:
  1004. return ' DEFERRABLE INITIALLY DEFERRED'
  1005. if deferrable == Deferrable.IMMEDIATE:
  1006. return ' DEFERRABLE INITIALLY IMMEDIATE'
  1007. def _unique_sql(self, model, fields, name, condition=None, deferrable=None, include=None):
  1008. if (
  1009. deferrable and
  1010. not self.connection.features.supports_deferrable_unique_constraints
  1011. ):
  1012. return None
  1013. if condition or include:
  1014. # Databases support conditional and covering unique constraints via
  1015. # a unique index.
  1016. sql = self._create_unique_sql(
  1017. model,
  1018. fields,
  1019. name=name,
  1020. condition=condition,
  1021. include=include,
  1022. )
  1023. if sql:
  1024. self.deferred_sql.append(sql)
  1025. return None
  1026. constraint = self.sql_unique_constraint % {
  1027. 'columns': ', '.join(map(self.quote_name, fields)),
  1028. 'deferrable': self._deferrable_constraint_sql(deferrable),
  1029. }
  1030. return self.sql_constraint % {
  1031. 'name': self.quote_name(name),
  1032. 'constraint': constraint,
  1033. }
  1034. def _create_unique_sql(self, model, columns, name=None, condition=None, deferrable=None, include=None):
  1035. if (
  1036. (
  1037. deferrable and
  1038. not self.connection.features.supports_deferrable_unique_constraints
  1039. ) or
  1040. (condition and not self.connection.features.supports_partial_indexes) or
  1041. (include and not self.connection.features.supports_covering_indexes)
  1042. ):
  1043. return None
  1044. def create_unique_name(*args, **kwargs):
  1045. return self.quote_name(self._create_index_name(*args, **kwargs))
  1046. table = Table(model._meta.db_table, self.quote_name)
  1047. if name is None:
  1048. name = IndexName(model._meta.db_table, columns, '_uniq', create_unique_name)
  1049. else:
  1050. name = self.quote_name(name)
  1051. columns = Columns(table, columns, self.quote_name)
  1052. if condition or include:
  1053. sql = self.sql_create_unique_index
  1054. else:
  1055. sql = self.sql_create_unique
  1056. return Statement(
  1057. sql,
  1058. table=table,
  1059. name=name,
  1060. columns=columns,
  1061. condition=self._index_condition_sql(condition),
  1062. deferrable=self._deferrable_constraint_sql(deferrable),
  1063. include=self._index_include_sql(model, include),
  1064. )
  1065. def _delete_unique_sql(self, model, name, condition=None, deferrable=None, include=None):
  1066. if (
  1067. (
  1068. deferrable and
  1069. not self.connection.features.supports_deferrable_unique_constraints
  1070. ) or
  1071. (condition and not self.connection.features.supports_partial_indexes) or
  1072. (include and not self.connection.features.supports_covering_indexes)
  1073. ):
  1074. return None
  1075. if condition or include:
  1076. sql = self.sql_delete_index
  1077. else:
  1078. sql = self.sql_delete_unique
  1079. return self._delete_constraint_sql(sql, model, name)
  1080. def _check_sql(self, name, check):
  1081. return self.sql_constraint % {
  1082. 'name': self.quote_name(name),
  1083. 'constraint': self.sql_check_constraint % {'check': check},
  1084. }
  1085. def _create_check_sql(self, model, name, check):
  1086. return Statement(
  1087. self.sql_create_check,
  1088. table=Table(model._meta.db_table, self.quote_name),
  1089. name=self.quote_name(name),
  1090. check=check,
  1091. )
  1092. def _delete_check_sql(self, model, name):
  1093. return self._delete_constraint_sql(self.sql_delete_check, model, name)
  1094. def _delete_constraint_sql(self, template, model, name):
  1095. return Statement(
  1096. template,
  1097. table=Table(model._meta.db_table, self.quote_name),
  1098. name=self.quote_name(name),
  1099. )
  1100. def _constraint_names(self, model, column_names=None, unique=None,
  1101. primary_key=None, index=None, foreign_key=None,
  1102. check=None, type_=None, exclude=None):
  1103. """Return all constraint names matching the columns and conditions."""
  1104. if column_names is not None:
  1105. column_names = [
  1106. self.connection.introspection.identifier_converter(name)
  1107. for name in column_names
  1108. ]
  1109. with self.connection.cursor() as cursor:
  1110. constraints = self.connection.introspection.get_constraints(cursor, model._meta.db_table)
  1111. result = []
  1112. for name, infodict in constraints.items():
  1113. if column_names is None or column_names == infodict['columns']:
  1114. if unique is not None and infodict['unique'] != unique:
  1115. continue
  1116. if primary_key is not None and infodict['primary_key'] != primary_key:
  1117. continue
  1118. if index is not None and infodict['index'] != index:
  1119. continue
  1120. if check is not None and infodict['check'] != check:
  1121. continue
  1122. if foreign_key is not None and not infodict['foreign_key']:
  1123. continue
  1124. if type_ is not None and infodict['type'] != type_:
  1125. continue
  1126. if not exclude or name not in exclude:
  1127. result.append(name)
  1128. return result
  1129. def _delete_primary_key(self, model, strict=False):
  1130. constraint_names = self._constraint_names(model, primary_key=True)
  1131. if strict and len(constraint_names) != 1:
  1132. raise ValueError('Found wrong number (%s) of PK constraints for %s' % (
  1133. len(constraint_names),
  1134. model._meta.db_table,
  1135. ))
  1136. for constraint_name in constraint_names:
  1137. self.execute(self._delete_primary_key_sql(model, constraint_name))
  1138. def _create_primary_key_sql(self, model, field):
  1139. return Statement(
  1140. self.sql_create_pk,
  1141. table=Table(model._meta.db_table, self.quote_name),
  1142. name=self.quote_name(
  1143. self._create_index_name(model._meta.db_table, [field.column], suffix="_pk")
  1144. ),
  1145. columns=Columns(model._meta.db_table, [field.column], self.quote_name),
  1146. )
  1147. def _delete_primary_key_sql(self, model, name):
  1148. return self._delete_constraint_sql(self.sql_delete_pk, model, name)
  1149. def remove_procedure(self, procedure_name, param_types=()):
  1150. sql = self.sql_delete_procedure % {
  1151. 'procedure': self.quote_name(procedure_name),
  1152. 'param_types': ','.join(param_types),
  1153. }
  1154. self.execute(sql)