schema.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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 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)"
  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)"
  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)%(extra)s%(condition)s"
  71. sql_create_unique_index = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)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 = bytes()
  253. else:
  254. default = str()
  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(model, fields, {'index': True}, self.sql_delete_index)
  350. # Created indexes
  351. for field_names in news.difference(olds):
  352. fields = [model._meta.get_field(field) for field in field_names]
  353. self.execute(self._create_index_sql(model, fields, suffix="_idx"))
  354. def _delete_composed_index(self, model, fields, constraint_kwargs, sql):
  355. meta_constraint_names = {constraint.name for constraint in model._meta.constraints}
  356. meta_index_names = {constraint.name for constraint in model._meta.indexes}
  357. columns = [model._meta.get_field(field).column for field in fields]
  358. constraint_names = self._constraint_names(
  359. model, columns, exclude=meta_constraint_names | meta_index_names,
  360. **constraint_kwargs
  361. )
  362. if len(constraint_names) != 1:
  363. raise ValueError("Found wrong number (%s) of constraints for %s(%s)" % (
  364. len(constraint_names),
  365. model._meta.db_table,
  366. ", ".join(columns),
  367. ))
  368. self.execute(self._delete_constraint_sql(sql, model, constraint_names[0]))
  369. def alter_db_table(self, model, old_db_table, new_db_table):
  370. """Rename the table a model points to."""
  371. if (old_db_table == new_db_table or
  372. (self.connection.features.ignores_table_name_case and
  373. old_db_table.lower() == new_db_table.lower())):
  374. return
  375. self.execute(self.sql_rename_table % {
  376. "old_table": self.quote_name(old_db_table),
  377. "new_table": self.quote_name(new_db_table),
  378. })
  379. # Rename all references to the old table name.
  380. for sql in self.deferred_sql:
  381. if isinstance(sql, Statement):
  382. sql.rename_table_references(old_db_table, new_db_table)
  383. def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):
  384. """Move a model's table between tablespaces."""
  385. self.execute(self.sql_retablespace_table % {
  386. "table": self.quote_name(model._meta.db_table),
  387. "old_tablespace": self.quote_name(old_db_tablespace),
  388. "new_tablespace": self.quote_name(new_db_tablespace),
  389. })
  390. def add_field(self, model, field):
  391. """
  392. Create a field on a model. Usually involves adding a column, but may
  393. involve adding a table instead (for M2M fields).
  394. """
  395. # Special-case implicit M2M tables
  396. if field.many_to_many and field.remote_field.through._meta.auto_created:
  397. return self.create_model(field.remote_field.through)
  398. # Get the column's definition
  399. definition, params = self.column_sql(model, field, include_default=True)
  400. # It might not actually have a column behind it
  401. if definition is None:
  402. return
  403. # Check constraints can go on the column SQL here
  404. db_params = field.db_parameters(connection=self.connection)
  405. if db_params['check']:
  406. definition += " " + self.sql_check_constraint % db_params
  407. if field.remote_field and self.connection.features.supports_foreign_keys and field.db_constraint:
  408. constraint_suffix = '_fk_%(to_table)s_%(to_column)s'
  409. # Add FK constraint inline, if supported.
  410. if self.sql_create_column_inline_fk:
  411. to_table = field.remote_field.model._meta.db_table
  412. to_column = field.remote_field.model._meta.get_field(field.remote_field.field_name).column
  413. definition += " " + self.sql_create_column_inline_fk % {
  414. 'name': self._fk_constraint_name(model, field, constraint_suffix),
  415. 'column': self.quote_name(field.column),
  416. 'to_table': self.quote_name(to_table),
  417. 'to_column': self.quote_name(to_column),
  418. 'deferrable': self.connection.ops.deferrable_sql()
  419. }
  420. # Otherwise, add FK constraints later.
  421. else:
  422. self.deferred_sql.append(self._create_fk_sql(model, field, constraint_suffix))
  423. # Build the SQL and run it
  424. sql = self.sql_create_column % {
  425. "table": self.quote_name(model._meta.db_table),
  426. "column": self.quote_name(field.column),
  427. "definition": definition,
  428. }
  429. self.execute(sql, params)
  430. # Drop the default if we need to
  431. # (Django usually does not use in-database defaults)
  432. if not self.skip_default(field) and self.effective_default(field) is not None:
  433. changes_sql, params = self._alter_column_default_sql(model, None, field, drop=True)
  434. sql = self.sql_alter_column % {
  435. "table": self.quote_name(model._meta.db_table),
  436. "changes": changes_sql,
  437. }
  438. self.execute(sql, params)
  439. # Add an index, if required
  440. self.deferred_sql.extend(self._field_indexes_sql(model, field))
  441. # Reset connection if required
  442. if self.connection.features.connection_persists_old_columns:
  443. self.connection.close()
  444. def remove_field(self, model, field):
  445. """
  446. Remove a field from a model. Usually involves deleting a column,
  447. but for M2Ms may involve deleting a table.
  448. """
  449. # Special-case implicit M2M tables
  450. if field.many_to_many and field.remote_field.through._meta.auto_created:
  451. return self.delete_model(field.remote_field.through)
  452. # It might not actually have a column behind it
  453. if field.db_parameters(connection=self.connection)['type'] is None:
  454. return
  455. # Drop any FK constraints, MySQL requires explicit deletion
  456. if field.remote_field:
  457. fk_names = self._constraint_names(model, [field.column], foreign_key=True)
  458. for fk_name in fk_names:
  459. self.execute(self._delete_fk_sql(model, fk_name))
  460. # Delete the column
  461. sql = self.sql_delete_column % {
  462. "table": self.quote_name(model._meta.db_table),
  463. "column": self.quote_name(field.column),
  464. }
  465. self.execute(sql)
  466. # Reset connection if required
  467. if self.connection.features.connection_persists_old_columns:
  468. self.connection.close()
  469. # Remove all deferred statements referencing the deleted column.
  470. for sql in list(self.deferred_sql):
  471. if isinstance(sql, Statement) and sql.references_column(model._meta.db_table, field.column):
  472. self.deferred_sql.remove(sql)
  473. def alter_field(self, model, old_field, new_field, strict=False):
  474. """
  475. Allow a field's type, uniqueness, nullability, default, column,
  476. constraints, etc. to be modified.
  477. `old_field` is required to compute the necessary changes.
  478. If `strict` is True, raise errors if the old column does not match
  479. `old_field` precisely.
  480. """
  481. # Ensure this field is even column-based
  482. old_db_params = old_field.db_parameters(connection=self.connection)
  483. old_type = old_db_params['type']
  484. new_db_params = new_field.db_parameters(connection=self.connection)
  485. new_type = new_db_params['type']
  486. if ((old_type is None and old_field.remote_field is None) or
  487. (new_type is None and new_field.remote_field is None)):
  488. raise ValueError(
  489. "Cannot alter field %s into %s - they do not properly define "
  490. "db_type (are you using a badly-written custom field?)" %
  491. (old_field, new_field),
  492. )
  493. elif old_type is None and new_type is None and (
  494. old_field.remote_field.through and new_field.remote_field.through and
  495. old_field.remote_field.through._meta.auto_created and
  496. new_field.remote_field.through._meta.auto_created):
  497. return self._alter_many_to_many(model, old_field, new_field, strict)
  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. not old_field.remote_field.through._meta.auto_created and
  501. not new_field.remote_field.through._meta.auto_created):
  502. # Both sides have through models; this is a no-op.
  503. return
  504. elif old_type is None or new_type is None:
  505. raise ValueError(
  506. "Cannot alter field %s into %s - they are not compatible types "
  507. "(you cannot alter to or from M2M fields, or add or remove "
  508. "through= on M2M fields)" % (old_field, new_field)
  509. )
  510. self._alter_field(model, old_field, new_field, old_type, new_type,
  511. old_db_params, new_db_params, strict)
  512. def _alter_field(self, model, old_field, new_field, old_type, new_type,
  513. old_db_params, new_db_params, strict=False):
  514. """Perform a "physical" (non-ManyToMany) field update."""
  515. # Drop any FK constraints, we'll remake them later
  516. fks_dropped = set()
  517. if old_field.remote_field and old_field.db_constraint:
  518. fk_names = self._constraint_names(model, [old_field.column], foreign_key=True)
  519. if strict and len(fk_names) != 1:
  520. raise ValueError("Found wrong number (%s) of foreign key constraints for %s.%s" % (
  521. len(fk_names),
  522. model._meta.db_table,
  523. old_field.column,
  524. ))
  525. for fk_name in fk_names:
  526. fks_dropped.add((old_field.column,))
  527. self.execute(self._delete_fk_sql(model, fk_name))
  528. # Has unique been removed?
  529. if old_field.unique and (not new_field.unique or self._field_became_primary_key(old_field, new_field)):
  530. # Find the unique constraint for this field
  531. meta_constraint_names = {constraint.name for constraint in model._meta.constraints}
  532. constraint_names = self._constraint_names(
  533. model, [old_field.column], unique=True, primary_key=False,
  534. exclude=meta_constraint_names,
  535. )
  536. if strict and len(constraint_names) != 1:
  537. raise ValueError("Found wrong number (%s) of unique constraints for %s.%s" % (
  538. len(constraint_names),
  539. model._meta.db_table,
  540. old_field.column,
  541. ))
  542. for constraint_name in constraint_names:
  543. self.execute(self._delete_unique_sql(model, constraint_name))
  544. # Drop incoming FK constraints if the field is a primary key or unique,
  545. # which might be a to_field target, and things are going to change.
  546. drop_foreign_keys = (
  547. (
  548. (old_field.primary_key and new_field.primary_key) or
  549. (old_field.unique and new_field.unique)
  550. ) and old_type != new_type
  551. )
  552. if drop_foreign_keys:
  553. # '_meta.related_field' also contains M2M reverse fields, these
  554. # will be filtered out
  555. for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):
  556. rel_fk_names = self._constraint_names(
  557. new_rel.related_model, [new_rel.field.column], foreign_key=True
  558. )
  559. for fk_name in rel_fk_names:
  560. self.execute(self._delete_fk_sql(new_rel.related_model, fk_name))
  561. # Removed an index? (no strict check, as multiple indexes are possible)
  562. # Remove indexes if db_index switched to False or a unique constraint
  563. # will now be used in lieu of an index. The following lines from the
  564. # truth table show all True cases; the rest are False:
  565. #
  566. # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
  567. # ------------------------------------------------------------------------------
  568. # True | False | False | False
  569. # True | False | False | True
  570. # True | False | True | True
  571. if old_field.db_index and not old_field.unique and (not new_field.db_index or new_field.unique):
  572. # Find the index for this field
  573. meta_index_names = {index.name for index in model._meta.indexes}
  574. # Retrieve only BTREE indexes since this is what's created with
  575. # db_index=True.
  576. index_names = self._constraint_names(
  577. model, [old_field.column], index=True, type_=Index.suffix,
  578. exclude=meta_index_names,
  579. )
  580. for index_name in index_names:
  581. # The only way to check if an index was created with
  582. # db_index=True or with Index(['field'], name='foo')
  583. # is to look at its name (refs #28053).
  584. self.execute(self._delete_index_sql(model, index_name))
  585. # Change check constraints?
  586. if old_db_params['check'] != new_db_params['check'] and old_db_params['check']:
  587. meta_constraint_names = {constraint.name for constraint in model._meta.constraints}
  588. constraint_names = self._constraint_names(
  589. model, [old_field.column], check=True,
  590. exclude=meta_constraint_names,
  591. )
  592. if strict and len(constraint_names) != 1:
  593. raise ValueError("Found wrong number (%s) of check constraints for %s.%s" % (
  594. len(constraint_names),
  595. model._meta.db_table,
  596. old_field.column,
  597. ))
  598. for constraint_name in constraint_names:
  599. self.execute(self._delete_check_sql(model, constraint_name))
  600. # Have they renamed the column?
  601. if old_field.column != new_field.column:
  602. self.execute(self._rename_field_sql(model._meta.db_table, old_field, new_field, new_type))
  603. # Rename all references to the renamed column.
  604. for sql in self.deferred_sql:
  605. if isinstance(sql, Statement):
  606. sql.rename_column_references(model._meta.db_table, old_field.column, new_field.column)
  607. # Next, start accumulating actions to do
  608. actions = []
  609. null_actions = []
  610. post_actions = []
  611. # Type change?
  612. if old_type != new_type:
  613. fragment, other_actions = self._alter_column_type_sql(model, old_field, new_field, new_type)
  614. actions.append(fragment)
  615. post_actions.extend(other_actions)
  616. # When changing a column NULL constraint to NOT NULL with a given
  617. # default value, we need to perform 4 steps:
  618. # 1. Add a default for new incoming writes
  619. # 2. Update existing NULL rows with new default
  620. # 3. Replace NULL constraint with NOT NULL
  621. # 4. Drop the default again.
  622. # Default change?
  623. old_default = self.effective_default(old_field)
  624. new_default = self.effective_default(new_field)
  625. needs_database_default = (
  626. old_field.null and
  627. not new_field.null and
  628. old_default != new_default and
  629. new_default is not None and
  630. not self.skip_default(new_field)
  631. )
  632. if needs_database_default:
  633. actions.append(self._alter_column_default_sql(model, old_field, new_field))
  634. # Nullability change?
  635. if old_field.null != new_field.null:
  636. fragment = self._alter_column_null_sql(model, old_field, new_field)
  637. if fragment:
  638. null_actions.append(fragment)
  639. # Only if we have a default and there is a change from NULL to NOT NULL
  640. four_way_default_alteration = (
  641. new_field.has_default() and
  642. (old_field.null and not new_field.null)
  643. )
  644. if actions or null_actions:
  645. if not four_way_default_alteration:
  646. # If we don't have to do a 4-way default alteration we can
  647. # directly run a (NOT) NULL alteration
  648. actions = actions + null_actions
  649. # Combine actions together if we can (e.g. postgres)
  650. if self.connection.features.supports_combined_alters and actions:
  651. sql, params = tuple(zip(*actions))
  652. actions = [(", ".join(sql), sum(params, []))]
  653. # Apply those actions
  654. for sql, params in actions:
  655. self.execute(
  656. self.sql_alter_column % {
  657. "table": self.quote_name(model._meta.db_table),
  658. "changes": sql,
  659. },
  660. params,
  661. )
  662. if four_way_default_alteration:
  663. # Update existing rows with default value
  664. self.execute(
  665. self.sql_update_with_default % {
  666. "table": self.quote_name(model._meta.db_table),
  667. "column": self.quote_name(new_field.column),
  668. "default": "%s",
  669. },
  670. [new_default],
  671. )
  672. # Since we didn't run a NOT NULL change before we need to do it
  673. # now
  674. for sql, params in null_actions:
  675. self.execute(
  676. self.sql_alter_column % {
  677. "table": self.quote_name(model._meta.db_table),
  678. "changes": sql,
  679. },
  680. params,
  681. )
  682. if post_actions:
  683. for sql, params in post_actions:
  684. self.execute(sql, params)
  685. # If primary_key changed to False, delete the primary key constraint.
  686. if old_field.primary_key and not new_field.primary_key:
  687. self._delete_primary_key(model, strict)
  688. # Added a unique?
  689. if self._unique_should_be_added(old_field, new_field):
  690. self.execute(self._create_unique_sql(model, [new_field.column]))
  691. # Added an index? Add an index if db_index switched to True or a unique
  692. # constraint will no longer be used in lieu of an index. The following
  693. # lines from the truth table show all True cases; the rest are False:
  694. #
  695. # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique
  696. # ------------------------------------------------------------------------------
  697. # False | False | True | False
  698. # False | True | True | False
  699. # True | True | True | False
  700. if (not old_field.db_index or old_field.unique) and new_field.db_index and not new_field.unique:
  701. self.execute(self._create_index_sql(model, [new_field]))
  702. # Type alteration on primary key? Then we need to alter the column
  703. # referring to us.
  704. rels_to_update = []
  705. if drop_foreign_keys:
  706. rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
  707. # Changed to become primary key?
  708. if self._field_became_primary_key(old_field, new_field):
  709. # Make the new one
  710. self.execute(self._create_primary_key_sql(model, new_field))
  711. # Update all referencing columns
  712. rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
  713. # Handle our type alters on the other end of rels from the PK stuff above
  714. for old_rel, new_rel in rels_to_update:
  715. rel_db_params = new_rel.field.db_parameters(connection=self.connection)
  716. rel_type = rel_db_params['type']
  717. fragment, other_actions = self._alter_column_type_sql(
  718. new_rel.related_model, old_rel.field, new_rel.field, rel_type
  719. )
  720. self.execute(
  721. self.sql_alter_column % {
  722. "table": self.quote_name(new_rel.related_model._meta.db_table),
  723. "changes": fragment[0],
  724. },
  725. fragment[1],
  726. )
  727. for sql, params in other_actions:
  728. self.execute(sql, params)
  729. # Does it have a foreign key?
  730. if (new_field.remote_field and
  731. (fks_dropped or not old_field.remote_field or not old_field.db_constraint) and
  732. new_field.db_constraint):
  733. self.execute(self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s"))
  734. # Rebuild FKs that pointed to us if we previously had to drop them
  735. if drop_foreign_keys:
  736. for rel in new_field.model._meta.related_objects:
  737. if _is_relevant_relation(rel, new_field) and rel.field.db_constraint:
  738. self.execute(self._create_fk_sql(rel.related_model, rel.field, "_fk"))
  739. # Does it have check constraints we need to add?
  740. if old_db_params['check'] != new_db_params['check'] and new_db_params['check']:
  741. constraint_name = self._create_index_name(model._meta.db_table, [new_field.column], suffix='_check')
  742. self.execute(self._create_check_sql(model, constraint_name, new_db_params['check']))
  743. # Drop the default if we need to
  744. # (Django usually does not use in-database defaults)
  745. if needs_database_default:
  746. changes_sql, params = self._alter_column_default_sql(model, old_field, new_field, drop=True)
  747. sql = self.sql_alter_column % {
  748. "table": self.quote_name(model._meta.db_table),
  749. "changes": changes_sql,
  750. }
  751. self.execute(sql, params)
  752. # Reset connection if required
  753. if self.connection.features.connection_persists_old_columns:
  754. self.connection.close()
  755. def _alter_column_null_sql(self, model, old_field, new_field):
  756. """
  757. Hook to specialize column null alteration.
  758. Return a (sql, params) fragment to set a column to null or non-null
  759. as required by new_field, or None if no changes are required.
  760. """
  761. if (self.connection.features.interprets_empty_strings_as_nulls and
  762. new_field.get_internal_type() in ("CharField", "TextField")):
  763. # The field is nullable in the database anyway, leave it alone.
  764. return
  765. else:
  766. new_db_params = new_field.db_parameters(connection=self.connection)
  767. sql = self.sql_alter_column_null if new_field.null else self.sql_alter_column_not_null
  768. return (
  769. sql % {
  770. 'column': self.quote_name(new_field.column),
  771. 'type': new_db_params['type'],
  772. },
  773. [],
  774. )
  775. def _alter_column_default_sql(self, model, old_field, new_field, drop=False):
  776. """
  777. Hook to specialize column default alteration.
  778. Return a (sql, params) fragment to add or drop (depending on the drop
  779. argument) a default to new_field's column.
  780. """
  781. new_default = self.effective_default(new_field)
  782. default = self._column_default_sql(new_field)
  783. params = [new_default]
  784. if drop:
  785. params = []
  786. elif self.connection.features.requires_literal_defaults:
  787. # Some databases (Oracle) can't take defaults as a parameter
  788. # If this is the case, the SchemaEditor for that database should
  789. # implement prepare_default().
  790. default = self.prepare_default(new_default)
  791. params = []
  792. new_db_params = new_field.db_parameters(connection=self.connection)
  793. sql = self.sql_alter_column_no_default if drop else self.sql_alter_column_default
  794. return (
  795. sql % {
  796. 'column': self.quote_name(new_field.column),
  797. 'type': new_db_params['type'],
  798. 'default': default,
  799. },
  800. params,
  801. )
  802. def _alter_column_type_sql(self, model, old_field, new_field, new_type):
  803. """
  804. Hook to specialize column type alteration for different backends,
  805. for cases when a creation type is different to an alteration type
  806. (e.g. SERIAL in PostgreSQL, PostGIS fields).
  807. Return a two-tuple of: an SQL fragment of (sql, params) to insert into
  808. an ALTER TABLE statement and a list of extra (sql, params) tuples to
  809. run once the field is altered.
  810. """
  811. return (
  812. (
  813. self.sql_alter_column_type % {
  814. "column": self.quote_name(new_field.column),
  815. "type": new_type,
  816. },
  817. [],
  818. ),
  819. [],
  820. )
  821. def _alter_many_to_many(self, model, old_field, new_field, strict):
  822. """Alter M2Ms to repoint their to= endpoints."""
  823. # Rename the through table
  824. if old_field.remote_field.through._meta.db_table != new_field.remote_field.through._meta.db_table:
  825. self.alter_db_table(old_field.remote_field.through, old_field.remote_field.through._meta.db_table,
  826. new_field.remote_field.through._meta.db_table)
  827. # Repoint the FK to the other side
  828. self.alter_field(
  829. new_field.remote_field.through,
  830. # We need the field that points to the target model, so we can tell alter_field to change it -
  831. # this is m2m_reverse_field_name() (as opposed to m2m_field_name, which points to our model)
  832. old_field.remote_field.through._meta.get_field(old_field.m2m_reverse_field_name()),
  833. new_field.remote_field.through._meta.get_field(new_field.m2m_reverse_field_name()),
  834. )
  835. self.alter_field(
  836. new_field.remote_field.through,
  837. # for self-referential models we need to alter field from the other end too
  838. old_field.remote_field.through._meta.get_field(old_field.m2m_field_name()),
  839. new_field.remote_field.through._meta.get_field(new_field.m2m_field_name()),
  840. )
  841. def _create_index_name(self, table_name, column_names, suffix=""):
  842. """
  843. Generate a unique name for an index/unique constraint.
  844. The name is divided into 3 parts: the table name, the column names,
  845. and a unique digest and suffix.
  846. """
  847. _, table_name = split_identifier(table_name)
  848. hash_suffix_part = '%s%s' % (names_digest(table_name, *column_names, length=8), suffix)
  849. max_length = self.connection.ops.max_name_length() or 200
  850. # If everything fits into max_length, use that name.
  851. index_name = '%s_%s_%s' % (table_name, '_'.join(column_names), hash_suffix_part)
  852. if len(index_name) <= max_length:
  853. return index_name
  854. # Shorten a long suffix.
  855. if len(hash_suffix_part) > max_length / 3:
  856. hash_suffix_part = hash_suffix_part[:max_length // 3]
  857. other_length = (max_length - len(hash_suffix_part)) // 2 - 1
  858. index_name = '%s_%s_%s' % (
  859. table_name[:other_length],
  860. '_'.join(column_names)[:other_length],
  861. hash_suffix_part,
  862. )
  863. # Prepend D if needed to prevent the name from starting with an
  864. # underscore or a number (not permitted on Oracle).
  865. if index_name[0] == "_" or index_name[0].isdigit():
  866. index_name = "D%s" % index_name[:-1]
  867. return index_name
  868. def _get_index_tablespace_sql(self, model, fields, db_tablespace=None):
  869. if db_tablespace is None:
  870. if len(fields) == 1 and fields[0].db_tablespace:
  871. db_tablespace = fields[0].db_tablespace
  872. elif model._meta.db_tablespace:
  873. db_tablespace = model._meta.db_tablespace
  874. if db_tablespace is not None:
  875. return ' ' + self.connection.ops.tablespace_sql(db_tablespace)
  876. return ''
  877. def _create_index_sql(self, model, fields, *, name=None, suffix='', using='',
  878. db_tablespace=None, col_suffixes=(), sql=None, opclasses=(),
  879. condition=None):
  880. """
  881. Return the SQL statement to create the index for one or several fields.
  882. `sql` can be specified if the syntax differs from the standard (GIS
  883. indexes, ...).
  884. """
  885. tablespace_sql = self._get_index_tablespace_sql(model, fields, db_tablespace=db_tablespace)
  886. columns = [field.column for field in fields]
  887. sql_create_index = sql or self.sql_create_index
  888. table = model._meta.db_table
  889. def create_index_name(*args, **kwargs):
  890. nonlocal name
  891. if name is None:
  892. name = self._create_index_name(*args, **kwargs)
  893. return self.quote_name(name)
  894. return Statement(
  895. sql_create_index,
  896. table=Table(table, self.quote_name),
  897. name=IndexName(table, columns, suffix, create_index_name),
  898. using=using,
  899. columns=self._index_columns(table, columns, col_suffixes, opclasses),
  900. extra=tablespace_sql,
  901. condition=(' WHERE ' + condition) if condition else '',
  902. )
  903. def _delete_index_sql(self, model, name, sql=None):
  904. return Statement(
  905. sql or self.sql_delete_index,
  906. table=Table(model._meta.db_table, self.quote_name),
  907. name=self.quote_name(name),
  908. )
  909. def _index_columns(self, table, columns, col_suffixes, opclasses):
  910. return Columns(table, columns, self.quote_name, col_suffixes=col_suffixes)
  911. def _model_indexes_sql(self, model):
  912. """
  913. Return a list of all index SQL statements (field indexes,
  914. index_together, Meta.indexes) for the specified model.
  915. """
  916. if not model._meta.managed or model._meta.proxy or model._meta.swapped:
  917. return []
  918. output = []
  919. for field in model._meta.local_fields:
  920. output.extend(self._field_indexes_sql(model, field))
  921. for field_names in model._meta.index_together:
  922. fields = [model._meta.get_field(field) for field in field_names]
  923. output.append(self._create_index_sql(model, fields, suffix="_idx"))
  924. for index in model._meta.indexes:
  925. output.append(index.create_sql(model, self))
  926. return output
  927. def _field_indexes_sql(self, model, field):
  928. """
  929. Return a list of all index SQL statements for the specified field.
  930. """
  931. output = []
  932. if self._field_should_be_indexed(model, field):
  933. output.append(self._create_index_sql(model, [field]))
  934. return output
  935. def _field_should_be_indexed(self, model, field):
  936. return field.db_index and not field.unique
  937. def _field_became_primary_key(self, old_field, new_field):
  938. return not old_field.primary_key and new_field.primary_key
  939. def _unique_should_be_added(self, old_field, new_field):
  940. return (not old_field.unique and new_field.unique) or (
  941. old_field.primary_key and not new_field.primary_key and new_field.unique
  942. )
  943. def _rename_field_sql(self, table, old_field, new_field, new_type):
  944. return self.sql_rename_column % {
  945. "table": self.quote_name(table),
  946. "old_column": self.quote_name(old_field.column),
  947. "new_column": self.quote_name(new_field.column),
  948. "type": new_type,
  949. }
  950. def _create_fk_sql(self, model, field, suffix):
  951. table = Table(model._meta.db_table, self.quote_name)
  952. name = self._fk_constraint_name(model, field, suffix)
  953. column = Columns(model._meta.db_table, [field.column], self.quote_name)
  954. to_table = Table(field.target_field.model._meta.db_table, self.quote_name)
  955. to_column = Columns(field.target_field.model._meta.db_table, [field.target_field.column], self.quote_name)
  956. deferrable = self.connection.ops.deferrable_sql()
  957. return Statement(
  958. self.sql_create_fk,
  959. table=table,
  960. name=name,
  961. column=column,
  962. to_table=to_table,
  963. to_column=to_column,
  964. deferrable=deferrable,
  965. )
  966. def _fk_constraint_name(self, model, field, suffix):
  967. def create_fk_name(*args, **kwargs):
  968. return self.quote_name(self._create_index_name(*args, **kwargs))
  969. return ForeignKeyName(
  970. model._meta.db_table,
  971. [field.column],
  972. split_identifier(field.target_field.model._meta.db_table)[1],
  973. [field.target_field.column],
  974. suffix,
  975. create_fk_name,
  976. )
  977. def _delete_fk_sql(self, model, name):
  978. return self._delete_constraint_sql(self.sql_delete_fk, model, name)
  979. def _unique_sql(self, model, fields, name, condition=None):
  980. if condition:
  981. # Databases support conditional unique constraints via a unique
  982. # index.
  983. sql = self._create_unique_sql(model, fields, name=name, condition=condition)
  984. if sql:
  985. self.deferred_sql.append(sql)
  986. return None
  987. constraint = self.sql_unique_constraint % {
  988. 'columns': ', '.join(map(self.quote_name, fields)),
  989. }
  990. return self.sql_constraint % {
  991. 'name': self.quote_name(name),
  992. 'constraint': constraint,
  993. }
  994. def _create_unique_sql(self, model, columns, name=None, condition=None):
  995. def create_unique_name(*args, **kwargs):
  996. return self.quote_name(self._create_index_name(*args, **kwargs))
  997. table = Table(model._meta.db_table, self.quote_name)
  998. if name is None:
  999. name = IndexName(model._meta.db_table, columns, '_uniq', create_unique_name)
  1000. else:
  1001. name = self.quote_name(name)
  1002. columns = Columns(table, columns, self.quote_name)
  1003. if condition:
  1004. return Statement(
  1005. self.sql_create_unique_index,
  1006. table=table,
  1007. name=name,
  1008. columns=columns,
  1009. condition=' WHERE ' + condition,
  1010. ) if self.connection.features.supports_partial_indexes else None
  1011. else:
  1012. return Statement(
  1013. self.sql_create_unique,
  1014. table=table,
  1015. name=name,
  1016. columns=columns,
  1017. )
  1018. def _delete_unique_sql(self, model, name, condition=None):
  1019. if condition:
  1020. return (
  1021. self._delete_constraint_sql(self.sql_delete_index, model, name)
  1022. if self.connection.features.supports_partial_indexes else None
  1023. )
  1024. return self._delete_constraint_sql(self.sql_delete_unique, model, name)
  1025. def _check_sql(self, name, check):
  1026. return self.sql_constraint % {
  1027. 'name': self.quote_name(name),
  1028. 'constraint': self.sql_check_constraint % {'check': check},
  1029. }
  1030. def _create_check_sql(self, model, name, check):
  1031. return Statement(
  1032. self.sql_create_check,
  1033. table=Table(model._meta.db_table, self.quote_name),
  1034. name=self.quote_name(name),
  1035. check=check,
  1036. )
  1037. def _delete_check_sql(self, model, name):
  1038. return self._delete_constraint_sql(self.sql_delete_check, model, name)
  1039. def _delete_constraint_sql(self, template, model, name):
  1040. return Statement(
  1041. template,
  1042. table=Table(model._meta.db_table, self.quote_name),
  1043. name=self.quote_name(name),
  1044. )
  1045. def _constraint_names(self, model, column_names=None, unique=None,
  1046. primary_key=None, index=None, foreign_key=None,
  1047. check=None, type_=None, exclude=None):
  1048. """Return all constraint names matching the columns and conditions."""
  1049. if column_names is not None:
  1050. column_names = [
  1051. self.connection.introspection.identifier_converter(name)
  1052. for name in column_names
  1053. ]
  1054. with self.connection.cursor() as cursor:
  1055. constraints = self.connection.introspection.get_constraints(cursor, model._meta.db_table)
  1056. result = []
  1057. for name, infodict in constraints.items():
  1058. if column_names is None or column_names == infodict['columns']:
  1059. if unique is not None and infodict['unique'] != unique:
  1060. continue
  1061. if primary_key is not None and infodict['primary_key'] != primary_key:
  1062. continue
  1063. if index is not None and infodict['index'] != index:
  1064. continue
  1065. if check is not None and infodict['check'] != check:
  1066. continue
  1067. if foreign_key is not None and not infodict['foreign_key']:
  1068. continue
  1069. if type_ is not None and infodict['type'] != type_:
  1070. continue
  1071. if not exclude or name not in exclude:
  1072. result.append(name)
  1073. return result
  1074. def _delete_primary_key(self, model, strict=False):
  1075. constraint_names = self._constraint_names(model, primary_key=True)
  1076. if strict and len(constraint_names) != 1:
  1077. raise ValueError('Found wrong number (%s) of PK constraints for %s' % (
  1078. len(constraint_names),
  1079. model._meta.db_table,
  1080. ))
  1081. for constraint_name in constraint_names:
  1082. self.execute(self._delete_primary_key_sql(model, constraint_name))
  1083. def _create_primary_key_sql(self, model, field):
  1084. return Statement(
  1085. self.sql_create_pk,
  1086. table=Table(model._meta.db_table, self.quote_name),
  1087. name=self.quote_name(
  1088. self._create_index_name(model._meta.db_table, [field.column], suffix="_pk")
  1089. ),
  1090. columns=Columns(model._meta.db_table, [field.column], self.quote_name),
  1091. )
  1092. def _delete_primary_key_sql(self, model, name):
  1093. return self._delete_constraint_sql(self.sql_delete_pk, model, name)
  1094. def remove_procedure(self, procedure_name, param_types=()):
  1095. sql = self.sql_delete_procedure % {
  1096. 'procedure': self.quote_name(procedure_name),
  1097. 'param_types': ','.join(param_types),
  1098. }
  1099. self.execute(sql)