You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

927 lines
42 KiB

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