schema.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. import hashlib
  2. import operator
  3. from django.db.backends.creation import BaseDatabaseCreation
  4. from django.db.backends.utils import truncate_name
  5. from django.db.models.fields.related import ManyToManyField
  6. from django.db.transaction import atomic
  7. from django.utils.encoding import force_bytes
  8. from django.utils.log import getLogger
  9. from django.utils.six.moves import reduce
  10. from django.utils import six
  11. logger = getLogger('django.db.backends.schema')
  12. class BaseDatabaseSchemaEditor(object):
  13. """
  14. This class (and its subclasses) are responsible for emitting schema-changing
  15. statements to the databases - model creation/removal/alteration, field
  16. renaming, index fiddling, and so on.
  17. It is intended to eventually completely replace DatabaseCreation.
  18. This class should be used by creating an instance for each set of schema
  19. changes (e.g. a syncdb run, a migration file), and by first calling start(),
  20. then the relevant actions, and then commit(). This is necessary to allow
  21. things like circular foreign key references - FKs will only be created once
  22. commit() is called.
  23. """
  24. # Overrideable SQL templates
  25. sql_create_table = "CREATE TABLE %(table)s (%(definition)s)"
  26. sql_create_table_unique = "UNIQUE (%(columns)s)"
  27. sql_rename_table = "ALTER TABLE %(old_table)s RENAME TO %(new_table)s"
  28. sql_retablespace_table = "ALTER TABLE %(table)s SET TABLESPACE %(new_tablespace)s"
  29. sql_delete_table = "DROP TABLE %(table)s CASCADE"
  30. sql_create_column = "ALTER TABLE %(table)s ADD COLUMN %(column)s %(definition)s"
  31. sql_alter_column = "ALTER TABLE %(table)s %(changes)s"
  32. sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s"
  33. sql_alter_column_null = "ALTER COLUMN %(column)s DROP NOT NULL"
  34. sql_alter_column_not_null = "ALTER COLUMN %(column)s SET NOT NULL"
  35. sql_alter_column_default = "ALTER COLUMN %(column)s SET DEFAULT %(default)s"
  36. sql_alter_column_no_default = "ALTER COLUMN %(column)s DROP DEFAULT"
  37. sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s CASCADE"
  38. sql_rename_column = "ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s"
  39. sql_create_check = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)"
  40. sql_delete_check = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
  41. sql_create_unique = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s UNIQUE (%(columns)s)"
  42. sql_delete_unique = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
  43. sql_create_fk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) REFERENCES %(to_table)s (%(to_column)s) DEFERRABLE INITIALLY DEFERRED"
  44. sql_create_inline_fk = None
  45. sql_delete_fk = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
  46. sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s"
  47. sql_delete_index = "DROP INDEX %(name)s"
  48. sql_create_pk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
  49. sql_delete_pk = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
  50. def __init__(self, connection, collect_sql=False):
  51. self.connection = connection
  52. self.collect_sql = collect_sql
  53. if self.collect_sql:
  54. self.collected_sql = []
  55. # State-managing methods
  56. def __enter__(self):
  57. self.deferred_sql = []
  58. if self.connection.features.can_rollback_ddl:
  59. self.atomic = atomic(self.connection.alias)
  60. self.atomic.__enter__()
  61. return self
  62. def __exit__(self, exc_type, exc_value, traceback):
  63. if exc_type is None:
  64. for sql in self.deferred_sql:
  65. self.execute(sql)
  66. if self.connection.features.can_rollback_ddl:
  67. self.atomic.__exit__(exc_type, exc_value, traceback)
  68. # Core utility functions
  69. def execute(self, sql, params=[]):
  70. """
  71. Executes the given SQL statement, with optional parameters.
  72. """
  73. # Log the command we're running, then run it
  74. logger.debug("%s; (params %r)" % (sql, params))
  75. if self.collect_sql:
  76. self.collected_sql.append((sql % tuple(map(self.quote_value, params))) + ";")
  77. else:
  78. with self.connection.cursor() as cursor:
  79. cursor.execute(sql, params)
  80. def quote_name(self, name):
  81. return self.connection.ops.quote_name(name)
  82. # Field <-> database mapping functions
  83. def column_sql(self, model, field, include_default=False):
  84. """
  85. Takes a field and returns its column definition.
  86. The field must already have had set_attributes_from_name called.
  87. """
  88. # Get the column's type and use that as the basis of the SQL
  89. db_params = field.db_parameters(connection=self.connection)
  90. sql = db_params['type']
  91. params = []
  92. # Check for fields that aren't actually columns (e.g. M2M)
  93. if sql is None:
  94. return None, None
  95. # Work out nullability
  96. null = field.null
  97. # If we were told to include a default value, do so
  98. default_value = self.effective_default(field)
  99. include_default = include_default and not self.skip_default(field)
  100. if include_default and default_value is not None:
  101. if self.connection.features.requires_literal_defaults:
  102. # Some databases can't take defaults as a parameter (oracle)
  103. # If this is the case, the individual schema backend should
  104. # implement prepare_default
  105. sql += " DEFAULT %s" % self.prepare_default(default_value)
  106. else:
  107. sql += " DEFAULT %s"
  108. params += [default_value]
  109. # Oracle treats the empty string ('') as null, so coerce the null
  110. # option whenever '' is a possible value.
  111. if (field.empty_strings_allowed and not field.primary_key and
  112. self.connection.features.interprets_empty_strings_as_nulls):
  113. null = True
  114. if null and not self.connection.features.implied_column_null:
  115. sql += " NULL"
  116. elif not null:
  117. sql += " NOT NULL"
  118. # Primary key/unique outputs
  119. if field.primary_key:
  120. sql += " PRIMARY KEY"
  121. elif field.unique:
  122. sql += " UNIQUE"
  123. # Optionally add the tablespace if it's an implicitly indexed column
  124. tablespace = field.db_tablespace or model._meta.db_tablespace
  125. if tablespace and self.connection.features.supports_tablespaces and field.unique:
  126. sql += " %s" % self.connection.ops.tablespace_sql(tablespace, inline=True)
  127. # Return the sql
  128. return sql, params
  129. def skip_default(self, field):
  130. """
  131. Some backends don't accept default values for certain columns types
  132. (i.e. MySQL longtext and longblob).
  133. """
  134. return False
  135. def prepare_default(self, value):
  136. """
  137. Only used for backends which have requires_literal_defaults feature
  138. """
  139. raise NotImplementedError('subclasses of BaseDatabaseSchemaEditor for backends which have requires_literal_defaults must provide a prepare_default() method')
  140. def effective_default(self, field):
  141. """
  142. Returns a field's effective database default value
  143. """
  144. if field.has_default():
  145. default = field.get_default()
  146. elif not field.null and field.blank and field.empty_strings_allowed:
  147. if field.get_internal_type() == "BinaryField":
  148. default = six.binary_type()
  149. else:
  150. default = six.text_type()
  151. else:
  152. default = None
  153. # If it's a callable, call it
  154. if six.callable(default):
  155. default = default()
  156. # Run it through the field's get_db_prep_save method so we can send it
  157. # to the database.
  158. default = field.get_db_prep_save(default, self.connection)
  159. return default
  160. def quote_value(self, value):
  161. """
  162. Returns a quoted version of the value so it's safe to use in an SQL
  163. string. This is not safe against injection from user code; it is
  164. intended only for use in making SQL scripts or preparing default values
  165. for particularly tricky backends (defaults are not user-defined, though,
  166. so this is safe).
  167. """
  168. raise NotImplementedError()
  169. # Actions
  170. def create_model(self, model):
  171. """
  172. Takes a model and creates a table for it in the database.
  173. Will also create any accompanying indexes or unique constraints.
  174. """
  175. # Create column SQL, add FK deferreds if needed
  176. column_sqls = []
  177. params = []
  178. for field in model._meta.local_fields:
  179. # SQL
  180. definition, extra_params = self.column_sql(model, field)
  181. if definition is None:
  182. continue
  183. # Check constraints can go on the column SQL here
  184. db_params = field.db_parameters(connection=self.connection)
  185. if db_params['check']:
  186. definition += " CHECK (%s)" % db_params['check']
  187. # Autoincrement SQL (for backends with inline variant)
  188. col_type_suffix = field.db_type_suffix(connection=self.connection)
  189. if col_type_suffix:
  190. definition += " %s" % col_type_suffix
  191. params.extend(extra_params)
  192. # Indexes
  193. if field.db_index and not field.unique:
  194. self.deferred_sql.append(
  195. self.sql_create_index % {
  196. "name": self._create_index_name(model, [field.column], suffix=""),
  197. "table": self.quote_name(model._meta.db_table),
  198. "columns": self.quote_name(field.column),
  199. "extra": "",
  200. }
  201. )
  202. # FK
  203. if field.rel and field.db_constraint:
  204. to_table = field.rel.to._meta.db_table
  205. to_column = field.rel.to._meta.get_field(field.rel.field_name).column
  206. if self.connection.features.supports_foreign_keys:
  207. self.deferred_sql.append(
  208. self.sql_create_fk % {
  209. "name": self._create_index_name(model, [field.column], suffix="_fk_%s_%s" % (to_table, to_column)),
  210. "table": self.quote_name(model._meta.db_table),
  211. "column": self.quote_name(field.column),
  212. "to_table": self.quote_name(to_table),
  213. "to_column": self.quote_name(to_column),
  214. }
  215. )
  216. elif self.sql_create_inline_fk:
  217. definition += " " + self.sql_create_inline_fk % {
  218. "to_table": self.quote_name(to_table),
  219. "to_column": self.quote_name(to_column),
  220. }
  221. # Add the SQL to our big list
  222. column_sqls.append("%s %s" % (
  223. self.quote_name(field.column),
  224. definition,
  225. ))
  226. # Autoincrement SQL (for backends with post table definition variant)
  227. if field.get_internal_type() == "AutoField":
  228. autoinc_sql = self.connection.ops.autoinc_sql(model._meta.db_table, field.column)
  229. if autoinc_sql:
  230. self.deferred_sql.extend(autoinc_sql)
  231. # Add any unique_togethers
  232. for fields in model._meta.unique_together:
  233. columns = [model._meta.get_field_by_name(field)[0].column for field in fields]
  234. column_sqls.append(self.sql_create_table_unique % {
  235. "columns": ", ".join(self.quote_name(column) for column in columns),
  236. })
  237. # Make the table
  238. sql = self.sql_create_table % {
  239. "table": self.quote_name(model._meta.db_table),
  240. "definition": ", ".join(column_sqls)
  241. }
  242. self.execute(sql, params)
  243. # Add any index_togethers
  244. for fields in model._meta.index_together:
  245. columns = [model._meta.get_field_by_name(field)[0].column for field in fields]
  246. self.execute(self.sql_create_index % {
  247. "table": self.quote_name(model._meta.db_table),
  248. "name": self._create_index_name(model, columns, suffix="_idx"),
  249. "columns": ", ".join(self.quote_name(column) for column in columns),
  250. "extra": "",
  251. })
  252. # Make M2M tables
  253. for field in model._meta.local_many_to_many:
  254. if field.rel.through._meta.auto_created:
  255. self.create_model(field.rel.through)
  256. def delete_model(self, model):
  257. """
  258. Deletes a model from the database.
  259. """
  260. # Handle auto-created intermediary models
  261. for field in model._meta.local_many_to_many:
  262. if field.rel.through._meta.auto_created:
  263. self.delete_model(field.rel.through)
  264. # Delete the table
  265. self.execute(self.sql_delete_table % {
  266. "table": self.quote_name(model._meta.db_table),
  267. })
  268. def alter_unique_together(self, model, old_unique_together, new_unique_together):
  269. """
  270. Deals with a model changing its unique_together.
  271. Note: The input unique_togethers must be doubly-nested, not the single-
  272. nested ["foo", "bar"] format.
  273. """
  274. olds = set(tuple(fields) for fields in old_unique_together)
  275. news = set(tuple(fields) for fields in new_unique_together)
  276. # Deleted uniques
  277. for fields in olds.difference(news):
  278. columns = [model._meta.get_field_by_name(field)[0].column for field in fields]
  279. constraint_names = self._constraint_names(model, columns, unique=True)
  280. if len(constraint_names) != 1:
  281. raise ValueError("Found wrong number (%s) of constraints for %s(%s)" % (
  282. len(constraint_names),
  283. model._meta.db_table,
  284. ", ".join(columns),
  285. ))
  286. self.execute(
  287. self.sql_delete_unique % {
  288. "table": self.quote_name(model._meta.db_table),
  289. "name": constraint_names[0],
  290. },
  291. )
  292. # Created uniques
  293. for fields in news.difference(olds):
  294. columns = [model._meta.get_field_by_name(field)[0].column for field in fields]
  295. self.execute(self.sql_create_unique % {
  296. "table": self.quote_name(model._meta.db_table),
  297. "name": self._create_index_name(model, columns, suffix="_uniq"),
  298. "columns": ", ".join(self.quote_name(column) for column in columns),
  299. })
  300. def alter_index_together(self, model, old_index_together, new_index_together):
  301. """
  302. Deals with a model changing its index_together.
  303. Note: The input index_togethers must be doubly-nested, not the single-
  304. nested ["foo", "bar"] format.
  305. """
  306. olds = set(tuple(fields) for fields in old_index_together)
  307. news = set(tuple(fields) for fields in new_index_together)
  308. # Deleted indexes
  309. for fields in olds.difference(news):
  310. columns = [model._meta.get_field_by_name(field)[0].column for field in fields]
  311. constraint_names = self._constraint_names(model, list(columns), index=True)
  312. if len(constraint_names) != 1:
  313. raise ValueError("Found wrong number (%s) of constraints for %s(%s)" % (
  314. len(constraint_names),
  315. model._meta.db_table,
  316. ", ".join(columns),
  317. ))
  318. self.execute(
  319. self.sql_delete_index % {
  320. "table": self.quote_name(model._meta.db_table),
  321. "name": constraint_names[0],
  322. },
  323. )
  324. # Created indexes
  325. for fields in news.difference(olds):
  326. columns = [model._meta.get_field_by_name(field)[0].column for field in fields]
  327. self.execute(self.sql_create_index % {
  328. "table": self.quote_name(model._meta.db_table),
  329. "name": self._create_index_name(model, columns, suffix="_idx"),
  330. "columns": ", ".join(self.quote_name(column) for column in columns),
  331. "extra": "",
  332. })
  333. def alter_db_table(self, model, old_db_table, new_db_table):
  334. """
  335. Renames the table a model points to.
  336. """
  337. if old_db_table == new_db_table:
  338. return
  339. self.execute(self.sql_rename_table % {
  340. "old_table": self.quote_name(old_db_table),
  341. "new_table": self.quote_name(new_db_table),
  342. })
  343. def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):
  344. """
  345. Moves a model's table between tablespaces
  346. """
  347. self.execute(self.sql_retablespace_table % {
  348. "table": self.quote_name(model._meta.db_table),
  349. "old_tablespace": self.quote_name(old_db_tablespace),
  350. "new_tablespace": self.quote_name(new_db_tablespace),
  351. })
  352. def add_field(self, model, field):
  353. """
  354. Creates a field on a model.
  355. Usually involves adding a column, but may involve adding a
  356. table instead (for M2M fields)
  357. """
  358. # Special-case implicit M2M tables
  359. if isinstance(field, ManyToManyField) and field.rel.through._meta.auto_created:
  360. return self.create_model(field.rel.through)
  361. # Get the column's definition
  362. definition, params = self.column_sql(model, field, include_default=True)
  363. # It might not actually have a column behind it
  364. if definition is None:
  365. return
  366. # Check constraints can go on the column SQL here
  367. db_params = field.db_parameters(connection=self.connection)
  368. if db_params['check']:
  369. definition += " CHECK (%s)" % db_params['check']
  370. # Build the SQL and run it
  371. sql = self.sql_create_column % {
  372. "table": self.quote_name(model._meta.db_table),
  373. "column": self.quote_name(field.column),
  374. "definition": definition,
  375. }
  376. self.execute(sql, params)
  377. # Drop the default if we need to
  378. # (Django usually does not use in-database defaults)
  379. if not self.skip_default(field) and field.default is not None:
  380. sql = self.sql_alter_column % {
  381. "table": self.quote_name(model._meta.db_table),
  382. "changes": self.sql_alter_column_no_default % {
  383. "column": self.quote_name(field.column),
  384. }
  385. }
  386. self.execute(sql)
  387. # Add an index, if required
  388. if field.db_index and not field.unique:
  389. self.deferred_sql.append(
  390. self.sql_create_index % {
  391. "name": self._create_index_name(model, [field.column], suffix=""),
  392. "table": self.quote_name(model._meta.db_table),
  393. "columns": self.quote_name(field.column),
  394. "extra": "",
  395. }
  396. )
  397. # Add any FK constraints later
  398. if field.rel and self.connection.features.supports_foreign_keys and field.db_constraint:
  399. to_table = field.rel.to._meta.db_table
  400. to_column = field.rel.to._meta.get_field(field.rel.field_name).column
  401. self.deferred_sql.append(
  402. self.sql_create_fk % {
  403. "name": self._create_index_name(model, [field.column], suffix="_fk_%s_%s" % (to_table, to_column)),
  404. "table": self.quote_name(model._meta.db_table),
  405. "column": self.quote_name(field.column),
  406. "to_table": self.quote_name(to_table),
  407. "to_column": self.quote_name(to_column),
  408. }
  409. )
  410. # Reset connection if required
  411. if self.connection.features.connection_persists_old_columns:
  412. self.connection.close()
  413. def remove_field(self, model, field):
  414. """
  415. Removes a field from a model. Usually involves deleting a column,
  416. but for M2Ms may involve deleting a table.
  417. """
  418. # Special-case implicit M2M tables
  419. if isinstance(field, ManyToManyField) and field.rel.through._meta.auto_created:
  420. return self.delete_model(field.rel.through)
  421. # It might not actually have a column behind it
  422. if field.db_parameters(connection=self.connection)['type'] is None:
  423. return
  424. # Drop any FK constraints, MySQL requires explicit deletion
  425. if field.rel:
  426. fk_names = self._constraint_names(model, [field.column], foreign_key=True)
  427. for fk_name in fk_names:
  428. self.execute(
  429. self.sql_delete_fk % {
  430. "table": self.quote_name(model._meta.db_table),
  431. "name": fk_name,
  432. }
  433. )
  434. # Delete the column
  435. sql = self.sql_delete_column % {
  436. "table": self.quote_name(model._meta.db_table),
  437. "column": self.quote_name(field.column),
  438. }
  439. self.execute(sql)
  440. # Reset connection if required
  441. if self.connection.features.connection_persists_old_columns:
  442. self.connection.close()
  443. def alter_field(self, model, old_field, new_field, strict=False):
  444. """
  445. Allows a field's type, uniqueness, nullability, default, column,
  446. constraints etc. to be modified.
  447. Requires a copy of the old field as well so we can only perform
  448. changes that are required.
  449. If strict is true, raises errors if the old column does not match old_field precisely.
  450. """
  451. # Ensure this field is even column-based
  452. old_db_params = old_field.db_parameters(connection=self.connection)
  453. old_type = old_db_params['type']
  454. new_db_params = new_field.db_parameters(connection=self.connection)
  455. new_type = new_db_params['type']
  456. if (old_type is None and old_field.rel is None) or (new_type is None and new_field.rel is None):
  457. raise ValueError("Cannot alter field %s into %s - they do not properly define db_type (are you using PostGIS 1.5 or badly-written custom fields?)" % (
  458. old_field,
  459. new_field,
  460. ))
  461. elif old_type is None and new_type is None and (old_field.rel.through and new_field.rel.through and old_field.rel.through._meta.auto_created and new_field.rel.through._meta.auto_created):
  462. return self._alter_many_to_many(model, old_field, new_field, strict)
  463. elif old_type is None and new_type is None and (old_field.rel.through and new_field.rel.through and not old_field.rel.through._meta.auto_created and not new_field.rel.through._meta.auto_created):
  464. # Both sides have through models; this is a no-op.
  465. return
  466. elif old_type is None or new_type is None:
  467. raise ValueError("Cannot alter field %s into %s - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)" % (
  468. old_field,
  469. new_field,
  470. ))
  471. self._alter_field(model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict)
  472. def _alter_field(self, model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict=False):
  473. """Actually perform a "physical" (non-ManyToMany) field update."""
  474. # Has unique been removed?
  475. if old_field.unique and (not new_field.unique or (not old_field.primary_key and new_field.primary_key)):
  476. # Find the unique constraint for this field
  477. constraint_names = self._constraint_names(model, [old_field.column], unique=True)
  478. if strict and len(constraint_names) != 1:
  479. raise ValueError("Found wrong number (%s) of unique constraints for %s.%s" % (
  480. len(constraint_names),
  481. model._meta.db_table,
  482. old_field.column,
  483. ))
  484. for constraint_name in constraint_names:
  485. self.execute(
  486. self.sql_delete_unique % {
  487. "table": self.quote_name(model._meta.db_table),
  488. "name": constraint_name,
  489. },
  490. )
  491. # Drop any FK constraints, we'll remake them later
  492. fks_dropped = set()
  493. if old_field.rel and old_field.db_constraint:
  494. fk_names = self._constraint_names(model, [old_field.column], foreign_key=True)
  495. if strict and len(fk_names) != 1:
  496. raise ValueError("Found wrong number (%s) of foreign key constraints for %s.%s" % (
  497. len(fk_names),
  498. model._meta.db_table,
  499. old_field.column,
  500. ))
  501. for fk_name in fk_names:
  502. fks_dropped.add((old_field.column,))
  503. self.execute(
  504. self.sql_delete_fk % {
  505. "table": self.quote_name(model._meta.db_table),
  506. "name": fk_name,
  507. }
  508. )
  509. # Drop incoming FK constraints if we're a primary key and things are going
  510. # to change.
  511. if old_field.primary_key and new_field.primary_key and old_type != new_type:
  512. for rel in new_field.model._meta.get_all_related_objects():
  513. rel_fk_names = self._constraint_names(rel.model, [rel.field.column], foreign_key=True)
  514. for fk_name in rel_fk_names:
  515. self.execute(
  516. self.sql_delete_fk % {
  517. "table": self.quote_name(rel.model._meta.db_table),
  518. "name": fk_name,
  519. }
  520. )
  521. # Removed an index?
  522. if old_field.db_index and not new_field.db_index and not old_field.unique and not (not new_field.unique and old_field.unique):
  523. # Find the index for this field
  524. index_names = self._constraint_names(model, [old_field.column], index=True)
  525. if strict and len(index_names) != 1:
  526. raise ValueError("Found wrong number (%s) of indexes for %s.%s" % (
  527. len(index_names),
  528. model._meta.db_table,
  529. old_field.column,
  530. ))
  531. for index_name in index_names:
  532. self.execute(
  533. self.sql_delete_index % {
  534. "table": self.quote_name(model._meta.db_table),
  535. "name": index_name,
  536. }
  537. )
  538. # Change check constraints?
  539. if old_db_params['check'] != new_db_params['check'] and old_db_params['check']:
  540. constraint_names = self._constraint_names(model, [old_field.column], check=True)
  541. if strict and len(constraint_names) != 1:
  542. raise ValueError("Found wrong number (%s) of check constraints for %s.%s" % (
  543. len(constraint_names),
  544. model._meta.db_table,
  545. old_field.column,
  546. ))
  547. for constraint_name in constraint_names:
  548. self.execute(
  549. self.sql_delete_check % {
  550. "table": self.quote_name(model._meta.db_table),
  551. "name": constraint_name,
  552. }
  553. )
  554. # Have they renamed the column?
  555. if old_field.column != new_field.column:
  556. self.execute(self.sql_rename_column % {
  557. "table": self.quote_name(model._meta.db_table),
  558. "old_column": self.quote_name(old_field.column),
  559. "new_column": self.quote_name(new_field.column),
  560. "type": new_type,
  561. })
  562. # Next, start accumulating actions to do
  563. actions = []
  564. post_actions = []
  565. # Type change?
  566. if old_type != new_type:
  567. fragment, other_actions = self._alter_column_type_sql(model._meta.db_table, new_field.column, new_type)
  568. actions.append(fragment)
  569. post_actions.extend(other_actions)
  570. # Default change?
  571. old_default = self.effective_default(old_field)
  572. new_default = self.effective_default(new_field)
  573. if old_default != new_default:
  574. if new_default is None:
  575. actions.append((
  576. self.sql_alter_column_no_default % {
  577. "column": self.quote_name(new_field.column),
  578. },
  579. [],
  580. ))
  581. else:
  582. if self.connection.features.requires_literal_defaults:
  583. # Some databases can't take defaults as a parameter (oracle)
  584. # If this is the case, the individual schema backend should
  585. # implement prepare_default
  586. actions.append((
  587. self.sql_alter_column_default % {
  588. "column": self.quote_name(new_field.column),
  589. "default": self.prepare_default(new_default),
  590. },
  591. [],
  592. ))
  593. else:
  594. actions.append((
  595. self.sql_alter_column_default % {
  596. "column": self.quote_name(new_field.column),
  597. "default": "%s",
  598. },
  599. [new_default],
  600. ))
  601. # Nullability change?
  602. if old_field.null != new_field.null:
  603. if new_field.null:
  604. actions.append((
  605. self.sql_alter_column_null % {
  606. "column": self.quote_name(new_field.column),
  607. "type": new_type,
  608. },
  609. [],
  610. ))
  611. else:
  612. actions.append((
  613. self.sql_alter_column_not_null % {
  614. "column": self.quote_name(new_field.column),
  615. "type": new_type,
  616. },
  617. [],
  618. ))
  619. if actions:
  620. # Combine actions together if we can (e.g. postgres)
  621. if self.connection.features.supports_combined_alters:
  622. sql, params = tuple(zip(*actions))
  623. actions = [(", ".join(sql), reduce(operator.add, params))]
  624. # Apply those actions
  625. for sql, params in actions:
  626. self.execute(
  627. self.sql_alter_column % {
  628. "table": self.quote_name(model._meta.db_table),
  629. "changes": sql,
  630. },
  631. params,
  632. )
  633. if post_actions:
  634. for sql, params in post_actions:
  635. self.execute(sql, params)
  636. # Added a unique?
  637. if not old_field.unique and new_field.unique:
  638. self.execute(
  639. self.sql_create_unique % {
  640. "table": self.quote_name(model._meta.db_table),
  641. "name": self._create_index_name(model, [new_field.column], suffix="_uniq"),
  642. "columns": self.quote_name(new_field.column),
  643. }
  644. )
  645. # Added an index?
  646. if not old_field.db_index and new_field.db_index and not new_field.unique and not (not old_field.unique and new_field.unique):
  647. self.execute(
  648. self.sql_create_index % {
  649. "table": self.quote_name(model._meta.db_table),
  650. "name": self._create_index_name(model, [new_field.column], suffix="_uniq"),
  651. "columns": self.quote_name(new_field.column),
  652. "extra": "",
  653. }
  654. )
  655. # Type alteration on primary key? Then we need to alter the column
  656. # referring to us.
  657. rels_to_update = []
  658. if old_field.primary_key and new_field.primary_key and old_type != new_type:
  659. rels_to_update.extend(new_field.model._meta.get_all_related_objects())
  660. # Changed to become primary key?
  661. # Note that we don't detect unsetting of a PK, as we assume another field
  662. # will always come along and replace it.
  663. if not old_field.primary_key and new_field.primary_key:
  664. # First, drop the old PK
  665. constraint_names = self._constraint_names(model, primary_key=True)
  666. if strict and len(constraint_names) != 1:
  667. raise ValueError("Found wrong number (%s) of PK constraints for %s" % (
  668. len(constraint_names),
  669. model._meta.db_table,
  670. ))
  671. for constraint_name in constraint_names:
  672. self.execute(
  673. self.sql_delete_pk % {
  674. "table": self.quote_name(model._meta.db_table),
  675. "name": constraint_name,
  676. },
  677. )
  678. # Make the new one
  679. self.execute(
  680. self.sql_create_pk % {
  681. "table": self.quote_name(model._meta.db_table),
  682. "name": self._create_index_name(model, [new_field.column], suffix="_pk"),
  683. "columns": self.quote_name(new_field.column),
  684. }
  685. )
  686. # Update all referencing columns
  687. rels_to_update.extend(new_field.model._meta.get_all_related_objects())
  688. # Handle our type alters on the other end of rels from the PK stuff above
  689. for rel in rels_to_update:
  690. rel_db_params = rel.field.db_parameters(connection=self.connection)
  691. rel_type = rel_db_params['type']
  692. self.execute(
  693. self.sql_alter_column % {
  694. "table": self.quote_name(rel.model._meta.db_table),
  695. "changes": self.sql_alter_column_type % {
  696. "column": self.quote_name(rel.field.column),
  697. "type": rel_type,
  698. }
  699. }
  700. )
  701. # Does it have a foreign key?
  702. if new_field.rel and \
  703. (fks_dropped or (old_field.rel and not old_field.db_constraint)) and \
  704. new_field.db_constraint:
  705. to_table = new_field.rel.to._meta.db_table
  706. to_column = new_field.rel.get_related_field().column
  707. self.execute(
  708. self.sql_create_fk % {
  709. "table": self.quote_name(model._meta.db_table),
  710. "name": self._create_index_name(model, [new_field.column], suffix="_fk_%s_%s" % (to_table, to_column)),
  711. "column": self.quote_name(new_field.column),
  712. "to_table": self.quote_name(to_table),
  713. "to_column": self.quote_name(to_column),
  714. }
  715. )
  716. # Rebuild FKs that pointed to us if we previously had to drop them
  717. if old_field.primary_key and new_field.primary_key and old_type != new_type:
  718. for rel in new_field.model._meta.get_all_related_objects():
  719. self.execute(
  720. self.sql_create_fk % {
  721. "table": self.quote_name(rel.model._meta.db_table),
  722. "name": self._create_index_name(rel.model, [rel.field.column], suffix="_fk"),
  723. "column": self.quote_name(rel.field.column),
  724. "to_table": self.quote_name(model._meta.db_table),
  725. "to_column": self.quote_name(new_field.column),
  726. }
  727. )
  728. # Does it have check constraints we need to add?
  729. if old_db_params['check'] != new_db_params['check'] and new_db_params['check']:
  730. self.execute(
  731. self.sql_create_check % {
  732. "table": self.quote_name(model._meta.db_table),
  733. "name": self._create_index_name(model, [new_field.column], suffix="_check"),
  734. "column": self.quote_name(new_field.column),
  735. "check": new_db_params['check'],
  736. }
  737. )
  738. # Drop the default if we need to
  739. # (Django usually does not use in-database defaults)
  740. if not self.skip_default(new_field) and new_field.default is not None:
  741. sql = self.sql_alter_column % {
  742. "table": self.quote_name(model._meta.db_table),
  743. "changes": self.sql_alter_column_no_default % {
  744. "column": self.quote_name(new_field.column),
  745. }
  746. }
  747. self.execute(sql)
  748. # Reset connection if required
  749. if self.connection.features.connection_persists_old_columns:
  750. self.connection.close()
  751. def _alter_column_type_sql(self, table, column, type):
  752. """
  753. Hook to specialize column type alteration for different backends,
  754. for cases when a creation type is different to an alteration type
  755. (e.g. SERIAL in PostgreSQL, PostGIS fields).
  756. Should return two things; an SQL fragment of (sql, params) to insert
  757. into an ALTER TABLE statement, and a list of extra (sql, params) tuples
  758. to run once the field is altered.
  759. """
  760. return (
  761. (
  762. self.sql_alter_column_type % {
  763. "column": self.quote_name(column),
  764. "type": type,
  765. },
  766. [],
  767. ),
  768. [],
  769. )
  770. def _alter_many_to_many(self, model, old_field, new_field, strict):
  771. """
  772. Alters M2Ms to repoint their to= endpoints.
  773. """
  774. # Rename the through table
  775. if old_field.rel.through._meta.db_table != new_field.rel.through._meta.db_table:
  776. self.alter_db_table(old_field.rel.through, old_field.rel.through._meta.db_table, new_field.rel.through._meta.db_table)
  777. # Repoint the FK to the other side
  778. self.alter_field(
  779. new_field.rel.through,
  780. # We need the field that points to the target model, so we can tell alter_field to change it -
  781. # this is m2m_reverse_field_name() (as opposed to m2m_field_name, which points to our model)
  782. old_field.rel.through._meta.get_field_by_name(old_field.m2m_reverse_field_name())[0],
  783. new_field.rel.through._meta.get_field_by_name(new_field.m2m_reverse_field_name())[0],
  784. )
  785. def _create_index_name(self, model, column_names, suffix=""):
  786. """
  787. Generates a unique name for an index/unique constraint.
  788. """
  789. # If there is just one column in the index, use a default algorithm from Django
  790. if len(column_names) == 1 and not suffix:
  791. return truncate_name(
  792. '%s_%s' % (model._meta.db_table, BaseDatabaseCreation._digest(column_names[0])),
  793. self.connection.ops.max_name_length()
  794. )
  795. # Else generate the name for the index using a different algorithm
  796. table_name = model._meta.db_table.replace('"', '').replace('.', '_')
  797. index_unique_name = '_%x' % abs(hash((table_name, ','.join(column_names))))
  798. max_length = self.connection.ops.max_name_length() or 200
  799. # If the index name is too long, truncate it
  800. index_name = ('%s_%s%s%s' % (table_name, column_names[0], index_unique_name, suffix)).replace('"', '').replace('.', '_')
  801. if len(index_name) > max_length:
  802. part = ('_%s%s%s' % (column_names[0], index_unique_name, suffix))
  803. index_name = '%s%s' % (table_name[:(max_length - len(part))], part)
  804. # It shouldn't start with an underscore (Oracle hates this)
  805. if index_name[0] == "_":
  806. index_name = index_name[1:]
  807. # If it's STILL too long, just hash it down
  808. if len(index_name) > max_length:
  809. index_name = hashlib.md5(force_bytes(index_name)).hexdigest()[:max_length]
  810. # It can't start with a number on Oracle, so prepend D if we need to
  811. if index_name[0].isdigit():
  812. index_name = "D%s" % index_name[:-1]
  813. return index_name
  814. def _constraint_names(self, model, column_names=None, unique=None, primary_key=None, index=None, foreign_key=None, check=None):
  815. """
  816. Returns all constraint names matching the columns and conditions
  817. """
  818. column_names = list(column_names) if column_names else None
  819. with self.connection.cursor() as cursor:
  820. constraints = self.connection.introspection.get_constraints(cursor, model._meta.db_table)
  821. result = []
  822. for name, infodict in constraints.items():
  823. if column_names is None or column_names == infodict['columns']:
  824. if unique is not None and infodict['unique'] != unique:
  825. continue
  826. if primary_key is not None and infodict['primary_key'] != primary_key:
  827. continue
  828. if index is not None and infodict['index'] != index:
  829. continue
  830. if check is not None and infodict['check'] != check:
  831. continue
  832. if foreign_key is not None and not infodict['foreign_key']:
  833. continue
  834. result.append(name)
  835. return result