schema.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  1. import logging
  2. import operator
  3. from datetime import datetime
  4. from django.conf import settings
  5. from django.db.backends.ddl_references import (
  6. Columns,
  7. Expressions,
  8. ForeignKeyName,
  9. IndexName,
  10. Statement,
  11. Table,
  12. )
  13. from django.db.backends.utils import names_digest, split_identifier, truncate_name
  14. from django.db.models import NOT_PROVIDED, Deferrable, Index
  15. from django.db.models.sql import Query
  16. from django.db.transaction import TransactionManagementError, atomic
  17. from django.utils import timezone
  18. logger = logging.getLogger("django.db.backends.schema")
  19. def _is_relevant_relation(relation, altered_field):
  20. """
  21. When altering the given field, must constraints on its model from the given
  22. relation be temporarily dropped?
  23. """
  24. field = relation.field
  25. if field.many_to_many:
  26. # M2M reverse field
  27. return False
  28. if altered_field.primary_key and field.to_fields == [None]:
  29. # Foreign key constraint on the primary key, which is being altered.
  30. return True
  31. # Is the constraint targeting the field being altered?
  32. return altered_field.name in field.to_fields
  33. def _all_related_fields(model):
  34. # Related fields must be returned in a deterministic order.
  35. return sorted(
  36. model._meta._get_fields(
  37. forward=False,
  38. reverse=True,
  39. include_hidden=True,
  40. include_parents=False,
  41. ),
  42. key=operator.attrgetter("name"),
  43. )
  44. def _related_non_m2m_objects(old_field, new_field):
  45. # Filter out m2m objects from reverse relations.
  46. # Return (old_relation, new_relation) tuples.
  47. related_fields = zip(
  48. (
  49. obj
  50. for obj in _all_related_fields(old_field.model)
  51. if _is_relevant_relation(obj, old_field)
  52. ),
  53. (
  54. obj
  55. for obj in _all_related_fields(new_field.model)
  56. if _is_relevant_relation(obj, new_field)
  57. ),
  58. )
  59. for old_rel, new_rel in related_fields:
  60. yield old_rel, new_rel
  61. yield from _related_non_m2m_objects(
  62. old_rel.remote_field,
  63. new_rel.remote_field,
  64. )
  65. class BaseDatabaseSchemaEditor:
  66. """
  67. This class and its subclasses are responsible for emitting schema-changing
  68. statements to the databases - model creation/removal/alteration, field
  69. renaming, index fiddling, and so on.
  70. """
  71. # Overrideable SQL templates
  72. sql_create_table = "CREATE TABLE %(table)s (%(definition)s)"
  73. sql_rename_table = "ALTER TABLE %(old_table)s RENAME TO %(new_table)s"
  74. sql_retablespace_table = "ALTER TABLE %(table)s SET TABLESPACE %(new_tablespace)s"
  75. sql_delete_table = "DROP TABLE %(table)s CASCADE"
  76. sql_create_column = "ALTER TABLE %(table)s ADD COLUMN %(column)s %(definition)s"
  77. sql_alter_column = "ALTER TABLE %(table)s %(changes)s"
  78. sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s%(collation)s"
  79. sql_alter_column_null = "ALTER COLUMN %(column)s DROP NOT NULL"
  80. sql_alter_column_not_null = "ALTER COLUMN %(column)s SET NOT NULL"
  81. sql_alter_column_default = "ALTER COLUMN %(column)s SET DEFAULT %(default)s"
  82. sql_alter_column_no_default = "ALTER COLUMN %(column)s DROP DEFAULT"
  83. sql_alter_column_no_default_null = sql_alter_column_no_default
  84. sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s CASCADE"
  85. sql_rename_column = (
  86. "ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s"
  87. )
  88. sql_update_with_default = (
  89. "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL"
  90. )
  91. sql_unique_constraint = "UNIQUE (%(columns)s)%(deferrable)s"
  92. sql_check_constraint = "CHECK (%(check)s)"
  93. sql_delete_constraint = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
  94. sql_constraint = "CONSTRAINT %(name)s %(constraint)s"
  95. sql_create_check = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)"
  96. sql_delete_check = sql_delete_constraint
  97. sql_create_unique = (
  98. "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s "
  99. "UNIQUE%(nulls_distinct)s (%(columns)s)%(deferrable)s"
  100. )
  101. sql_delete_unique = sql_delete_constraint
  102. sql_create_fk = (
  103. "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) "
  104. "REFERENCES %(to_table)s (%(to_column)s)%(deferrable)s"
  105. )
  106. sql_create_inline_fk = None
  107. sql_create_column_inline_fk = None
  108. sql_delete_fk = sql_delete_constraint
  109. sql_create_index = (
  110. "CREATE INDEX %(name)s ON %(table)s "
  111. "(%(columns)s)%(include)s%(extra)s%(condition)s"
  112. )
  113. sql_create_unique_index = (
  114. "CREATE UNIQUE INDEX %(name)s ON %(table)s "
  115. "(%(columns)s)%(include)s%(condition)s%(nulls_distinct)s"
  116. )
  117. sql_rename_index = "ALTER INDEX %(old_name)s RENAME TO %(new_name)s"
  118. sql_delete_index = "DROP INDEX %(name)s"
  119. sql_create_pk = (
  120. "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
  121. )
  122. sql_delete_pk = sql_delete_constraint
  123. sql_delete_procedure = "DROP PROCEDURE %(procedure)s"
  124. sql_alter_table_comment = "COMMENT ON TABLE %(table)s IS %(comment)s"
  125. sql_alter_column_comment = "COMMENT ON COLUMN %(table)s.%(column)s IS %(comment)s"
  126. def __init__(self, connection, collect_sql=False, atomic=True):
  127. self.connection = connection
  128. self.collect_sql = collect_sql
  129. if self.collect_sql:
  130. self.collected_sql = []
  131. self.atomic_migration = self.connection.features.can_rollback_ddl and atomic
  132. # State-managing methods
  133. def __enter__(self):
  134. self.deferred_sql = []
  135. if self.atomic_migration:
  136. self.atomic = atomic(self.connection.alias)
  137. self.atomic.__enter__()
  138. return self
  139. def __exit__(self, exc_type, exc_value, traceback):
  140. if exc_type is None:
  141. for sql in self.deferred_sql:
  142. self.execute(sql)
  143. if self.atomic_migration:
  144. self.atomic.__exit__(exc_type, exc_value, traceback)
  145. # Core utility functions
  146. def execute(self, sql, params=()):
  147. """Execute the given SQL statement, with optional parameters."""
  148. # Don't perform the transactional DDL check if SQL is being collected
  149. # as it's not going to be executed anyway.
  150. if (
  151. not self.collect_sql
  152. and self.connection.in_atomic_block
  153. and not self.connection.features.can_rollback_ddl
  154. ):
  155. raise TransactionManagementError(
  156. "Executing DDL statements while in a transaction on databases "
  157. "that can't perform a rollback is prohibited."
  158. )
  159. # Account for non-string statement objects.
  160. sql = str(sql)
  161. # Log the command we're running, then run it
  162. logger.debug(
  163. "%s; (params %r)", sql, params, extra={"params": params, "sql": sql}
  164. )
  165. if self.collect_sql:
  166. ending = "" if sql.rstrip().endswith(";") else ";"
  167. if params is not None:
  168. self.collected_sql.append(
  169. (sql % tuple(map(self.quote_value, params))) + ending
  170. )
  171. else:
  172. self.collected_sql.append(sql + ending)
  173. else:
  174. with self.connection.cursor() as cursor:
  175. cursor.execute(sql, params)
  176. def quote_name(self, name):
  177. return self.connection.ops.quote_name(name)
  178. def table_sql(self, model):
  179. """Take a model and return its table definition."""
  180. # Add any unique_togethers (always deferred, as some fields might be
  181. # created afterward, like geometry fields with some backends).
  182. for field_names in model._meta.unique_together:
  183. fields = [model._meta.get_field(field) for field in field_names]
  184. self.deferred_sql.append(self._create_unique_sql(model, fields))
  185. # Create column SQL, add FK deferreds if needed.
  186. column_sqls = []
  187. params = []
  188. for field in model._meta.local_fields:
  189. # SQL.
  190. definition, extra_params = self.column_sql(model, field)
  191. if definition is None:
  192. continue
  193. # Check constraints can go on the column SQL here.
  194. db_params = field.db_parameters(connection=self.connection)
  195. if db_params["check"]:
  196. definition += " " + self.sql_check_constraint % db_params
  197. # Autoincrement SQL (for backends with inline variant).
  198. col_type_suffix = field.db_type_suffix(connection=self.connection)
  199. if col_type_suffix:
  200. definition += " %s" % col_type_suffix
  201. params.extend(extra_params)
  202. # FK.
  203. if field.remote_field and field.db_constraint:
  204. to_table = field.remote_field.model._meta.db_table
  205. to_column = field.remote_field.model._meta.get_field(
  206. field.remote_field.field_name
  207. ).column
  208. if self.sql_create_inline_fk:
  209. definition += " " + self.sql_create_inline_fk % {
  210. "to_table": self.quote_name(to_table),
  211. "to_column": self.quote_name(to_column),
  212. }
  213. elif self.connection.features.supports_foreign_keys:
  214. self.deferred_sql.append(
  215. self._create_fk_sql(
  216. model, field, "_fk_%(to_table)s_%(to_column)s"
  217. )
  218. )
  219. # Add the SQL to our big list.
  220. column_sqls.append(
  221. "%s %s"
  222. % (
  223. self.quote_name(field.column),
  224. definition,
  225. )
  226. )
  227. # Autoincrement SQL (for backends with post table definition
  228. # variant).
  229. if field.get_internal_type() in (
  230. "AutoField",
  231. "BigAutoField",
  232. "SmallAutoField",
  233. ):
  234. autoinc_sql = self.connection.ops.autoinc_sql(
  235. model._meta.db_table, field.column
  236. )
  237. if autoinc_sql:
  238. self.deferred_sql.extend(autoinc_sql)
  239. constraints = [
  240. constraint.constraint_sql(model, self)
  241. for constraint in model._meta.constraints
  242. ]
  243. sql = self.sql_create_table % {
  244. "table": self.quote_name(model._meta.db_table),
  245. "definition": ", ".join(
  246. str(constraint)
  247. for constraint in (*column_sqls, *constraints)
  248. if constraint
  249. ),
  250. }
  251. if model._meta.db_tablespace:
  252. tablespace_sql = self.connection.ops.tablespace_sql(
  253. model._meta.db_tablespace
  254. )
  255. if tablespace_sql:
  256. sql += " " + tablespace_sql
  257. return sql, params
  258. # Field <-> database mapping functions
  259. def _iter_column_sql(
  260. self, column_db_type, params, model, field, field_db_params, include_default
  261. ):
  262. yield column_db_type
  263. if collation := field_db_params.get("collation"):
  264. yield self._collate_sql(collation)
  265. if self.connection.features.supports_comments_inline and field.db_comment:
  266. yield self._comment_sql(field.db_comment)
  267. # Work out nullability.
  268. null = field.null
  269. # Add database default.
  270. if field.db_default is not NOT_PROVIDED:
  271. default_sql, default_params = self.db_default_sql(field)
  272. yield f"DEFAULT {default_sql}"
  273. params.extend(default_params)
  274. include_default = False
  275. # Include a default value, if requested.
  276. include_default = (
  277. include_default
  278. and not self.skip_default(field)
  279. and
  280. # Don't include a default value if it's a nullable field and the
  281. # default cannot be dropped in the ALTER COLUMN statement (e.g.
  282. # MySQL longtext and longblob).
  283. not (null and self.skip_default_on_alter(field))
  284. )
  285. if include_default:
  286. default_value = self.effective_default(field)
  287. if default_value is not None:
  288. column_default = "DEFAULT " + self._column_default_sql(field)
  289. if self.connection.features.requires_literal_defaults:
  290. # Some databases can't take defaults as a parameter (Oracle).
  291. # If this is the case, the individual schema backend should
  292. # implement prepare_default().
  293. yield column_default % self.prepare_default(default_value)
  294. else:
  295. yield column_default
  296. params.append(default_value)
  297. # Oracle treats the empty string ('') as null, so coerce the null
  298. # option whenever '' is a possible value.
  299. if (
  300. field.empty_strings_allowed
  301. and not field.primary_key
  302. and self.connection.features.interprets_empty_strings_as_nulls
  303. ):
  304. null = True
  305. if field.generated:
  306. yield self._column_generated_sql(field)
  307. elif not null:
  308. yield "NOT NULL"
  309. elif not self.connection.features.implied_column_null:
  310. yield "NULL"
  311. if field.primary_key:
  312. yield "PRIMARY KEY"
  313. elif field.unique:
  314. yield "UNIQUE"
  315. # Optionally add the tablespace if it's an implicitly indexed column.
  316. tablespace = field.db_tablespace or model._meta.db_tablespace
  317. if (
  318. tablespace
  319. and self.connection.features.supports_tablespaces
  320. and field.unique
  321. ):
  322. yield self.connection.ops.tablespace_sql(tablespace, inline=True)
  323. def column_sql(self, model, field, include_default=False):
  324. """
  325. Return the column definition for a field. The field must already have
  326. had set_attributes_from_name() called.
  327. """
  328. # Get the column's type and use that as the basis of the SQL.
  329. field_db_params = field.db_parameters(connection=self.connection)
  330. column_db_type = field_db_params["type"]
  331. # Check for fields that aren't actually columns (e.g. M2M).
  332. if column_db_type is None:
  333. return None, None
  334. params = []
  335. return (
  336. " ".join(
  337. # This appends to the params being returned.
  338. self._iter_column_sql(
  339. column_db_type,
  340. params,
  341. model,
  342. field,
  343. field_db_params,
  344. include_default,
  345. )
  346. ),
  347. params,
  348. )
  349. def skip_default(self, field):
  350. """
  351. Some backends don't accept default values for certain columns types
  352. (i.e. MySQL longtext and longblob).
  353. """
  354. return False
  355. def skip_default_on_alter(self, field):
  356. """
  357. Some backends don't accept default values for certain columns types
  358. (i.e. MySQL longtext and longblob) in the ALTER COLUMN statement.
  359. """
  360. return False
  361. def prepare_default(self, value):
  362. """
  363. Only used for backends which have requires_literal_defaults feature
  364. """
  365. raise NotImplementedError(
  366. "subclasses of BaseDatabaseSchemaEditor for backends which have "
  367. "requires_literal_defaults must provide a prepare_default() method"
  368. )
  369. def _column_default_sql(self, field):
  370. """
  371. Return the SQL to use in a DEFAULT clause. The resulting string should
  372. contain a '%s' placeholder for a default value.
  373. """
  374. return "%s"
  375. def db_default_sql(self, field):
  376. """Return the sql and params for the field's database default."""
  377. from django.db.models.expressions import Value
  378. sql = "%s" if isinstance(field.db_default, Value) else "(%s)"
  379. query = Query(model=field.model)
  380. compiler = query.get_compiler(connection=self.connection)
  381. default_sql, params = compiler.compile(field.db_default)
  382. if self.connection.features.requires_literal_defaults:
  383. # Some databases doesn't support parameterized defaults (Oracle,
  384. # SQLite). If this is the case, the individual schema backend
  385. # should implement prepare_default().
  386. default_sql %= tuple(self.prepare_default(p) for p in params)
  387. params = []
  388. return sql % default_sql, params
  389. def _column_generated_sql(self, field):
  390. """Return the SQL to use in a GENERATED ALWAYS clause."""
  391. expression_sql, params = field.generated_sql(self.connection)
  392. persistency_sql = "STORED" if field.db_persist else "VIRTUAL"
  393. if params:
  394. expression_sql = expression_sql % tuple(self.quote_value(p) for p in params)
  395. return f"GENERATED ALWAYS AS ({expression_sql}) {persistency_sql}"
  396. @staticmethod
  397. def _effective_default(field):
  398. # This method allows testing its logic without a connection.
  399. if field.has_default():
  400. default = field.get_default()
  401. elif field.generated:
  402. default = None
  403. elif not field.null and field.blank and field.empty_strings_allowed:
  404. if field.get_internal_type() == "BinaryField":
  405. default = b""
  406. else:
  407. default = ""
  408. elif getattr(field, "auto_now", False) or getattr(field, "auto_now_add", False):
  409. internal_type = field.get_internal_type()
  410. if internal_type == "DateTimeField":
  411. default = timezone.now()
  412. else:
  413. default = datetime.now()
  414. if internal_type == "DateField":
  415. default = default.date()
  416. elif internal_type == "TimeField":
  417. default = default.time()
  418. else:
  419. default = None
  420. return default
  421. def effective_default(self, field):
  422. """Return a field's effective database default value."""
  423. return field.get_db_prep_save(self._effective_default(field), self.connection)
  424. def quote_value(self, value):
  425. """
  426. Return a quoted version of the value so it's safe to use in an SQL
  427. string. This is not safe against injection from user code; it is
  428. intended only for use in making SQL scripts or preparing default values
  429. for particularly tricky backends (defaults are not user-defined, though,
  430. so this is safe).
  431. """
  432. raise NotImplementedError()
  433. # Actions
  434. def create_model(self, model):
  435. """
  436. Create a table and any accompanying indexes or unique constraints for
  437. the given `model`.
  438. """
  439. sql, params = self.table_sql(model)
  440. # Prevent using [] as params, in the case a literal '%' is used in the
  441. # definition.
  442. self.execute(sql, params or None)
  443. if self.connection.features.supports_comments:
  444. # Add table comment.
  445. if model._meta.db_table_comment:
  446. self.alter_db_table_comment(model, None, model._meta.db_table_comment)
  447. # Add column comments.
  448. if not self.connection.features.supports_comments_inline:
  449. for field in model._meta.local_fields:
  450. if field.db_comment:
  451. field_db_params = field.db_parameters(
  452. connection=self.connection
  453. )
  454. field_type = field_db_params["type"]
  455. self.execute(
  456. *self._alter_column_comment_sql(
  457. model, field, field_type, field.db_comment
  458. )
  459. )
  460. # Add any field index and index_together's (deferred as SQLite
  461. # _remake_table needs it).
  462. self.deferred_sql.extend(self._model_indexes_sql(model))
  463. # Make M2M tables
  464. for field in model._meta.local_many_to_many:
  465. if field.remote_field.through._meta.auto_created:
  466. self.create_model(field.remote_field.through)
  467. def delete_model(self, model):
  468. """Delete a model from the database."""
  469. # Handle auto-created intermediary models
  470. for field in model._meta.local_many_to_many:
  471. if field.remote_field.through._meta.auto_created:
  472. self.delete_model(field.remote_field.through)
  473. # Delete the table
  474. self.execute(
  475. self.sql_delete_table
  476. % {
  477. "table": self.quote_name(model._meta.db_table),
  478. }
  479. )
  480. # Remove all deferred statements referencing the deleted table.
  481. for sql in list(self.deferred_sql):
  482. if isinstance(sql, Statement) and sql.references_table(
  483. model._meta.db_table
  484. ):
  485. self.deferred_sql.remove(sql)
  486. def add_index(self, model, index):
  487. """Add an index on a model."""
  488. if (
  489. index.contains_expressions
  490. and not self.connection.features.supports_expression_indexes
  491. ):
  492. return None
  493. # Index.create_sql returns interpolated SQL which makes params=None a
  494. # necessity to avoid escaping attempts on execution.
  495. self.execute(index.create_sql(model, self), params=None)
  496. def remove_index(self, model, index):
  497. """Remove an index from a model."""
  498. if (
  499. index.contains_expressions
  500. and not self.connection.features.supports_expression_indexes
  501. ):
  502. return None
  503. self.execute(index.remove_sql(model, self))
  504. def rename_index(self, model, old_index, new_index):
  505. if self.connection.features.can_rename_index:
  506. self.execute(
  507. self._rename_index_sql(model, old_index.name, new_index.name),
  508. params=None,
  509. )
  510. else:
  511. self.remove_index(model, old_index)
  512. self.add_index(model, new_index)
  513. def add_constraint(self, model, constraint):
  514. """Add a constraint to a model."""
  515. sql = constraint.create_sql(model, self)
  516. if sql:
  517. # Constraint.create_sql returns interpolated SQL which makes
  518. # params=None a necessity to avoid escaping attempts on execution.
  519. self.execute(sql, params=None)
  520. def remove_constraint(self, model, constraint):
  521. """Remove a constraint from a model."""
  522. sql = constraint.remove_sql(model, self)
  523. if sql:
  524. self.execute(sql)
  525. def alter_unique_together(self, model, old_unique_together, new_unique_together):
  526. """
  527. Deal with a model changing its unique_together. The input
  528. unique_togethers must be doubly-nested, not the single-nested
  529. ["foo", "bar"] format.
  530. """
  531. olds = {tuple(fields) for fields in old_unique_together}
  532. news = {tuple(fields) for fields in new_unique_together}
  533. # Deleted uniques
  534. for fields in olds.difference(news):
  535. self._delete_composed_index(
  536. model,
  537. fields,
  538. {"unique": True, "primary_key": False},
  539. self.sql_delete_unique,
  540. )
  541. # Created uniques
  542. for field_names in news.difference(olds):
  543. fields = [model._meta.get_field(field) for field in field_names]
  544. self.execute(self._create_unique_sql(model, fields))
  545. def alter_index_together(self, model, old_index_together, new_index_together):
  546. """
  547. Deal with a model changing its index_together. The input
  548. index_togethers must be doubly-nested, not the single-nested
  549. ["foo", "bar"] format.
  550. """
  551. olds = {tuple(fields) for fields in old_index_together}
  552. news = {tuple(fields) for fields in new_index_together}
  553. # Deleted indexes
  554. for fields in olds.difference(news):
  555. self._delete_composed_index(
  556. model,
  557. fields,
  558. {"index": True, "unique": False},
  559. self.sql_delete_index,
  560. )
  561. # Created indexes
  562. for field_names in news.difference(olds):
  563. fields = [model._meta.get_field(field) for field in field_names]
  564. self.execute(self._create_index_sql(model, fields=fields, suffix="_idx"))
  565. def _delete_composed_index(self, model, fields, constraint_kwargs, sql):
  566. meta_constraint_names = {
  567. constraint.name for constraint in model._meta.constraints
  568. }
  569. meta_index_names = {constraint.name for constraint in model._meta.indexes}
  570. columns = [model._meta.get_field(field).column for field in fields]
  571. constraint_names = self._constraint_names(
  572. model,
  573. columns,
  574. exclude=meta_constraint_names | meta_index_names,
  575. **constraint_kwargs,
  576. )
  577. if (
  578. constraint_kwargs.get("unique") is True
  579. and constraint_names
  580. and self.connection.features.allows_multiple_constraints_on_same_fields
  581. ):
  582. # Constraint matching the unique_together name.
  583. default_name = str(
  584. self._unique_constraint_name(model._meta.db_table, columns, quote=False)
  585. )
  586. if default_name in constraint_names:
  587. constraint_names = [default_name]
  588. if len(constraint_names) != 1:
  589. raise ValueError(
  590. "Found wrong number (%s) of constraints for %s(%s)"
  591. % (
  592. len(constraint_names),
  593. model._meta.db_table,
  594. ", ".join(columns),
  595. )
  596. )
  597. self.execute(self._delete_constraint_sql(sql, model, constraint_names[0]))
  598. def alter_db_table(self, model, old_db_table, new_db_table):
  599. """Rename the table a model points to."""
  600. if old_db_table == new_db_table or (
  601. self.connection.features.ignores_table_name_case
  602. and old_db_table.lower() == new_db_table.lower()
  603. ):
  604. return
  605. self.execute(
  606. self.sql_rename_table
  607. % {
  608. "old_table": self.quote_name(old_db_table),
  609. "new_table": self.quote_name(new_db_table),
  610. }
  611. )
  612. # Rename all references to the old table name.
  613. for sql in self.deferred_sql:
  614. if isinstance(sql, Statement):
  615. sql.rename_table_references(old_db_table, new_db_table)
  616. def alter_db_table_comment(self, model, old_db_table_comment, new_db_table_comment):
  617. if self.sql_alter_table_comment and self.connection.features.supports_comments:
  618. self.execute(
  619. self.sql_alter_table_comment
  620. % {
  621. "table": self.quote_name(model._meta.db_table),
  622. "comment": self.quote_value(new_db_table_comment or ""),
  623. }
  624. )
  625. def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):
  626. """Move a model's table between tablespaces."""
  627. self.execute(
  628. self.sql_retablespace_table
  629. % {
  630. "table": self.quote_name(model._meta.db_table),
  631. "old_tablespace": self.quote_name(old_db_tablespace),
  632. "new_tablespace": self.quote_name(new_db_tablespace),
  633. }
  634. )
  635. def add_field(self, model, field):
  636. """
  637. Create a field on a model. Usually involves adding a column, but may
  638. involve adding a table instead (for M2M fields).
  639. """
  640. # Special-case implicit M2M tables
  641. if field.many_to_many and field.remote_field.through._meta.auto_created:
  642. return self.create_model(field.remote_field.through)
  643. # Get the column's definition
  644. definition, params = self.column_sql(model, field, include_default=True)
  645. # It might not actually have a column behind it
  646. if definition is None:
  647. return
  648. if col_type_suffix := field.db_type_suffix(connection=self.connection):
  649. definition += f" {col_type_suffix}"
  650. # Check constraints can go on the column SQL here
  651. db_params = field.db_parameters(connection=self.connection)
  652. if db_params["check"]:
  653. definition += " " + self.sql_check_constraint % db_params
  654. if (
  655. field.remote_field
  656. and self.connection.features.supports_foreign_keys
  657. and field.db_constraint
  658. ):
  659. constraint_suffix = "_fk_%(to_table)s_%(to_column)s"
  660. # Add FK constraint inline, if supported.
  661. if self.sql_create_column_inline_fk:
  662. to_table = field.remote_field.model._meta.db_table
  663. to_column = field.remote_field.model._meta.get_field(
  664. field.remote_field.field_name
  665. ).column
  666. namespace, _ = split_identifier(model._meta.db_table)
  667. definition += " " + self.sql_create_column_inline_fk % {
  668. "name": self._fk_constraint_name(model, field, constraint_suffix),
  669. "namespace": (
  670. "%s." % self.quote_name(namespace) if namespace else ""
  671. ),
  672. "column": self.quote_name(field.column),
  673. "to_table": self.quote_name(to_table),
  674. "to_column": self.quote_name(to_column),
  675. "deferrable": self.connection.ops.deferrable_sql(),
  676. }
  677. # Otherwise, add FK constraints later.
  678. else:
  679. self.deferred_sql.append(
  680. self._create_fk_sql(model, field, constraint_suffix)
  681. )
  682. # Build the SQL and run it
  683. sql = self.sql_create_column % {
  684. "table": self.quote_name(model._meta.db_table),
  685. "column": self.quote_name(field.column),
  686. "definition": definition,
  687. }
  688. self.execute(sql, params)
  689. # Drop the default if we need to
  690. if (
  691. field.db_default is NOT_PROVIDED
  692. and not self.skip_default_on_alter(field)
  693. and self.effective_default(field) is not None
  694. ):
  695. changes_sql, params = self._alter_column_default_sql(
  696. model, None, field, drop=True
  697. )
  698. sql = self.sql_alter_column % {
  699. "table": self.quote_name(model._meta.db_table),
  700. "changes": changes_sql,
  701. }
  702. self.execute(sql, params)
  703. # Add field comment, if required.
  704. if (
  705. field.db_comment
  706. and self.connection.features.supports_comments
  707. and not self.connection.features.supports_comments_inline
  708. ):
  709. field_type = db_params["type"]
  710. self.execute(
  711. *self._alter_column_comment_sql(
  712. model, field, field_type, field.db_comment
  713. )
  714. )
  715. # Add an index, if required
  716. self.deferred_sql.extend(self._field_indexes_sql(model, field))
  717. # Reset connection if required
  718. if self.connection.features.connection_persists_old_columns:
  719. self.connection.close()
  720. def remove_field(self, model, field):
  721. """
  722. Remove a field from a model. Usually involves deleting a column,
  723. but for M2Ms may involve deleting a table.
  724. """
  725. # Special-case implicit M2M tables
  726. if field.many_to_many and field.remote_field.through._meta.auto_created:
  727. return self.delete_model(field.remote_field.through)
  728. # It might not actually have a column behind it
  729. if field.db_parameters(connection=self.connection)["type"] is None:
  730. return
  731. # Drop any FK constraints, MySQL requires explicit deletion
  732. if field.remote_field:
  733. fk_names = self._constraint_names(model, [field.column], foreign_key=True)
  734. for fk_name in fk_names:
  735. self.execute(self._delete_fk_sql(model, fk_name))
  736. # Delete the column
  737. sql = self.sql_delete_column % {
  738. "table": self.quote_name(model._meta.db_table),
  739. "column": self.quote_name(field.column),
  740. }
  741. self.execute(sql)
  742. # Reset connection if required
  743. if self.connection.features.connection_persists_old_columns:
  744. self.connection.close()
  745. # Remove all deferred statements referencing the deleted column.
  746. for sql in list(self.deferred_sql):
  747. if isinstance(sql, Statement) and sql.references_column(
  748. model._meta.db_table, field.column
  749. ):
  750. self.deferred_sql.remove(sql)
  751. def alter_field(self, model, old_field, new_field, strict=False):
  752. """
  753. Allow a field's type, uniqueness, nullability, default, column,
  754. constraints, etc. to be modified.
  755. `old_field` is required to compute the necessary changes.
  756. If `strict` is True, raise errors if the old column does not match
  757. `old_field` precisely.
  758. """
  759. if not self._field_should_be_altered(old_field, new_field):
  760. return
  761. # Ensure this field is even column-based
  762. old_db_params = old_field.db_parameters(connection=self.connection)
  763. old_type = old_db_params["type"]
  764. new_db_params = new_field.db_parameters(connection=self.connection)
  765. new_type = new_db_params["type"]
  766. if (old_type is None and old_field.remote_field is None) or (
  767. new_type is None and new_field.remote_field is None
  768. ):
  769. raise ValueError(
  770. "Cannot alter field %s into %s - they do not properly define "
  771. "db_type (are you using a badly-written custom field?)"
  772. % (old_field, new_field),
  773. )
  774. elif (
  775. old_type is None
  776. and new_type is None
  777. and (
  778. old_field.remote_field.through
  779. and new_field.remote_field.through
  780. and old_field.remote_field.through._meta.auto_created
  781. and new_field.remote_field.through._meta.auto_created
  782. )
  783. ):
  784. return self._alter_many_to_many(model, old_field, new_field, strict)
  785. elif (
  786. old_type is None
  787. and new_type is None
  788. and (
  789. old_field.remote_field.through
  790. and new_field.remote_field.through
  791. and not old_field.remote_field.through._meta.auto_created
  792. and not new_field.remote_field.through._meta.auto_created
  793. )
  794. ):
  795. # Both sides have through models; this is a no-op.
  796. return
  797. elif old_type is None or new_type is None:
  798. raise ValueError(
  799. "Cannot alter field %s into %s - they are not compatible types "
  800. "(you cannot alter to or from M2M fields, or add or remove "
  801. "through= on M2M fields)" % (old_field, new_field)
  802. )
  803. elif old_field.generated != new_field.generated or (
  804. new_field.generated
  805. and (
  806. old_field.db_persist != new_field.db_persist
  807. or old_field.generated_sql(self.connection)
  808. != new_field.generated_sql(self.connection)
  809. )
  810. ):
  811. raise ValueError(
  812. f"Modifying GeneratedFields is not supported - the field {new_field} "
  813. "must be removed and re-added with the new definition."
  814. )
  815. self._alter_field(
  816. model,
  817. old_field,
  818. new_field,
  819. old_type,
  820. new_type,
  821. old_db_params,
  822. new_db_params,
  823. strict,
  824. )
  825. def _field_db_check(self, field, field_db_params):
  826. # Always check constraints with the same mocked column name to avoid
  827. # recreating constrains when the column is renamed.
  828. check_constraints = self.connection.data_type_check_constraints
  829. data = field.db_type_parameters(self.connection)
  830. data["column"] = "__column_name__"
  831. try:
  832. return check_constraints[field.get_internal_type()] % data
  833. except KeyError:
  834. return None
  835. def _alter_field(
  836. self,
  837. model,
  838. old_field,
  839. new_field,
  840. old_type,
  841. new_type,
  842. old_db_params,
  843. new_db_params,
  844. strict=False,
  845. ):
  846. """Perform a "physical" (non-ManyToMany) field update."""
  847. # Drop any FK constraints, we'll remake them later
  848. fks_dropped = set()
  849. if (
  850. self.connection.features.supports_foreign_keys
  851. and old_field.remote_field
  852. and old_field.db_constraint
  853. and self._field_should_be_altered(
  854. old_field,
  855. new_field,
  856. ignore={"db_comment"},
  857. )
  858. ):
  859. fk_names = self._constraint_names(
  860. model, [old_field.column], foreign_key=True
  861. )
  862. if strict and len(fk_names) != 1:
  863. raise ValueError(
  864. "Found wrong number (%s) of foreign key constraints for %s.%s"
  865. % (
  866. len(fk_names),
  867. model._meta.db_table,
  868. old_field.column,
  869. )
  870. )
  871. for fk_name in fk_names:
  872. fks_dropped.add((old_field.column,))
  873. self.execute(self._delete_fk_sql(model, fk_name))
  874. # Has unique been removed?
  875. if old_field.unique and (
  876. not new_field.unique or self._field_became_primary_key(old_field, new_field)
  877. ):
  878. # Find the unique constraint for this field
  879. meta_constraint_names = {
  880. constraint.name for constraint in model._meta.constraints
  881. }
  882. constraint_names = self._constraint_names(
  883. model,
  884. [old_field.column],
  885. unique=True,
  886. primary_key=False,
  887. exclude=meta_constraint_names,
  888. )
  889. if strict and len(constraint_names) != 1:
  890. raise ValueError(
  891. "Found wrong number (%s) of unique constraints for %s.%s"
  892. % (
  893. len(constraint_names),
  894. model._meta.db_table,
  895. old_field.column,
  896. )
  897. )
  898. for constraint_name in constraint_names:
  899. self.execute(self._delete_unique_sql(model, constraint_name))
  900. # Drop incoming FK constraints if the field is a primary key or unique,
  901. # which might be a to_field target, and things are going to change.
  902. old_collation = old_db_params.get("collation")
  903. new_collation = new_db_params.get("collation")
  904. drop_foreign_keys = (
  905. self.connection.features.supports_foreign_keys
  906. and (
  907. (old_field.primary_key and new_field.primary_key)
  908. or (old_field.unique and new_field.unique)
  909. )
  910. and ((old_type != new_type) or (old_collation != new_collation))
  911. )
  912. if drop_foreign_keys:
  913. # '_meta.related_field' also contains M2M reverse fields, these
  914. # will be filtered out
  915. for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):
  916. rel_fk_names = self._constraint_names(
  917. new_rel.related_model, [new_rel.field.column], foreign_key=True
  918. )
  919. for fk_name in rel_fk_names:
  920. self.execute(self._delete_fk_sql(new_rel.related_model, fk_name))
  921. # Removed an index? (no strict check, as multiple indexes are possible)
  922. # Remove indexes if db_index switched to False or a unique constraint
  923. # will now be used in lieu of an index. The following lines from the
  924. # truth table show all True cases; the rest are False:
  925. #
  926. # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
  927. # ------------------------------------------------------------------------------
  928. # True | False | False | False
  929. # True | False | False | True
  930. # True | False | True | True
  931. if (
  932. old_field.db_index
  933. and not old_field.unique
  934. and (not new_field.db_index or new_field.unique)
  935. ):
  936. # Find the index for this field
  937. meta_index_names = {index.name for index in model._meta.indexes}
  938. # Retrieve only BTREE indexes since this is what's created with
  939. # db_index=True.
  940. index_names = self._constraint_names(
  941. model,
  942. [old_field.column],
  943. index=True,
  944. type_=Index.suffix,
  945. exclude=meta_index_names,
  946. )
  947. for index_name in index_names:
  948. # The only way to check if an index was created with
  949. # db_index=True or with Index(['field'], name='foo')
  950. # is to look at its name (refs #28053).
  951. self.execute(self._delete_index_sql(model, index_name))
  952. # Change check constraints?
  953. old_db_check = self._field_db_check(old_field, old_db_params)
  954. new_db_check = self._field_db_check(new_field, new_db_params)
  955. if old_db_check != new_db_check and old_db_check:
  956. meta_constraint_names = {
  957. constraint.name for constraint in model._meta.constraints
  958. }
  959. constraint_names = self._constraint_names(
  960. model,
  961. [old_field.column],
  962. check=True,
  963. exclude=meta_constraint_names,
  964. )
  965. if strict and len(constraint_names) != 1:
  966. raise ValueError(
  967. "Found wrong number (%s) of check constraints for %s.%s"
  968. % (
  969. len(constraint_names),
  970. model._meta.db_table,
  971. old_field.column,
  972. )
  973. )
  974. for constraint_name in constraint_names:
  975. self.execute(self._delete_check_sql(model, constraint_name))
  976. # Have they renamed the column?
  977. if old_field.column != new_field.column:
  978. self.execute(
  979. self._rename_field_sql(
  980. model._meta.db_table, old_field, new_field, new_type
  981. )
  982. )
  983. # Rename all references to the renamed column.
  984. for sql in self.deferred_sql:
  985. if isinstance(sql, Statement):
  986. sql.rename_column_references(
  987. model._meta.db_table, old_field.column, new_field.column
  988. )
  989. # Next, start accumulating actions to do
  990. actions = []
  991. null_actions = []
  992. post_actions = []
  993. # Type suffix change? (e.g. auto increment).
  994. old_type_suffix = old_field.db_type_suffix(connection=self.connection)
  995. new_type_suffix = new_field.db_type_suffix(connection=self.connection)
  996. # Type, collation, or comment change?
  997. if (
  998. old_type != new_type
  999. or old_type_suffix != new_type_suffix
  1000. or old_collation != new_collation
  1001. or (
  1002. self.connection.features.supports_comments
  1003. and old_field.db_comment != new_field.db_comment
  1004. )
  1005. ):
  1006. fragment, other_actions = self._alter_column_type_sql(
  1007. model, old_field, new_field, new_type, old_collation, new_collation
  1008. )
  1009. actions.append(fragment)
  1010. post_actions.extend(other_actions)
  1011. if new_field.db_default is not NOT_PROVIDED:
  1012. if (
  1013. old_field.db_default is NOT_PROVIDED
  1014. or new_field.db_default != old_field.db_default
  1015. ):
  1016. actions.append(
  1017. self._alter_column_database_default_sql(model, old_field, new_field)
  1018. )
  1019. elif old_field.db_default is not NOT_PROVIDED:
  1020. actions.append(
  1021. self._alter_column_database_default_sql(
  1022. model, old_field, new_field, drop=True
  1023. )
  1024. )
  1025. # When changing a column NULL constraint to NOT NULL with a given
  1026. # default value, we need to perform 4 steps:
  1027. # 1. Add a default for new incoming writes
  1028. # 2. Update existing NULL rows with new default
  1029. # 3. Replace NULL constraint with NOT NULL
  1030. # 4. Drop the default again.
  1031. # Default change?
  1032. needs_database_default = False
  1033. if (
  1034. old_field.null
  1035. and not new_field.null
  1036. and new_field.db_default is NOT_PROVIDED
  1037. ):
  1038. old_default = self.effective_default(old_field)
  1039. new_default = self.effective_default(new_field)
  1040. if (
  1041. not self.skip_default_on_alter(new_field)
  1042. and old_default != new_default
  1043. and new_default is not None
  1044. ):
  1045. needs_database_default = True
  1046. actions.append(
  1047. self._alter_column_default_sql(model, old_field, new_field)
  1048. )
  1049. # Nullability change?
  1050. if old_field.null != new_field.null:
  1051. fragment = self._alter_column_null_sql(model, old_field, new_field)
  1052. if fragment:
  1053. null_actions.append(fragment)
  1054. # Only if we have a default and there is a change from NULL to NOT NULL
  1055. four_way_default_alteration = (
  1056. new_field.has_default() or new_field.db_default is not NOT_PROVIDED
  1057. ) and (old_field.null and not new_field.null)
  1058. if actions or null_actions:
  1059. if not four_way_default_alteration:
  1060. # If we don't have to do a 4-way default alteration we can
  1061. # directly run a (NOT) NULL alteration
  1062. actions += null_actions
  1063. # Combine actions together if we can (e.g. postgres)
  1064. if self.connection.features.supports_combined_alters and actions:
  1065. sql, params = tuple(zip(*actions))
  1066. actions = [(", ".join(sql), sum(params, []))]
  1067. # Apply those actions
  1068. for sql, params in actions:
  1069. self.execute(
  1070. self.sql_alter_column
  1071. % {
  1072. "table": self.quote_name(model._meta.db_table),
  1073. "changes": sql,
  1074. },
  1075. params,
  1076. )
  1077. if four_way_default_alteration:
  1078. if new_field.db_default is NOT_PROVIDED:
  1079. default_sql = "%s"
  1080. params = [new_default]
  1081. else:
  1082. default_sql, params = self.db_default_sql(new_field)
  1083. # Update existing rows with default value
  1084. self.execute(
  1085. self.sql_update_with_default
  1086. % {
  1087. "table": self.quote_name(model._meta.db_table),
  1088. "column": self.quote_name(new_field.column),
  1089. "default": default_sql,
  1090. },
  1091. params,
  1092. )
  1093. # Since we didn't run a NOT NULL change before we need to do it
  1094. # now
  1095. for sql, params in null_actions:
  1096. self.execute(
  1097. self.sql_alter_column
  1098. % {
  1099. "table": self.quote_name(model._meta.db_table),
  1100. "changes": sql,
  1101. },
  1102. params,
  1103. )
  1104. if post_actions:
  1105. for sql, params in post_actions:
  1106. self.execute(sql, params)
  1107. # If primary_key changed to False, delete the primary key constraint.
  1108. if old_field.primary_key and not new_field.primary_key:
  1109. self._delete_primary_key(model, strict)
  1110. # Added a unique?
  1111. if self._unique_should_be_added(old_field, new_field):
  1112. self.execute(self._create_unique_sql(model, [new_field]))
  1113. # Added an index? Add an index if db_index switched to True or a unique
  1114. # constraint will no longer be used in lieu of an index. The following
  1115. # lines from the truth table show all True cases; the rest are False:
  1116. #
  1117. # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
  1118. # ------------------------------------------------------------------------------
  1119. # False | False | True | False
  1120. # False | True | True | False
  1121. # True | True | True | False
  1122. if (
  1123. (not old_field.db_index or old_field.unique)
  1124. and new_field.db_index
  1125. and not new_field.unique
  1126. ):
  1127. self.execute(self._create_index_sql(model, fields=[new_field]))
  1128. # Type alteration on primary key? Then we need to alter the column
  1129. # referring to us.
  1130. rels_to_update = []
  1131. if drop_foreign_keys:
  1132. rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
  1133. # Changed to become primary key?
  1134. if self._field_became_primary_key(old_field, new_field):
  1135. # Make the new one
  1136. self.execute(self._create_primary_key_sql(model, new_field))
  1137. # Update all referencing columns
  1138. rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
  1139. # Handle our type alters on the other end of rels from the PK stuff above
  1140. for old_rel, new_rel in rels_to_update:
  1141. rel_db_params = new_rel.field.db_parameters(connection=self.connection)
  1142. rel_type = rel_db_params["type"]
  1143. rel_collation = rel_db_params.get("collation")
  1144. old_rel_db_params = old_rel.field.db_parameters(connection=self.connection)
  1145. old_rel_collation = old_rel_db_params.get("collation")
  1146. fragment, other_actions = self._alter_column_type_sql(
  1147. new_rel.related_model,
  1148. old_rel.field,
  1149. new_rel.field,
  1150. rel_type,
  1151. old_rel_collation,
  1152. rel_collation,
  1153. )
  1154. self.execute(
  1155. self.sql_alter_column
  1156. % {
  1157. "table": self.quote_name(new_rel.related_model._meta.db_table),
  1158. "changes": fragment[0],
  1159. },
  1160. fragment[1],
  1161. )
  1162. for sql, params in other_actions:
  1163. self.execute(sql, params)
  1164. # Does it have a foreign key?
  1165. if (
  1166. self.connection.features.supports_foreign_keys
  1167. and new_field.remote_field
  1168. and (
  1169. fks_dropped or not old_field.remote_field or not old_field.db_constraint
  1170. )
  1171. and new_field.db_constraint
  1172. ):
  1173. self.execute(
  1174. self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s")
  1175. )
  1176. # Rebuild FKs that pointed to us if we previously had to drop them
  1177. if drop_foreign_keys:
  1178. for _, rel in rels_to_update:
  1179. if rel.field.db_constraint:
  1180. self.execute(
  1181. self._create_fk_sql(rel.related_model, rel.field, "_fk")
  1182. )
  1183. # Does it have check constraints we need to add?
  1184. if old_db_check != new_db_check and new_db_check:
  1185. constraint_name = self._create_index_name(
  1186. model._meta.db_table, [new_field.column], suffix="_check"
  1187. )
  1188. self.execute(
  1189. self._create_check_sql(model, constraint_name, new_db_params["check"])
  1190. )
  1191. # Drop the default if we need to
  1192. # (Django usually does not use in-database defaults)
  1193. if needs_database_default:
  1194. changes_sql, params = self._alter_column_default_sql(
  1195. model, old_field, new_field, drop=True
  1196. )
  1197. sql = self.sql_alter_column % {
  1198. "table": self.quote_name(model._meta.db_table),
  1199. "changes": changes_sql,
  1200. }
  1201. self.execute(sql, params)
  1202. # Reset connection if required
  1203. if self.connection.features.connection_persists_old_columns:
  1204. self.connection.close()
  1205. def _alter_column_null_sql(self, model, old_field, new_field):
  1206. """
  1207. Hook to specialize column null alteration.
  1208. Return a (sql, params) fragment to set a column to null or non-null
  1209. as required by new_field, or None if no changes are required.
  1210. """
  1211. if (
  1212. self.connection.features.interprets_empty_strings_as_nulls
  1213. and new_field.empty_strings_allowed
  1214. ):
  1215. # The field is nullable in the database anyway, leave it alone.
  1216. return
  1217. else:
  1218. new_db_params = new_field.db_parameters(connection=self.connection)
  1219. sql = (
  1220. self.sql_alter_column_null
  1221. if new_field.null
  1222. else self.sql_alter_column_not_null
  1223. )
  1224. return (
  1225. sql
  1226. % {
  1227. "column": self.quote_name(new_field.column),
  1228. "type": new_db_params["type"],
  1229. },
  1230. [],
  1231. )
  1232. def _alter_column_default_sql(self, model, old_field, new_field, drop=False):
  1233. """
  1234. Hook to specialize column default alteration.
  1235. Return a (sql, params) fragment to add or drop (depending on the drop
  1236. argument) a default to new_field's column.
  1237. """
  1238. new_default = self.effective_default(new_field)
  1239. default = self._column_default_sql(new_field)
  1240. params = [new_default]
  1241. if drop:
  1242. params = []
  1243. elif self.connection.features.requires_literal_defaults:
  1244. # Some databases (Oracle) can't take defaults as a parameter
  1245. # If this is the case, the SchemaEditor for that database should
  1246. # implement prepare_default().
  1247. default = self.prepare_default(new_default)
  1248. params = []
  1249. new_db_params = new_field.db_parameters(connection=self.connection)
  1250. if drop:
  1251. if new_field.null:
  1252. sql = self.sql_alter_column_no_default_null
  1253. else:
  1254. sql = self.sql_alter_column_no_default
  1255. else:
  1256. sql = self.sql_alter_column_default
  1257. return (
  1258. sql
  1259. % {
  1260. "column": self.quote_name(new_field.column),
  1261. "type": new_db_params["type"],
  1262. "default": default,
  1263. },
  1264. params,
  1265. )
  1266. def _alter_column_database_default_sql(
  1267. self, model, old_field, new_field, drop=False
  1268. ):
  1269. """
  1270. Hook to specialize column database default alteration.
  1271. Return a (sql, params) fragment to add or drop (depending on the drop
  1272. argument) a default to new_field's column.
  1273. """
  1274. if drop:
  1275. sql = self.sql_alter_column_no_default
  1276. default_sql = ""
  1277. params = []
  1278. else:
  1279. sql = self.sql_alter_column_default
  1280. default_sql, params = self.db_default_sql(new_field)
  1281. new_db_params = new_field.db_parameters(connection=self.connection)
  1282. return (
  1283. sql
  1284. % {
  1285. "column": self.quote_name(new_field.column),
  1286. "type": new_db_params["type"],
  1287. "default": default_sql,
  1288. },
  1289. params,
  1290. )
  1291. def _alter_column_type_sql(
  1292. self, model, old_field, new_field, new_type, old_collation, new_collation
  1293. ):
  1294. """
  1295. Hook to specialize column type alteration for different backends,
  1296. for cases when a creation type is different to an alteration type
  1297. (e.g. SERIAL in PostgreSQL, PostGIS fields).
  1298. Return a 2-tuple of: an SQL fragment of (sql, params) to insert into
  1299. an ALTER TABLE statement and a list of extra (sql, params) tuples to
  1300. run once the field is altered.
  1301. """
  1302. other_actions = []
  1303. if collate_sql := self._collate_sql(
  1304. new_collation, old_collation, model._meta.db_table
  1305. ):
  1306. collate_sql = f" {collate_sql}"
  1307. else:
  1308. collate_sql = ""
  1309. # Comment change?
  1310. comment_sql = ""
  1311. if self.connection.features.supports_comments and not new_field.many_to_many:
  1312. if old_field.db_comment != new_field.db_comment:
  1313. # PostgreSQL and Oracle can't execute 'ALTER COLUMN ...' and
  1314. # 'COMMENT ON ...' at the same time.
  1315. sql, params = self._alter_column_comment_sql(
  1316. model, new_field, new_type, new_field.db_comment
  1317. )
  1318. if sql:
  1319. other_actions.append((sql, params))
  1320. if new_field.db_comment:
  1321. comment_sql = self._comment_sql(new_field.db_comment)
  1322. return (
  1323. (
  1324. self.sql_alter_column_type
  1325. % {
  1326. "column": self.quote_name(new_field.column),
  1327. "type": new_type,
  1328. "collation": collate_sql,
  1329. "comment": comment_sql,
  1330. },
  1331. [],
  1332. ),
  1333. other_actions,
  1334. )
  1335. def _alter_column_comment_sql(self, model, new_field, new_type, new_db_comment):
  1336. return (
  1337. self.sql_alter_column_comment
  1338. % {
  1339. "table": self.quote_name(model._meta.db_table),
  1340. "column": self.quote_name(new_field.column),
  1341. "comment": self._comment_sql(new_db_comment),
  1342. },
  1343. [],
  1344. )
  1345. def _comment_sql(self, comment):
  1346. return self.quote_value(comment or "")
  1347. def _alter_many_to_many(self, model, old_field, new_field, strict):
  1348. """Alter M2Ms to repoint their to= endpoints."""
  1349. # Rename the through table
  1350. if (
  1351. old_field.remote_field.through._meta.db_table
  1352. != new_field.remote_field.through._meta.db_table
  1353. ):
  1354. self.alter_db_table(
  1355. old_field.remote_field.through,
  1356. old_field.remote_field.through._meta.db_table,
  1357. new_field.remote_field.through._meta.db_table,
  1358. )
  1359. # Repoint the FK to the other side
  1360. self.alter_field(
  1361. new_field.remote_field.through,
  1362. # The field that points to the target model is needed, so we can
  1363. # tell alter_field to change it - this is m2m_reverse_field_name()
  1364. # (as opposed to m2m_field_name(), which points to our model).
  1365. old_field.remote_field.through._meta.get_field(
  1366. old_field.m2m_reverse_field_name()
  1367. ),
  1368. new_field.remote_field.through._meta.get_field(
  1369. new_field.m2m_reverse_field_name()
  1370. ),
  1371. )
  1372. self.alter_field(
  1373. new_field.remote_field.through,
  1374. # for self-referential models we need to alter field from the other end too
  1375. old_field.remote_field.through._meta.get_field(old_field.m2m_field_name()),
  1376. new_field.remote_field.through._meta.get_field(new_field.m2m_field_name()),
  1377. )
  1378. def _create_index_name(self, table_name, column_names, suffix=""):
  1379. """
  1380. Generate a unique name for an index/unique constraint.
  1381. The name is divided into 3 parts: the table name, the column names,
  1382. and a unique digest and suffix.
  1383. """
  1384. _, table_name = split_identifier(table_name)
  1385. hash_suffix_part = "%s%s" % (
  1386. names_digest(table_name, *column_names, length=8),
  1387. suffix,
  1388. )
  1389. max_length = self.connection.ops.max_name_length() or 200
  1390. # If everything fits into max_length, use that name.
  1391. index_name = "%s_%s_%s" % (table_name, "_".join(column_names), hash_suffix_part)
  1392. if len(index_name) <= max_length:
  1393. return index_name
  1394. # Shorten a long suffix.
  1395. if len(hash_suffix_part) > max_length / 3:
  1396. hash_suffix_part = hash_suffix_part[: max_length // 3]
  1397. other_length = (max_length - len(hash_suffix_part)) // 2 - 1
  1398. index_name = "%s_%s_%s" % (
  1399. table_name[:other_length],
  1400. "_".join(column_names)[:other_length],
  1401. hash_suffix_part,
  1402. )
  1403. # Prepend D if needed to prevent the name from starting with an
  1404. # underscore or a number (not permitted on Oracle).
  1405. if index_name[0] == "_" or index_name[0].isdigit():
  1406. index_name = "D%s" % index_name[:-1]
  1407. return index_name
  1408. def _get_index_tablespace_sql(self, model, fields, db_tablespace=None):
  1409. if db_tablespace is None:
  1410. if len(fields) == 1 and fields[0].db_tablespace:
  1411. db_tablespace = fields[0].db_tablespace
  1412. elif settings.DEFAULT_INDEX_TABLESPACE:
  1413. db_tablespace = settings.DEFAULT_INDEX_TABLESPACE
  1414. elif model._meta.db_tablespace:
  1415. db_tablespace = model._meta.db_tablespace
  1416. if db_tablespace is not None:
  1417. return " " + self.connection.ops.tablespace_sql(db_tablespace)
  1418. return ""
  1419. def _index_condition_sql(self, condition):
  1420. if condition:
  1421. return " WHERE " + condition
  1422. return ""
  1423. def _index_include_sql(self, model, columns):
  1424. if not columns or not self.connection.features.supports_covering_indexes:
  1425. return ""
  1426. return Statement(
  1427. " INCLUDE (%(columns)s)",
  1428. columns=Columns(model._meta.db_table, columns, self.quote_name),
  1429. )
  1430. def _create_index_sql(
  1431. self,
  1432. model,
  1433. *,
  1434. fields=None,
  1435. name=None,
  1436. suffix="",
  1437. using="",
  1438. db_tablespace=None,
  1439. col_suffixes=(),
  1440. sql=None,
  1441. opclasses=(),
  1442. condition=None,
  1443. include=None,
  1444. expressions=None,
  1445. ):
  1446. """
  1447. Return the SQL statement to create the index for one or several fields
  1448. or expressions. `sql` can be specified if the syntax differs from the
  1449. standard (GIS indexes, ...).
  1450. """
  1451. fields = fields or []
  1452. expressions = expressions or []
  1453. compiler = Query(model, alias_cols=False).get_compiler(
  1454. connection=self.connection,
  1455. )
  1456. tablespace_sql = self._get_index_tablespace_sql(
  1457. model, fields, db_tablespace=db_tablespace
  1458. )
  1459. columns = [field.column for field in fields]
  1460. sql_create_index = sql or self.sql_create_index
  1461. table = model._meta.db_table
  1462. def create_index_name(*args, **kwargs):
  1463. nonlocal name
  1464. if name is None:
  1465. name = self._create_index_name(*args, **kwargs)
  1466. return self.quote_name(name)
  1467. return Statement(
  1468. sql_create_index,
  1469. table=Table(table, self.quote_name),
  1470. name=IndexName(table, columns, suffix, create_index_name),
  1471. using=using,
  1472. columns=(
  1473. self._index_columns(table, columns, col_suffixes, opclasses)
  1474. if columns
  1475. else Expressions(table, expressions, compiler, self.quote_value)
  1476. ),
  1477. extra=tablespace_sql,
  1478. condition=self._index_condition_sql(condition),
  1479. include=self._index_include_sql(model, include),
  1480. )
  1481. def _delete_index_sql(self, model, name, sql=None):
  1482. return Statement(
  1483. sql or self.sql_delete_index,
  1484. table=Table(model._meta.db_table, self.quote_name),
  1485. name=self.quote_name(name),
  1486. )
  1487. def _rename_index_sql(self, model, old_name, new_name):
  1488. return Statement(
  1489. self.sql_rename_index,
  1490. table=Table(model._meta.db_table, self.quote_name),
  1491. old_name=self.quote_name(old_name),
  1492. new_name=self.quote_name(new_name),
  1493. )
  1494. def _index_columns(self, table, columns, col_suffixes, opclasses):
  1495. return Columns(table, columns, self.quote_name, col_suffixes=col_suffixes)
  1496. def _model_indexes_sql(self, model):
  1497. """
  1498. Return a list of all index SQL statements (field indexes,
  1499. index_together, Meta.indexes) for the specified model.
  1500. """
  1501. if not model._meta.managed or model._meta.proxy or model._meta.swapped:
  1502. return []
  1503. output = []
  1504. for field in model._meta.local_fields:
  1505. output.extend(self._field_indexes_sql(model, field))
  1506. # RemovedInDjango51Warning.
  1507. for field_names in model._meta.index_together:
  1508. fields = [model._meta.get_field(field) for field in field_names]
  1509. output.append(self._create_index_sql(model, fields=fields, suffix="_idx"))
  1510. for index in model._meta.indexes:
  1511. if (
  1512. not index.contains_expressions
  1513. or self.connection.features.supports_expression_indexes
  1514. ):
  1515. output.append(index.create_sql(model, self))
  1516. return output
  1517. def _field_indexes_sql(self, model, field):
  1518. """
  1519. Return a list of all index SQL statements for the specified field.
  1520. """
  1521. output = []
  1522. if self._field_should_be_indexed(model, field):
  1523. output.append(self._create_index_sql(model, fields=[field]))
  1524. return output
  1525. def _field_should_be_altered(self, old_field, new_field, ignore=None):
  1526. if not old_field.concrete and not new_field.concrete:
  1527. return False
  1528. ignore = ignore or set()
  1529. _, old_path, old_args, old_kwargs = old_field.deconstruct()
  1530. _, new_path, new_args, new_kwargs = new_field.deconstruct()
  1531. # Don't alter when:
  1532. # - changing only a field name
  1533. # - changing an attribute that doesn't affect the schema
  1534. # - changing an attribute in the provided set of ignored attributes
  1535. # - adding only a db_column and the column name is not changed
  1536. # - db_table does not change for model referenced by foreign keys
  1537. for attr in ignore.union(old_field.non_db_attrs):
  1538. old_kwargs.pop(attr, None)
  1539. for attr in ignore.union(new_field.non_db_attrs):
  1540. new_kwargs.pop(attr, None)
  1541. if (
  1542. not new_field.many_to_many
  1543. and old_field.remote_field
  1544. and new_field.remote_field
  1545. and old_field.remote_field.model._meta.db_table
  1546. == new_field.remote_field.model._meta.db_table
  1547. ):
  1548. old_kwargs.pop("to", None)
  1549. new_kwargs.pop("to", None)
  1550. return self.quote_name(old_field.column) != self.quote_name(
  1551. new_field.column
  1552. ) or (old_path, old_args, old_kwargs) != (new_path, new_args, new_kwargs)
  1553. def _field_should_be_indexed(self, model, field):
  1554. return field.db_index and not field.unique
  1555. def _field_became_primary_key(self, old_field, new_field):
  1556. return not old_field.primary_key and new_field.primary_key
  1557. def _unique_should_be_added(self, old_field, new_field):
  1558. return (
  1559. not new_field.primary_key
  1560. and new_field.unique
  1561. and (not old_field.unique or old_field.primary_key)
  1562. )
  1563. def _rename_field_sql(self, table, old_field, new_field, new_type):
  1564. return self.sql_rename_column % {
  1565. "table": self.quote_name(table),
  1566. "old_column": self.quote_name(old_field.column),
  1567. "new_column": self.quote_name(new_field.column),
  1568. "type": new_type,
  1569. }
  1570. def _create_fk_sql(self, model, field, suffix):
  1571. table = Table(model._meta.db_table, self.quote_name)
  1572. name = self._fk_constraint_name(model, field, suffix)
  1573. column = Columns(model._meta.db_table, [field.column], self.quote_name)
  1574. to_table = Table(field.target_field.model._meta.db_table, self.quote_name)
  1575. to_column = Columns(
  1576. field.target_field.model._meta.db_table,
  1577. [field.target_field.column],
  1578. self.quote_name,
  1579. )
  1580. deferrable = self.connection.ops.deferrable_sql()
  1581. return Statement(
  1582. self.sql_create_fk,
  1583. table=table,
  1584. name=name,
  1585. column=column,
  1586. to_table=to_table,
  1587. to_column=to_column,
  1588. deferrable=deferrable,
  1589. )
  1590. def _fk_constraint_name(self, model, field, suffix):
  1591. def create_fk_name(*args, **kwargs):
  1592. return self.quote_name(self._create_index_name(*args, **kwargs))
  1593. return ForeignKeyName(
  1594. model._meta.db_table,
  1595. [field.column],
  1596. split_identifier(field.target_field.model._meta.db_table)[1],
  1597. [field.target_field.column],
  1598. suffix,
  1599. create_fk_name,
  1600. )
  1601. def _delete_fk_sql(self, model, name):
  1602. return self._delete_constraint_sql(self.sql_delete_fk, model, name)
  1603. def _deferrable_constraint_sql(self, deferrable):
  1604. if deferrable is None:
  1605. return ""
  1606. if deferrable == Deferrable.DEFERRED:
  1607. return " DEFERRABLE INITIALLY DEFERRED"
  1608. if deferrable == Deferrable.IMMEDIATE:
  1609. return " DEFERRABLE INITIALLY IMMEDIATE"
  1610. def _unique_index_nulls_distinct_sql(self, nulls_distinct):
  1611. if nulls_distinct is False:
  1612. return " NULLS NOT DISTINCT"
  1613. elif nulls_distinct is True:
  1614. return " NULLS DISTINCT"
  1615. return ""
  1616. def _unique_supported(
  1617. self,
  1618. condition=None,
  1619. deferrable=None,
  1620. include=None,
  1621. expressions=None,
  1622. nulls_distinct=None,
  1623. ):
  1624. return (
  1625. (not condition or self.connection.features.supports_partial_indexes)
  1626. and (
  1627. not deferrable
  1628. or self.connection.features.supports_deferrable_unique_constraints
  1629. )
  1630. and (not include or self.connection.features.supports_covering_indexes)
  1631. and (
  1632. not expressions or self.connection.features.supports_expression_indexes
  1633. )
  1634. and (
  1635. nulls_distinct is None
  1636. or self.connection.features.supports_nulls_distinct_unique_constraints
  1637. )
  1638. )
  1639. def _unique_sql(
  1640. self,
  1641. model,
  1642. fields,
  1643. name,
  1644. condition=None,
  1645. deferrable=None,
  1646. include=None,
  1647. opclasses=None,
  1648. expressions=None,
  1649. nulls_distinct=None,
  1650. ):
  1651. if not self._unique_supported(
  1652. condition=condition,
  1653. deferrable=deferrable,
  1654. include=include,
  1655. expressions=expressions,
  1656. nulls_distinct=nulls_distinct,
  1657. ):
  1658. return None
  1659. if (
  1660. condition
  1661. or include
  1662. or opclasses
  1663. or expressions
  1664. or nulls_distinct is not None
  1665. ):
  1666. # Databases support conditional, covering, functional unique,
  1667. # and nulls distinct constraints via a unique index.
  1668. sql = self._create_unique_sql(
  1669. model,
  1670. fields,
  1671. name=name,
  1672. condition=condition,
  1673. include=include,
  1674. opclasses=opclasses,
  1675. expressions=expressions,
  1676. nulls_distinct=nulls_distinct,
  1677. )
  1678. if sql:
  1679. self.deferred_sql.append(sql)
  1680. return None
  1681. constraint = self.sql_unique_constraint % {
  1682. "columns": ", ".join([self.quote_name(field.column) for field in fields]),
  1683. "deferrable": self._deferrable_constraint_sql(deferrable),
  1684. }
  1685. return self.sql_constraint % {
  1686. "name": self.quote_name(name),
  1687. "constraint": constraint,
  1688. }
  1689. def _create_unique_sql(
  1690. self,
  1691. model,
  1692. fields,
  1693. name=None,
  1694. condition=None,
  1695. deferrable=None,
  1696. include=None,
  1697. opclasses=None,
  1698. expressions=None,
  1699. nulls_distinct=None,
  1700. ):
  1701. if not self._unique_supported(
  1702. condition=condition,
  1703. deferrable=deferrable,
  1704. include=include,
  1705. expressions=expressions,
  1706. nulls_distinct=nulls_distinct,
  1707. ):
  1708. return None
  1709. compiler = Query(model, alias_cols=False).get_compiler(
  1710. connection=self.connection
  1711. )
  1712. table = model._meta.db_table
  1713. columns = [field.column for field in fields]
  1714. if name is None:
  1715. name = self._unique_constraint_name(table, columns, quote=True)
  1716. else:
  1717. name = self.quote_name(name)
  1718. if condition or include or opclasses or expressions:
  1719. sql = self.sql_create_unique_index
  1720. else:
  1721. sql = self.sql_create_unique
  1722. if columns:
  1723. columns = self._index_columns(
  1724. table, columns, col_suffixes=(), opclasses=opclasses
  1725. )
  1726. else:
  1727. columns = Expressions(table, expressions, compiler, self.quote_value)
  1728. return Statement(
  1729. sql,
  1730. table=Table(table, self.quote_name),
  1731. name=name,
  1732. columns=columns,
  1733. condition=self._index_condition_sql(condition),
  1734. deferrable=self._deferrable_constraint_sql(deferrable),
  1735. include=self._index_include_sql(model, include),
  1736. nulls_distinct=self._unique_index_nulls_distinct_sql(nulls_distinct),
  1737. )
  1738. def _unique_constraint_name(self, table, columns, quote=True):
  1739. if quote:
  1740. def create_unique_name(*args, **kwargs):
  1741. return self.quote_name(self._create_index_name(*args, **kwargs))
  1742. else:
  1743. create_unique_name = self._create_index_name
  1744. return IndexName(table, columns, "_uniq", create_unique_name)
  1745. def _delete_unique_sql(
  1746. self,
  1747. model,
  1748. name,
  1749. condition=None,
  1750. deferrable=None,
  1751. include=None,
  1752. opclasses=None,
  1753. expressions=None,
  1754. nulls_distinct=None,
  1755. ):
  1756. if not self._unique_supported(
  1757. condition=condition,
  1758. deferrable=deferrable,
  1759. include=include,
  1760. expressions=expressions,
  1761. nulls_distinct=nulls_distinct,
  1762. ):
  1763. return None
  1764. if condition or include or opclasses or expressions:
  1765. sql = self.sql_delete_index
  1766. else:
  1767. sql = self.sql_delete_unique
  1768. return self._delete_constraint_sql(sql, model, name)
  1769. def _check_sql(self, name, check):
  1770. return self.sql_constraint % {
  1771. "name": self.quote_name(name),
  1772. "constraint": self.sql_check_constraint % {"check": check},
  1773. }
  1774. def _create_check_sql(self, model, name, check):
  1775. if not self.connection.features.supports_table_check_constraints:
  1776. return None
  1777. return Statement(
  1778. self.sql_create_check,
  1779. table=Table(model._meta.db_table, self.quote_name),
  1780. name=self.quote_name(name),
  1781. check=check,
  1782. )
  1783. def _delete_check_sql(self, model, name):
  1784. if not self.connection.features.supports_table_check_constraints:
  1785. return None
  1786. return self._delete_constraint_sql(self.sql_delete_check, model, name)
  1787. def _delete_constraint_sql(self, template, model, name):
  1788. return Statement(
  1789. template,
  1790. table=Table(model._meta.db_table, self.quote_name),
  1791. name=self.quote_name(name),
  1792. )
  1793. def _constraint_names(
  1794. self,
  1795. model,
  1796. column_names=None,
  1797. unique=None,
  1798. primary_key=None,
  1799. index=None,
  1800. foreign_key=None,
  1801. check=None,
  1802. type_=None,
  1803. exclude=None,
  1804. ):
  1805. """Return all constraint names matching the columns and conditions."""
  1806. if column_names is not None:
  1807. column_names = [
  1808. (
  1809. self.connection.introspection.identifier_converter(
  1810. truncate_name(name, self.connection.ops.max_name_length())
  1811. )
  1812. if self.connection.features.truncates_names
  1813. else self.connection.introspection.identifier_converter(name)
  1814. )
  1815. for name in column_names
  1816. ]
  1817. with self.connection.cursor() as cursor:
  1818. constraints = self.connection.introspection.get_constraints(
  1819. cursor, model._meta.db_table
  1820. )
  1821. result = []
  1822. for name, infodict in constraints.items():
  1823. if column_names is None or column_names == infodict["columns"]:
  1824. if unique is not None and infodict["unique"] != unique:
  1825. continue
  1826. if primary_key is not None and infodict["primary_key"] != primary_key:
  1827. continue
  1828. if index is not None and infodict["index"] != index:
  1829. continue
  1830. if check is not None and infodict["check"] != check:
  1831. continue
  1832. if foreign_key is not None and not infodict["foreign_key"]:
  1833. continue
  1834. if type_ is not None and infodict["type"] != type_:
  1835. continue
  1836. if not exclude or name not in exclude:
  1837. result.append(name)
  1838. return result
  1839. def _delete_primary_key(self, model, strict=False):
  1840. constraint_names = self._constraint_names(model, primary_key=True)
  1841. if strict and len(constraint_names) != 1:
  1842. raise ValueError(
  1843. "Found wrong number (%s) of PK constraints for %s"
  1844. % (
  1845. len(constraint_names),
  1846. model._meta.db_table,
  1847. )
  1848. )
  1849. for constraint_name in constraint_names:
  1850. self.execute(self._delete_primary_key_sql(model, constraint_name))
  1851. def _create_primary_key_sql(self, model, field):
  1852. return Statement(
  1853. self.sql_create_pk,
  1854. table=Table(model._meta.db_table, self.quote_name),
  1855. name=self.quote_name(
  1856. self._create_index_name(
  1857. model._meta.db_table, [field.column], suffix="_pk"
  1858. )
  1859. ),
  1860. columns=Columns(model._meta.db_table, [field.column], self.quote_name),
  1861. )
  1862. def _delete_primary_key_sql(self, model, name):
  1863. return self._delete_constraint_sql(self.sql_delete_pk, model, name)
  1864. def _collate_sql(self, collation, old_collation=None, table_name=None):
  1865. return "COLLATE " + self.quote_name(collation) if collation else ""
  1866. def remove_procedure(self, procedure_name, param_types=()):
  1867. sql = self.sql_delete_procedure % {
  1868. "procedure": self.quote_name(procedure_name),
  1869. "param_types": ",".join(param_types),
  1870. }
  1871. self.execute(sql)