2012-09-24 20:23:25 +08:00
|
|
|
import hashlib
|
2015-03-24 20:33:56 +08:00
|
|
|
import logging
|
2016-04-02 21:49:32 +08:00
|
|
|
from datetime import datetime
|
2013-07-26 23:40:27 +08:00
|
|
|
|
2013-09-17 00:52:05 +08:00
|
|
|
from django.db.backends.utils import truncate_name
|
2013-05-18 17:06:30 +08:00
|
|
|
from django.db.transaction import atomic
|
2016-04-02 21:49:32 +08:00
|
|
|
from django.utils import six, timezone
|
2013-11-23 06:31:50 +08:00
|
|
|
from django.utils.encoding import force_bytes
|
2012-06-19 00:32:03 +08:00
|
|
|
|
2015-03-24 20:33:56 +08:00
|
|
|
logger = logging.getLogger('django.db.backends.schema')
|
2012-06-19 00:32:03 +08:00
|
|
|
|
|
|
|
|
2015-04-11 22:10:31 +08:00
|
|
|
def _related_non_m2m_objects(old_field, new_field):
|
|
|
|
# Filters out m2m objects from reverse relations.
|
|
|
|
# Returns (old_relation, new_relation) tuples.
|
|
|
|
return zip(
|
|
|
|
(obj for obj in old_field.model._meta.related_objects if not obj.field.many_to_many),
|
|
|
|
(obj for obj in new_field.model._meta.related_objects if not obj.field.many_to_many)
|
|
|
|
)
|
2015-01-07 08:16:35 +08:00
|
|
|
|
|
|
|
|
2012-06-19 00:32:03 +08:00
|
|
|
class BaseDatabaseSchemaEditor(object):
|
|
|
|
"""
|
|
|
|
This class (and its subclasses) are responsible for emitting schema-changing
|
|
|
|
statements to the databases - model creation/removal/alteration, field
|
|
|
|
renaming, index fiddling, and so on.
|
|
|
|
|
|
|
|
It is intended to eventually completely replace DatabaseCreation.
|
|
|
|
|
|
|
|
This class should be used by creating an instance for each set of schema
|
2014-12-27 01:34:26 +08:00
|
|
|
changes (e.g. a migration file), and by first calling start(),
|
2012-06-19 00:32:03 +08:00
|
|
|
then the relevant actions, and then commit(). This is necessary to allow
|
|
|
|
things like circular foreign key references - FKs will only be created once
|
|
|
|
commit() is called.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Overrideable SQL templates
|
|
|
|
sql_create_table = "CREATE TABLE %(table)s (%(definition)s)"
|
|
|
|
sql_rename_table = "ALTER TABLE %(old_table)s RENAME TO %(new_table)s"
|
2012-08-10 22:03:18 +08:00
|
|
|
sql_retablespace_table = "ALTER TABLE %(table)s SET TABLESPACE %(new_tablespace)s"
|
2012-06-19 00:32:03 +08:00
|
|
|
sql_delete_table = "DROP TABLE %(table)s CASCADE"
|
|
|
|
|
2012-06-19 20:25:22 +08:00
|
|
|
sql_create_column = "ALTER TABLE %(table)s ADD COLUMN %(column)s %(definition)s"
|
|
|
|
sql_alter_column = "ALTER TABLE %(table)s %(changes)s"
|
2012-06-19 00:32:03 +08:00
|
|
|
sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s"
|
|
|
|
sql_alter_column_null = "ALTER COLUMN %(column)s DROP NOT NULL"
|
|
|
|
sql_alter_column_not_null = "ALTER COLUMN %(column)s SET NOT NULL"
|
2012-06-19 20:25:22 +08:00
|
|
|
sql_alter_column_default = "ALTER COLUMN %(column)s SET DEFAULT %(default)s"
|
|
|
|
sql_alter_column_no_default = "ALTER COLUMN %(column)s DROP DEFAULT"
|
|
|
|
sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s CASCADE"
|
|
|
|
sql_rename_column = "ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s"
|
2014-10-07 07:53:21 +08:00
|
|
|
sql_update_with_default = "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL"
|
2012-06-19 00:32:03 +08:00
|
|
|
|
2012-09-08 03:40:59 +08:00
|
|
|
sql_create_check = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)"
|
2012-06-19 00:32:03 +08:00
|
|
|
sql_delete_check = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
|
|
|
|
|
|
|
|
sql_create_unique = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s UNIQUE (%(columns)s)"
|
|
|
|
sql_delete_unique = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
|
|
|
|
|
2014-09-04 20:15:09 +08:00
|
|
|
sql_create_fk = (
|
|
|
|
"ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) "
|
2016-05-06 08:13:32 +08:00
|
|
|
"REFERENCES %(to_table)s (%(to_column)s)%(deferrable)s"
|
2014-09-04 20:15:09 +08:00
|
|
|
)
|
2013-12-29 05:00:16 +08:00
|
|
|
sql_create_inline_fk = None
|
2012-06-19 00:32:03 +08:00
|
|
|
sql_delete_fk = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
|
|
|
|
|
2013-09-07 04:27:51 +08:00
|
|
|
sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s"
|
2012-06-19 00:32:03 +08:00
|
|
|
sql_delete_index = "DROP INDEX %(name)s"
|
|
|
|
|
2012-09-05 00:53:31 +08:00
|
|
|
sql_create_pk = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
|
|
|
|
sql_delete_pk = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s"
|
2012-06-19 00:32:03 +08:00
|
|
|
|
2016-01-31 04:46:28 +08:00
|
|
|
def __init__(self, connection, collect_sql=False, atomic=True):
|
2012-06-19 00:32:03 +08:00
|
|
|
self.connection = connection
|
2013-09-07 04:27:51 +08:00
|
|
|
self.collect_sql = collect_sql
|
|
|
|
if self.collect_sql:
|
|
|
|
self.collected_sql = []
|
2016-01-31 04:46:28 +08:00
|
|
|
self.atomic_migration = self.connection.features.can_rollback_ddl and atomic
|
2012-06-19 00:32:03 +08:00
|
|
|
|
|
|
|
# State-managing methods
|
|
|
|
|
2013-05-18 17:06:30 +08:00
|
|
|
def __enter__(self):
|
2013-05-18 17:48:46 +08:00
|
|
|
self.deferred_sql = []
|
2016-01-31 04:46:28 +08:00
|
|
|
if self.atomic_migration:
|
2014-04-24 03:38:09 +08:00
|
|
|
self.atomic = atomic(self.connection.alias)
|
|
|
|
self.atomic.__enter__()
|
2013-05-18 17:06:30 +08:00
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
|
|
if exc_type is None:
|
2013-05-18 17:48:46 +08:00
|
|
|
for sql in self.deferred_sql:
|
|
|
|
self.execute(sql)
|
2016-01-31 04:46:28 +08:00
|
|
|
if self.atomic_migration:
|
2014-04-24 03:38:09 +08:00
|
|
|
self.atomic.__exit__(exc_type, exc_value, traceback)
|
2012-06-19 00:32:03 +08:00
|
|
|
|
|
|
|
# Core utility functions
|
|
|
|
|
2013-08-10 00:42:56 +08:00
|
|
|
def execute(self, sql, params=[]):
|
2012-06-19 00:32:03 +08:00
|
|
|
"""
|
|
|
|
Executes the given SQL statement, with optional parameters.
|
|
|
|
"""
|
|
|
|
# Log the command we're running, then run it
|
2016-03-14 18:38:38 +08:00
|
|
|
logger.debug("%s; (params %r)", sql, params, extra={'params': params, 'sql': sql})
|
2013-09-07 04:27:51 +08:00
|
|
|
if self.collect_sql:
|
2014-12-01 18:13:01 +08:00
|
|
|
ending = "" if sql.endswith(";") else ";"
|
|
|
|
if params is not None:
|
|
|
|
self.collected_sql.append((sql % tuple(map(self.quote_value, params))) + ending)
|
|
|
|
else:
|
|
|
|
self.collected_sql.append(sql + ending)
|
2013-09-07 04:27:51 +08:00
|
|
|
else:
|
2014-01-09 23:05:15 +08:00
|
|
|
with self.connection.cursor() as cursor:
|
|
|
|
cursor.execute(sql, params)
|
2012-06-19 00:32:03 +08:00
|
|
|
|
|
|
|
def quote_name(self, name):
|
|
|
|
return self.connection.ops.quote_name(name)
|
|
|
|
|
2014-12-31 00:19:59 +08:00
|
|
|
@classmethod
|
|
|
|
def _digest(cls, *args):
|
|
|
|
"""
|
|
|
|
Generates a 32-bit digest of a set of arguments that can be used to
|
|
|
|
shorten identifying names.
|
|
|
|
"""
|
|
|
|
h = hashlib.md5()
|
|
|
|
for arg in args:
|
|
|
|
h.update(force_bytes(arg))
|
|
|
|
return h.hexdigest()[:8]
|
|
|
|
|
2012-06-19 20:25:22 +08:00
|
|
|
# Field <-> database mapping functions
|
|
|
|
|
|
|
|
def column_sql(self, model, field, include_default=False):
|
|
|
|
"""
|
|
|
|
Takes a field and returns its column definition.
|
|
|
|
The field must already have had set_attributes_from_name called.
|
|
|
|
"""
|
|
|
|
# Get the column's type and use that as the basis of the SQL
|
2012-09-08 03:40:59 +08:00
|
|
|
db_params = field.db_parameters(connection=self.connection)
|
|
|
|
sql = db_params['type']
|
2012-06-19 20:25:22 +08:00
|
|
|
params = []
|
|
|
|
# Check for fields that aren't actually columns (e.g. M2M)
|
|
|
|
if sql is None:
|
2013-11-27 20:56:33 +08:00
|
|
|
return None, None
|
2012-06-19 20:25:22 +08:00
|
|
|
# Work out nullability
|
|
|
|
null = field.null
|
2013-08-14 03:54:57 +08:00
|
|
|
# If we were told to include a default value, do so
|
2014-05-18 12:58:16 +08:00
|
|
|
include_default = include_default and not self.skip_default(field)
|
2014-09-15 02:26:16 +08:00
|
|
|
if include_default:
|
|
|
|
default_value = self.effective_default(field)
|
|
|
|
if default_value is not None:
|
|
|
|
if self.connection.features.requires_literal_defaults:
|
|
|
|
# Some databases can't take defaults as a parameter (oracle)
|
|
|
|
# If this is the case, the individual schema backend should
|
|
|
|
# implement prepare_default
|
|
|
|
sql += " DEFAULT %s" % self.prepare_default(default_value)
|
|
|
|
else:
|
|
|
|
sql += " DEFAULT %s"
|
|
|
|
params += [default_value]
|
2012-06-19 20:25:22 +08:00
|
|
|
# Oracle treats the empty string ('') as null, so coerce the null
|
|
|
|
# option whenever '' is a possible value.
|
|
|
|
if (field.empty_strings_allowed and not field.primary_key and
|
|
|
|
self.connection.features.interprets_empty_strings_as_nulls):
|
|
|
|
null = True
|
2014-05-20 20:27:07 +08:00
|
|
|
if null and not self.connection.features.implied_column_null:
|
2012-06-19 20:25:22 +08:00
|
|
|
sql += " NULL"
|
2014-05-20 20:27:07 +08:00
|
|
|
elif not null:
|
2012-06-19 20:25:22 +08:00
|
|
|
sql += " NOT NULL"
|
|
|
|
# Primary key/unique outputs
|
|
|
|
if field.primary_key:
|
|
|
|
sql += " PRIMARY KEY"
|
|
|
|
elif field.unique:
|
|
|
|
sql += " UNIQUE"
|
2013-08-23 21:38:55 +08:00
|
|
|
# Optionally add the tablespace if it's an implicitly indexed column
|
|
|
|
tablespace = field.db_tablespace or model._meta.db_tablespace
|
|
|
|
if tablespace and self.connection.features.supports_tablespaces and field.unique:
|
|
|
|
sql += " %s" % self.connection.ops.tablespace_sql(tablespace, inline=True)
|
2012-06-19 20:25:22 +08:00
|
|
|
# Return the sql
|
|
|
|
return sql, params
|
|
|
|
|
2014-05-18 12:58:16 +08:00
|
|
|
def skip_default(self, field):
|
|
|
|
"""
|
|
|
|
Some backends don't accept default values for certain columns types
|
|
|
|
(i.e. MySQL longtext and longblob).
|
|
|
|
"""
|
|
|
|
return False
|
|
|
|
|
2013-08-23 19:07:55 +08:00
|
|
|
def prepare_default(self, value):
|
|
|
|
"""
|
|
|
|
Only used for backends which have requires_literal_defaults feature
|
|
|
|
"""
|
2014-09-04 20:15:09 +08:00
|
|
|
raise NotImplementedError(
|
|
|
|
'subclasses of BaseDatabaseSchemaEditor for backends which have '
|
|
|
|
'requires_literal_defaults must provide a prepare_default() method'
|
|
|
|
)
|
2013-08-23 19:07:55 +08:00
|
|
|
|
2012-06-19 20:25:22 +08:00
|
|
|
def effective_default(self, field):
|
2012-09-18 17:37:30 +08:00
|
|
|
"""
|
|
|
|
Returns a field's effective database default value
|
|
|
|
"""
|
2012-06-19 20:25:22 +08:00
|
|
|
if field.has_default():
|
|
|
|
default = field.get_default()
|
|
|
|
elif not field.null and field.blank and field.empty_strings_allowed:
|
2014-06-17 09:43:45 +08:00
|
|
|
if field.get_internal_type() == "BinaryField":
|
|
|
|
default = six.binary_type()
|
|
|
|
else:
|
|
|
|
default = six.text_type()
|
2016-04-02 21:49:32 +08:00
|
|
|
elif getattr(field, 'auto_now', False) or getattr(field, 'auto_now_add', False):
|
|
|
|
default = datetime.now()
|
|
|
|
internal_type = field.get_internal_type()
|
|
|
|
if internal_type == 'DateField':
|
|
|
|
default = default.date
|
|
|
|
elif internal_type == 'TimeField':
|
|
|
|
default = default.time
|
|
|
|
elif internal_type == 'DateTimeField':
|
|
|
|
default = timezone.now
|
2012-06-19 20:25:22 +08:00
|
|
|
else:
|
|
|
|
default = None
|
|
|
|
# If it's a callable, call it
|
2016-05-09 06:07:15 +08:00
|
|
|
if callable(default):
|
2012-06-19 20:25:22 +08:00
|
|
|
default = default()
|
2014-05-08 04:46:23 +08:00
|
|
|
# Run it through the field's get_db_prep_save method so we can send it
|
|
|
|
# to the database.
|
|
|
|
default = field.get_db_prep_save(default, self.connection)
|
2012-06-19 20:25:22 +08:00
|
|
|
return default
|
|
|
|
|
2014-02-09 20:41:55 +08:00
|
|
|
def quote_value(self, value):
|
|
|
|
"""
|
|
|
|
Returns a quoted version of the value so it's safe to use in an SQL
|
|
|
|
string. This is not safe against injection from user code; it is
|
|
|
|
intended only for use in making SQL scripts or preparing default values
|
|
|
|
for particularly tricky backends (defaults are not user-defined, though,
|
|
|
|
so this is safe).
|
|
|
|
"""
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
2012-06-19 00:32:03 +08:00
|
|
|
# Actions
|
|
|
|
|
2012-09-22 08:17:08 +08:00
|
|
|
def create_model(self, model):
|
2012-06-19 00:32:03 +08:00
|
|
|
"""
|
|
|
|
Takes a model and creates a table for it in the database.
|
|
|
|
Will also create any accompanying indexes or unique constraints.
|
|
|
|
"""
|
|
|
|
# Create column SQL, add FK deferreds if needed
|
|
|
|
column_sqls = []
|
2012-06-19 20:25:22 +08:00
|
|
|
params = []
|
2012-06-19 00:32:03 +08:00
|
|
|
for field in model._meta.local_fields:
|
|
|
|
# SQL
|
2012-06-19 20:25:22 +08:00
|
|
|
definition, extra_params = self.column_sql(model, field)
|
2012-06-19 00:32:03 +08:00
|
|
|
if definition is None:
|
|
|
|
continue
|
2012-09-08 03:40:59 +08:00
|
|
|
# Check constraints can go on the column SQL here
|
|
|
|
db_params = field.db_parameters(connection=self.connection)
|
|
|
|
if db_params['check']:
|
|
|
|
definition += " CHECK (%s)" % db_params['check']
|
2013-12-28 22:05:56 +08:00
|
|
|
# Autoincrement SQL (for backends with inline variant)
|
|
|
|
col_type_suffix = field.db_type_suffix(connection=self.connection)
|
|
|
|
if col_type_suffix:
|
|
|
|
definition += " %s" % col_type_suffix
|
2012-06-19 20:25:22 +08:00
|
|
|
params.extend(extra_params)
|
2012-06-19 00:32:03 +08:00
|
|
|
# FK
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field and field.db_constraint:
|
|
|
|
to_table = field.remote_field.model._meta.db_table
|
|
|
|
to_column = field.remote_field.model._meta.get_field(field.remote_field.field_name).column
|
2013-12-29 05:00:16 +08:00
|
|
|
if self.connection.features.supports_foreign_keys:
|
2014-09-16 18:46:50 +08:00
|
|
|
self.deferred_sql.append(self._create_fk_sql(model, field, "_fk_%(to_table)s_%(to_column)s"))
|
2013-12-29 05:00:16 +08:00
|
|
|
elif self.sql_create_inline_fk:
|
|
|
|
definition += " " + self.sql_create_inline_fk % {
|
2012-06-19 00:32:03 +08:00
|
|
|
"to_table": self.quote_name(to_table),
|
|
|
|
"to_column": self.quote_name(to_column),
|
|
|
|
}
|
2013-12-29 05:00:16 +08:00
|
|
|
# Add the SQL to our big list
|
|
|
|
column_sqls.append("%s %s" % (
|
|
|
|
self.quote_name(field.column),
|
|
|
|
definition,
|
|
|
|
))
|
2013-12-28 22:05:56 +08:00
|
|
|
# Autoincrement SQL (for backends with post table definition variant)
|
2015-07-02 16:43:15 +08:00
|
|
|
if field.get_internal_type() in ("AutoField", "BigAutoField"):
|
2013-08-14 03:54:57 +08:00
|
|
|
autoinc_sql = self.connection.ops.autoinc_sql(model._meta.db_table, field.column)
|
|
|
|
if autoinc_sql:
|
|
|
|
self.deferred_sql.extend(autoinc_sql)
|
2014-09-15 02:26:16 +08:00
|
|
|
|
2015-03-22 00:38:23 +08:00
|
|
|
# Add any unique_togethers (always deferred, as some fields might be
|
|
|
|
# created afterwards, like geometry fields with some backends)
|
2012-08-10 19:38:18 +08:00
|
|
|
for fields in model._meta.unique_together:
|
2015-01-07 08:16:35 +08:00
|
|
|
columns = [model._meta.get_field(field).column for field in fields]
|
2015-03-22 00:38:23 +08:00
|
|
|
self.deferred_sql.append(self._create_unique_sql(model, columns))
|
2012-06-19 00:32:03 +08:00
|
|
|
# Make the table
|
|
|
|
sql = self.sql_create_table % {
|
2013-12-23 03:44:49 +08:00
|
|
|
"table": self.quote_name(model._meta.db_table),
|
2012-06-19 00:32:03 +08:00
|
|
|
"definition": ", ".join(column_sqls)
|
|
|
|
}
|
2014-09-15 02:26:16 +08:00
|
|
|
if model._meta.db_tablespace:
|
|
|
|
tablespace_sql = self.connection.ops.tablespace_sql(model._meta.db_tablespace)
|
|
|
|
if tablespace_sql:
|
|
|
|
sql += ' ' + tablespace_sql
|
|
|
|
# Prevent using [] as params, in the case a literal '%' is used in the definition
|
|
|
|
self.execute(sql, params or None)
|
2014-12-05 00:56:11 +08:00
|
|
|
|
|
|
|
# Add any field index and index_together's (deferred as SQLite3 _remake_table needs it)
|
|
|
|
self.deferred_sql.extend(self._model_indexes_sql(model))
|
|
|
|
|
2012-09-08 02:39:22 +08:00
|
|
|
# Make M2M tables
|
|
|
|
for field in model._meta.local_many_to_many:
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field.through._meta.auto_created:
|
|
|
|
self.create_model(field.remote_field.through)
|
2012-06-19 00:32:03 +08:00
|
|
|
|
2012-09-22 08:17:08 +08:00
|
|
|
def delete_model(self, model):
|
2012-06-19 00:32:03 +08:00
|
|
|
"""
|
2012-06-19 20:25:22 +08:00
|
|
|
Deletes a model from the database.
|
2012-06-19 00:32:03 +08:00
|
|
|
"""
|
2014-02-18 06:51:40 +08:00
|
|
|
# Handle auto-created intermediary models
|
|
|
|
for field in model._meta.local_many_to_many:
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field.through._meta.auto_created:
|
|
|
|
self.delete_model(field.remote_field.through)
|
2014-02-18 06:51:40 +08:00
|
|
|
|
2012-06-19 20:25:22 +08:00
|
|
|
# Delete the table
|
2012-06-19 00:32:03 +08:00
|
|
|
self.execute(self.sql_delete_table % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
|
|
|
})
|
2012-06-19 20:25:22 +08:00
|
|
|
|
2012-08-10 19:38:18 +08:00
|
|
|
def alter_unique_together(self, model, old_unique_together, new_unique_together):
|
|
|
|
"""
|
|
|
|
Deals with a model changing its unique_together.
|
|
|
|
Note: The input unique_togethers must be doubly-nested, not the single-
|
|
|
|
nested ["foo", "bar"] format.
|
|
|
|
"""
|
2013-07-03 01:02:20 +08:00
|
|
|
olds = set(tuple(fields) for fields in old_unique_together)
|
|
|
|
news = set(tuple(fields) for fields in new_unique_together)
|
2012-08-10 19:38:18 +08:00
|
|
|
# Deleted uniques
|
|
|
|
for fields in olds.difference(news):
|
2015-05-13 23:40:57 +08:00
|
|
|
self._delete_composed_index(model, fields, {'unique': True}, self.sql_delete_unique)
|
2012-08-10 19:38:18 +08:00
|
|
|
# Created uniques
|
|
|
|
for fields in news.difference(olds):
|
2015-01-07 08:16:35 +08:00
|
|
|
columns = [model._meta.get_field(field).column for field in fields]
|
2014-09-16 18:46:50 +08:00
|
|
|
self.execute(self._create_unique_sql(model, columns))
|
2012-08-10 19:38:18 +08:00
|
|
|
|
2013-07-02 18:43:44 +08:00
|
|
|
def alter_index_together(self, model, old_index_together, new_index_together):
|
|
|
|
"""
|
|
|
|
Deals with a model changing its index_together.
|
|
|
|
Note: The input index_togethers must be doubly-nested, not the single-
|
|
|
|
nested ["foo", "bar"] format.
|
|
|
|
"""
|
2013-07-03 01:02:20 +08:00
|
|
|
olds = set(tuple(fields) for fields in old_index_together)
|
|
|
|
news = set(tuple(fields) for fields in new_index_together)
|
2013-07-02 18:43:44 +08:00
|
|
|
# Deleted indexes
|
|
|
|
for fields in olds.difference(news):
|
2015-05-13 23:40:57 +08:00
|
|
|
self._delete_composed_index(model, fields, {'index': True}, self.sql_delete_index)
|
2013-07-02 18:43:44 +08:00
|
|
|
# Created indexes
|
2014-06-20 20:32:11 +08:00
|
|
|
for field_names in news.difference(olds):
|
2015-01-07 08:16:35 +08:00
|
|
|
fields = [model._meta.get_field(field) for field in field_names]
|
2014-06-20 20:32:11 +08:00
|
|
|
self.execute(self._create_index_sql(model, fields, suffix="_idx"))
|
2013-07-02 18:43:44 +08:00
|
|
|
|
2015-05-13 23:40:57 +08:00
|
|
|
def _delete_composed_index(self, model, fields, constraint_kwargs, sql):
|
|
|
|
columns = [model._meta.get_field(field).column for field in fields]
|
|
|
|
constraint_names = self._constraint_names(model, columns, **constraint_kwargs)
|
|
|
|
if len(constraint_names) != 1:
|
|
|
|
raise ValueError("Found wrong number (%s) of constraints for %s(%s)" % (
|
|
|
|
len(constraint_names),
|
|
|
|
model._meta.db_table,
|
|
|
|
", ".join(columns),
|
|
|
|
))
|
|
|
|
self.execute(self._delete_constraint_sql(sql, model, constraint_names[0]))
|
|
|
|
|
2012-08-10 22:03:18 +08:00
|
|
|
def alter_db_table(self, model, old_db_table, new_db_table):
|
|
|
|
"""
|
|
|
|
Renames the table a model points to.
|
|
|
|
"""
|
2016-06-21 12:01:03 +08:00
|
|
|
if (old_db_table == new_db_table or
|
|
|
|
(self.connection.features.ignores_quoted_identifier_case and
|
|
|
|
old_db_table.lower() == new_db_table.lower())):
|
2014-07-21 17:14:00 +08:00
|
|
|
return
|
2012-08-10 22:03:18 +08:00
|
|
|
self.execute(self.sql_rename_table % {
|
|
|
|
"old_table": self.quote_name(old_db_table),
|
|
|
|
"new_table": self.quote_name(new_db_table),
|
|
|
|
})
|
|
|
|
|
|
|
|
def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace):
|
|
|
|
"""
|
|
|
|
Moves a model's table between tablespaces
|
|
|
|
"""
|
2013-08-11 21:27:42 +08:00
|
|
|
self.execute(self.sql_retablespace_table % {
|
2012-08-10 22:03:18 +08:00
|
|
|
"table": self.quote_name(model._meta.db_table),
|
|
|
|
"old_tablespace": self.quote_name(old_db_tablespace),
|
|
|
|
"new_tablespace": self.quote_name(new_db_tablespace),
|
|
|
|
})
|
|
|
|
|
2013-08-11 21:28:55 +08:00
|
|
|
def add_field(self, model, field):
|
2012-06-19 20:25:22 +08:00
|
|
|
"""
|
|
|
|
Creates a field on a model.
|
|
|
|
Usually involves adding a column, but may involve adding a
|
|
|
|
table instead (for M2M fields)
|
|
|
|
"""
|
|
|
|
# Special-case implicit M2M tables
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.many_to_many and field.remote_field.through._meta.auto_created:
|
|
|
|
return self.create_model(field.remote_field.through)
|
2012-06-19 20:25:22 +08:00
|
|
|
# Get the column's definition
|
|
|
|
definition, params = self.column_sql(model, field, include_default=True)
|
|
|
|
# It might not actually have a column behind it
|
|
|
|
if definition is None:
|
|
|
|
return
|
2012-09-08 03:40:59 +08:00
|
|
|
# Check constraints can go on the column SQL here
|
|
|
|
db_params = field.db_parameters(connection=self.connection)
|
|
|
|
if db_params['check']:
|
|
|
|
definition += " CHECK (%s)" % db_params['check']
|
2012-06-19 20:25:22 +08:00
|
|
|
# Build the SQL and run it
|
|
|
|
sql = self.sql_create_column % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
|
|
|
"column": self.quote_name(field.column),
|
|
|
|
"definition": definition,
|
|
|
|
}
|
|
|
|
self.execute(sql, params)
|
|
|
|
# Drop the default if we need to
|
|
|
|
# (Django usually does not use in-database defaults)
|
2014-05-18 12:58:16 +08:00
|
|
|
if not self.skip_default(field) and field.default is not None:
|
2012-06-19 20:25:22 +08:00
|
|
|
sql = self.sql_alter_column % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
|
|
|
"changes": self.sql_alter_column_no_default % {
|
|
|
|
"column": self.quote_name(field.column),
|
|
|
|
}
|
|
|
|
}
|
2012-09-24 19:16:16 +08:00
|
|
|
self.execute(sql)
|
2013-08-14 03:54:57 +08:00
|
|
|
# Add an index, if required
|
|
|
|
if field.db_index and not field.unique:
|
2014-06-20 20:32:11 +08:00
|
|
|
self.deferred_sql.append(self._create_index_sql(model, [field]))
|
2012-06-19 20:25:22 +08:00
|
|
|
# Add any FK constraints later
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field and self.connection.features.supports_foreign_keys and field.db_constraint:
|
2014-09-16 18:46:50 +08:00
|
|
|
self.deferred_sql.append(self._create_fk_sql(model, field, "_fk_%(to_table)s_%(to_column)s"))
|
2013-08-23 19:07:55 +08:00
|
|
|
# Reset connection if required
|
|
|
|
if self.connection.features.connection_persists_old_columns:
|
|
|
|
self.connection.close()
|
2012-06-19 20:25:22 +08:00
|
|
|
|
2013-05-30 00:47:10 +08:00
|
|
|
def remove_field(self, model, field):
|
2012-06-19 20:25:22 +08:00
|
|
|
"""
|
|
|
|
Removes a field from a model. Usually involves deleting a column,
|
|
|
|
but for M2Ms may involve deleting a table.
|
|
|
|
"""
|
|
|
|
# Special-case implicit M2M tables
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.many_to_many and field.remote_field.through._meta.auto_created:
|
|
|
|
return self.delete_model(field.remote_field.through)
|
2012-06-19 20:25:22 +08:00
|
|
|
# It might not actually have a column behind it
|
2012-09-24 19:19:32 +08:00
|
|
|
if field.db_parameters(connection=self.connection)['type'] is None:
|
2012-06-19 20:25:22 +08:00
|
|
|
return
|
2014-04-16 22:55:34 +08:00
|
|
|
# Drop any FK constraints, MySQL requires explicit deletion
|
2015-02-26 22:19:17 +08:00
|
|
|
if field.remote_field:
|
2014-04-16 22:55:34 +08:00
|
|
|
fk_names = self._constraint_names(model, [field.column], foreign_key=True)
|
|
|
|
for fk_name in fk_names:
|
2014-09-16 18:46:50 +08:00
|
|
|
self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
|
2012-06-19 20:25:22 +08:00
|
|
|
# Delete the column
|
|
|
|
sql = self.sql_delete_column % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
|
|
|
"column": self.quote_name(field.column),
|
|
|
|
}
|
|
|
|
self.execute(sql)
|
2013-08-23 19:07:55 +08:00
|
|
|
# Reset connection if required
|
|
|
|
if self.connection.features.connection_persists_old_columns:
|
|
|
|
self.connection.close()
|
2012-06-19 20:25:22 +08:00
|
|
|
|
2012-08-31 06:11:56 +08:00
|
|
|
def alter_field(self, model, old_field, new_field, strict=False):
|
2012-06-19 20:25:22 +08:00
|
|
|
"""
|
|
|
|
Allows a field's type, uniqueness, nullability, default, column,
|
|
|
|
constraints etc. to be modified.
|
|
|
|
Requires a copy of the old field as well so we can only perform
|
|
|
|
changes that are required.
|
2012-08-31 06:11:56 +08:00
|
|
|
If strict is true, raises errors if the old column does not match old_field precisely.
|
2012-06-19 20:25:22 +08:00
|
|
|
"""
|
|
|
|
# Ensure this field is even column-based
|
2012-09-08 03:40:59 +08:00
|
|
|
old_db_params = old_field.db_parameters(connection=self.connection)
|
|
|
|
old_type = old_db_params['type']
|
|
|
|
new_db_params = new_field.db_parameters(connection=self.connection)
|
|
|
|
new_type = new_db_params['type']
|
2015-04-11 22:10:31 +08:00
|
|
|
if ((old_type is None and old_field.remote_field is None) or
|
|
|
|
(new_type is None and new_field.remote_field is None)):
|
2014-09-04 20:15:09 +08:00
|
|
|
raise ValueError(
|
|
|
|
"Cannot alter field %s into %s - they do not properly define "
|
2015-03-17 23:16:50 +08:00
|
|
|
"db_type (are you using a badly-written custom field?)" %
|
|
|
|
(old_field, new_field),
|
2014-09-04 20:15:09 +08:00
|
|
|
)
|
|
|
|
elif old_type is None and new_type is None and (
|
2015-02-26 22:19:17 +08:00
|
|
|
old_field.remote_field.through and new_field.remote_field.through and
|
|
|
|
old_field.remote_field.through._meta.auto_created and
|
|
|
|
new_field.remote_field.through._meta.auto_created):
|
2012-09-08 02:39:22 +08:00
|
|
|
return self._alter_many_to_many(model, old_field, new_field, strict)
|
2014-09-04 20:15:09 +08:00
|
|
|
elif old_type is None and new_type is None and (
|
2015-02-26 22:19:17 +08:00
|
|
|
old_field.remote_field.through and new_field.remote_field.through and
|
|
|
|
not old_field.remote_field.through._meta.auto_created and
|
|
|
|
not new_field.remote_field.through._meta.auto_created):
|
2014-05-09 01:33:59 +08:00
|
|
|
# Both sides have through models; this is a no-op.
|
|
|
|
return
|
2012-06-19 20:25:22 +08:00
|
|
|
elif old_type is None or new_type is None:
|
2014-09-04 20:15:09 +08:00
|
|
|
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)" % (old_field, new_field)
|
|
|
|
)
|
2014-05-20 23:25:59 +08:00
|
|
|
|
2014-09-04 20:15:09 +08:00
|
|
|
self._alter_field(model, old_field, new_field, old_type, new_type,
|
|
|
|
old_db_params, new_db_params, strict)
|
2014-05-20 23:25:59 +08:00
|
|
|
|
2014-09-04 20:15:09 +08:00
|
|
|
def _alter_field(self, model, old_field, new_field, old_type, new_type,
|
|
|
|
old_db_params, new_db_params, strict=False):
|
2014-05-20 23:25:59 +08:00
|
|
|
"""Actually perform a "physical" (non-ManyToMany) field update."""
|
|
|
|
|
2012-09-08 01:31:05 +08:00
|
|
|
# Drop any FK constraints, we'll remake them later
|
2014-08-04 09:58:44 +08:00
|
|
|
fks_dropped = set()
|
2015-02-26 22:19:17 +08:00
|
|
|
if old_field.remote_field and old_field.db_constraint:
|
2012-09-08 01:31:05 +08:00
|
|
|
fk_names = self._constraint_names(model, [old_field.column], foreign_key=True)
|
|
|
|
if strict and len(fk_names) != 1:
|
|
|
|
raise ValueError("Found wrong number (%s) of foreign key constraints for %s.%s" % (
|
|
|
|
len(fk_names),
|
|
|
|
model._meta.db_table,
|
|
|
|
old_field.column,
|
|
|
|
))
|
|
|
|
for fk_name in fk_names:
|
2014-08-04 09:58:44 +08:00
|
|
|
fks_dropped.add((old_field.column,))
|
2014-09-16 18:46:50 +08:00
|
|
|
self.execute(self._delete_constraint_sql(self.sql_delete_fk, model, fk_name))
|
2015-01-19 22:31:23 +08:00
|
|
|
# Has unique been removed?
|
|
|
|
if old_field.unique and (not new_field.unique or (not old_field.primary_key and new_field.primary_key)):
|
|
|
|
# Find the unique constraint for this field
|
|
|
|
constraint_names = self._constraint_names(model, [old_field.column], unique=True)
|
|
|
|
if strict and len(constraint_names) != 1:
|
|
|
|
raise ValueError("Found wrong number (%s) of unique constraints for %s.%s" % (
|
|
|
|
len(constraint_names),
|
|
|
|
model._meta.db_table,
|
|
|
|
old_field.column,
|
|
|
|
))
|
|
|
|
for constraint_name in constraint_names:
|
|
|
|
self.execute(self._delete_constraint_sql(self.sql_delete_unique, model, constraint_name))
|
2013-12-11 22:19:05 +08:00
|
|
|
# Drop incoming FK constraints if we're a primary key and things are going
|
|
|
|
# to change.
|
|
|
|
if old_field.primary_key and new_field.primary_key and old_type != new_type:
|
2015-01-07 08:16:35 +08:00
|
|
|
# '_meta.related_field' also contains M2M reverse fields, these
|
|
|
|
# will be filtered out
|
2015-04-11 22:10:31 +08:00
|
|
|
for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field):
|
|
|
|
rel_fk_names = self._constraint_names(
|
|
|
|
new_rel.related_model, [new_rel.field.column], foreign_key=True
|
|
|
|
)
|
2013-12-11 22:19:05 +08:00
|
|
|
for fk_name in rel_fk_names:
|
2015-04-11 22:10:31 +08:00
|
|
|
self.execute(self._delete_constraint_sql(self.sql_delete_fk, new_rel.related_model, fk_name))
|
2014-12-05 00:56:11 +08:00
|
|
|
# Removed an index? (no strict check, as multiple indexes are possible)
|
2014-09-04 20:15:09 +08:00
|
|
|
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)):
|
2014-08-07 09:59:11 +08:00
|
|
|
# Find the index for this field
|
|
|
|
index_names = self._constraint_names(model, [old_field.column], index=True)
|
|
|
|
for index_name in index_names:
|
2014-09-16 18:46:50 +08:00
|
|
|
self.execute(self._delete_constraint_sql(self.sql_delete_index, model, index_name))
|
2012-09-08 03:40:59 +08:00
|
|
|
# Change check constraints?
|
|
|
|
if old_db_params['check'] != new_db_params['check'] and old_db_params['check']:
|
|
|
|
constraint_names = self._constraint_names(model, [old_field.column], check=True)
|
|
|
|
if strict and len(constraint_names) != 1:
|
|
|
|
raise ValueError("Found wrong number (%s) of check constraints for %s.%s" % (
|
|
|
|
len(constraint_names),
|
|
|
|
model._meta.db_table,
|
|
|
|
old_field.column,
|
|
|
|
))
|
|
|
|
for constraint_name in constraint_names:
|
2014-09-16 18:46:50 +08:00
|
|
|
self.execute(self._delete_constraint_sql(self.sql_delete_check, model, constraint_name))
|
2012-08-02 22:08:39 +08:00
|
|
|
# Have they renamed the column?
|
2012-06-19 20:25:22 +08:00
|
|
|
if old_field.column != new_field.column:
|
2015-05-27 06:18:21 +08:00
|
|
|
self.execute(self._rename_field_sql(model._meta.db_table, old_field, new_field, new_type))
|
2012-06-19 20:25:22 +08:00
|
|
|
# Next, start accumulating actions to do
|
|
|
|
actions = []
|
2014-10-07 07:53:21 +08:00
|
|
|
null_actions = []
|
2013-12-11 22:19:05 +08:00
|
|
|
post_actions = []
|
2012-06-19 20:25:22 +08:00
|
|
|
# Type change?
|
|
|
|
if old_type != new_type:
|
2015-04-11 22:10:31 +08:00
|
|
|
fragment, other_actions = self._alter_column_type_sql(
|
|
|
|
model._meta.db_table, old_field, new_field, new_type
|
|
|
|
)
|
2013-12-11 22:19:05 +08:00
|
|
|
actions.append(fragment)
|
|
|
|
post_actions.extend(other_actions)
|
2014-10-07 07:53:21 +08:00
|
|
|
# When changing a column NULL constraint to NOT NULL with a given
|
|
|
|
# default value, we need to perform 4 steps:
|
|
|
|
# 1. Add a default for new incoming writes
|
|
|
|
# 2. Update existing NULL rows with new default
|
|
|
|
# 3. Replace NULL constraint with NOT NULL
|
|
|
|
# 4. Drop the default again.
|
2012-06-19 20:25:22 +08:00
|
|
|
# Default change?
|
|
|
|
old_default = self.effective_default(old_field)
|
|
|
|
new_default = self.effective_default(new_field)
|
2014-12-30 05:23:18 +08:00
|
|
|
needs_database_default = (
|
|
|
|
old_default != new_default and
|
|
|
|
new_default is not None and
|
|
|
|
not self.skip_default(new_field)
|
|
|
|
)
|
|
|
|
if needs_database_default:
|
|
|
|
if self.connection.features.requires_literal_defaults:
|
|
|
|
# Some databases can't take defaults as a parameter (oracle)
|
|
|
|
# If this is the case, the individual schema backend should
|
|
|
|
# implement prepare_default
|
2012-06-19 20:25:22 +08:00
|
|
|
actions.append((
|
2014-12-30 05:23:18 +08:00
|
|
|
self.sql_alter_column_default % {
|
2012-06-19 20:25:22 +08:00
|
|
|
"column": self.quote_name(new_field.column),
|
2016-03-19 06:06:43 +08:00
|
|
|
"type": new_type,
|
2014-12-30 05:23:18 +08:00
|
|
|
"default": self.prepare_default(new_default),
|
2012-06-19 20:25:22 +08:00
|
|
|
},
|
|
|
|
[],
|
|
|
|
))
|
|
|
|
else:
|
2014-12-30 05:23:18 +08:00
|
|
|
actions.append((
|
|
|
|
self.sql_alter_column_default % {
|
|
|
|
"column": self.quote_name(new_field.column),
|
2016-03-19 06:06:43 +08:00
|
|
|
"type": new_type,
|
2014-12-30 05:23:18 +08:00
|
|
|
"default": "%s",
|
|
|
|
},
|
|
|
|
[new_default],
|
|
|
|
))
|
2012-06-19 20:25:22 +08:00
|
|
|
# Nullability change?
|
|
|
|
if old_field.null != new_field.null:
|
2015-02-18 06:50:45 +08:00
|
|
|
if (self.connection.features.interprets_empty_strings_as_nulls and
|
|
|
|
new_field.get_internal_type() in ("CharField", "TextField")):
|
|
|
|
# The field is nullable in the database anyway, leave it alone
|
|
|
|
pass
|
|
|
|
elif new_field.null:
|
2014-10-07 07:53:21 +08:00
|
|
|
null_actions.append((
|
2012-06-19 20:25:22 +08:00
|
|
|
self.sql_alter_column_null % {
|
|
|
|
"column": self.quote_name(new_field.column),
|
2012-08-18 20:48:54 +08:00
|
|
|
"type": new_type,
|
2012-06-19 20:25:22 +08:00
|
|
|
},
|
|
|
|
[],
|
|
|
|
))
|
|
|
|
else:
|
2014-10-07 07:53:21 +08:00
|
|
|
null_actions.append((
|
2012-09-24 19:53:37 +08:00
|
|
|
self.sql_alter_column_not_null % {
|
2012-06-19 20:25:22 +08:00
|
|
|
"column": self.quote_name(new_field.column),
|
2012-08-18 20:48:54 +08:00
|
|
|
"type": new_type,
|
2012-06-19 20:25:22 +08:00
|
|
|
},
|
|
|
|
[],
|
|
|
|
))
|
2014-10-07 07:53:21 +08:00
|
|
|
# Only if we have a default and there is a change from NULL to NOT NULL
|
|
|
|
four_way_default_alteration = (
|
|
|
|
new_field.has_default() and
|
|
|
|
(old_field.null and not new_field.null)
|
|
|
|
)
|
|
|
|
if actions or null_actions:
|
|
|
|
if not four_way_default_alteration:
|
|
|
|
# If we don't have to do a 4-way default alteration we can
|
|
|
|
# directly run a (NOT) NULL alteration
|
|
|
|
actions = actions + null_actions
|
2012-08-02 22:08:39 +08:00
|
|
|
# Combine actions together if we can (e.g. postgres)
|
2014-10-31 21:08:24 +08:00
|
|
|
if self.connection.features.supports_combined_alters and actions:
|
2012-08-02 22:08:39 +08:00
|
|
|
sql, params = tuple(zip(*actions))
|
2014-11-13 07:06:12 +08:00
|
|
|
actions = [(", ".join(sql), sum(params, []))]
|
2012-08-02 22:08:39 +08:00
|
|
|
# Apply those actions
|
|
|
|
for sql, params in actions:
|
|
|
|
self.execute(
|
|
|
|
self.sql_alter_column % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
|
|
|
"changes": sql,
|
|
|
|
},
|
|
|
|
params,
|
|
|
|
)
|
2014-10-07 07:53:21 +08:00
|
|
|
if four_way_default_alteration:
|
|
|
|
# Update existing rows with default value
|
|
|
|
self.execute(
|
|
|
|
self.sql_update_with_default % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
|
|
|
"column": self.quote_name(new_field.column),
|
|
|
|
"default": "%s",
|
|
|
|
},
|
|
|
|
[new_default],
|
|
|
|
)
|
|
|
|
# Since we didn't run a NOT NULL change before we need to do it
|
|
|
|
# now
|
|
|
|
for sql, params in null_actions:
|
|
|
|
self.execute(
|
|
|
|
self.sql_alter_column % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
|
|
|
"changes": sql,
|
|
|
|
},
|
|
|
|
params,
|
|
|
|
)
|
2013-12-11 22:19:05 +08:00
|
|
|
if post_actions:
|
|
|
|
for sql, params in post_actions:
|
|
|
|
self.execute(sql, params)
|
2012-08-02 22:08:39 +08:00
|
|
|
# Added a unique?
|
2015-06-02 07:27:28 +08:00
|
|
|
if (not old_field.unique and new_field.unique) or (
|
|
|
|
old_field.primary_key and not new_field.primary_key and new_field.unique
|
|
|
|
):
|
2014-09-16 18:46:50 +08:00
|
|
|
self.execute(self._create_unique_sql(model, [new_field.column]))
|
2012-08-31 06:11:56 +08:00
|
|
|
# Added an index?
|
2014-09-04 20:15:09 +08:00
|
|
|
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)):
|
2014-06-20 20:32:11 +08:00
|
|
|
self.execute(self._create_index_sql(model, [new_field], suffix="_uniq"))
|
2013-12-11 21:16:29 +08:00
|
|
|
# Type alteration on primary key? Then we need to alter the column
|
|
|
|
# referring to us.
|
|
|
|
rels_to_update = []
|
|
|
|
if old_field.primary_key and new_field.primary_key and old_type != new_type:
|
2015-04-11 22:10:31 +08:00
|
|
|
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
|
2012-09-05 00:53:31 +08:00
|
|
|
# Changed to become primary key?
|
|
|
|
# Note that we don't detect unsetting of a PK, as we assume another field
|
|
|
|
# will always come along and replace it.
|
|
|
|
if not old_field.primary_key and new_field.primary_key:
|
|
|
|
# First, drop the old PK
|
|
|
|
constraint_names = self._constraint_names(model, primary_key=True)
|
|
|
|
if strict and len(constraint_names) != 1:
|
|
|
|
raise ValueError("Found wrong number (%s) of PK constraints for %s" % (
|
|
|
|
len(constraint_names),
|
|
|
|
model._meta.db_table,
|
|
|
|
))
|
|
|
|
for constraint_name in constraint_names:
|
2014-09-16 18:46:50 +08:00
|
|
|
self.execute(self._delete_constraint_sql(self.sql_delete_pk, model, constraint_name))
|
2012-09-05 00:53:31 +08:00
|
|
|
# Make the new one
|
|
|
|
self.execute(
|
|
|
|
self.sql_create_pk % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
2014-09-17 01:37:18 +08:00
|
|
|
"name": self.quote_name(self._create_index_name(model, [new_field.column], suffix="_pk")),
|
2012-09-05 00:53:31 +08:00
|
|
|
"columns": self.quote_name(new_field.column),
|
|
|
|
}
|
|
|
|
)
|
2013-12-11 21:16:29 +08:00
|
|
|
# Update all referencing columns
|
2015-04-11 22:10:31 +08:00
|
|
|
rels_to_update.extend(_related_non_m2m_objects(old_field, new_field))
|
2013-12-11 22:19:05 +08:00
|
|
|
# Handle our type alters on the other end of rels from the PK stuff above
|
2015-04-11 22:10:31 +08:00
|
|
|
for old_rel, new_rel in rels_to_update:
|
|
|
|
rel_db_params = new_rel.field.db_parameters(connection=self.connection)
|
2013-12-11 21:16:29 +08:00
|
|
|
rel_type = rel_db_params['type']
|
2015-04-11 22:10:31 +08:00
|
|
|
fragment, other_actions = self._alter_column_type_sql(
|
|
|
|
new_rel.related_model._meta.db_table, old_rel.field, new_rel.field, rel_type
|
|
|
|
)
|
2013-12-11 21:16:29 +08:00
|
|
|
self.execute(
|
|
|
|
self.sql_alter_column % {
|
2015-04-11 22:10:31 +08:00
|
|
|
"table": self.quote_name(new_rel.related_model._meta.db_table),
|
|
|
|
"changes": fragment[0],
|
|
|
|
},
|
|
|
|
fragment[1],
|
2013-12-11 21:16:29 +08:00
|
|
|
)
|
2015-04-11 22:10:31 +08:00
|
|
|
for sql, params in other_actions:
|
|
|
|
self.execute(sql, params)
|
2012-09-08 01:31:05 +08:00
|
|
|
# Does it have a foreign key?
|
2015-02-26 22:19:17 +08:00
|
|
|
if (new_field.remote_field and
|
|
|
|
(fks_dropped or not old_field.remote_field or not old_field.db_constraint) and
|
2015-03-05 20:41:15 +08:00
|
|
|
new_field.db_constraint):
|
2014-09-16 18:46:50 +08:00
|
|
|
self.execute(self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s"))
|
2013-12-11 22:19:05 +08:00
|
|
|
# Rebuild FKs that pointed to us if we previously had to drop them
|
|
|
|
if old_field.primary_key and new_field.primary_key and old_type != new_type:
|
2015-01-07 08:16:35 +08:00
|
|
|
for rel in new_field.model._meta.related_objects:
|
|
|
|
if not rel.many_to_many:
|
|
|
|
self.execute(self._create_fk_sql(rel.related_model, rel.field, "_fk"))
|
2012-09-08 03:40:59 +08:00
|
|
|
# Does it have check constraints we need to add?
|
|
|
|
if old_db_params['check'] != new_db_params['check'] and new_db_params['check']:
|
|
|
|
self.execute(
|
|
|
|
self.sql_create_check % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
2014-09-17 01:37:18 +08:00
|
|
|
"name": self.quote_name(self._create_index_name(model, [new_field.column], suffix="_check")),
|
2012-09-08 03:40:59 +08:00
|
|
|
"column": self.quote_name(new_field.column),
|
|
|
|
"check": new_db_params['check'],
|
|
|
|
}
|
|
|
|
)
|
2014-07-21 17:03:51 +08:00
|
|
|
# Drop the default if we need to
|
|
|
|
# (Django usually does not use in-database defaults)
|
2014-12-30 05:23:18 +08:00
|
|
|
if needs_database_default:
|
2014-07-21 17:03:51 +08:00
|
|
|
sql = self.sql_alter_column % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
|
|
|
"changes": self.sql_alter_column_no_default % {
|
|
|
|
"column": self.quote_name(new_field.column),
|
2016-03-19 06:06:43 +08:00
|
|
|
"type": new_type,
|
2014-07-21 17:03:51 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
self.execute(sql)
|
2013-08-23 19:07:55 +08:00
|
|
|
# Reset connection if required
|
|
|
|
if self.connection.features.connection_persists_old_columns:
|
|
|
|
self.connection.close()
|
2012-08-02 22:08:39 +08:00
|
|
|
|
2015-04-11 22:10:31 +08:00
|
|
|
def _alter_column_type_sql(self, table, old_field, new_field, new_type):
|
2013-12-11 22:19:05 +08:00
|
|
|
"""
|
2014-03-02 22:25:53 +08:00
|
|
|
Hook to specialize column type alteration for different backends,
|
2013-12-11 22:19:05 +08:00
|
|
|
for cases when a creation type is different to an alteration type
|
|
|
|
(e.g. SERIAL in PostgreSQL, PostGIS fields).
|
|
|
|
|
|
|
|
Should return two things; an SQL fragment of (sql, params) to insert
|
|
|
|
into an ALTER TABLE statement, and a list of extra (sql, params) tuples
|
|
|
|
to run once the field is altered.
|
|
|
|
"""
|
|
|
|
return (
|
|
|
|
(
|
|
|
|
self.sql_alter_column_type % {
|
2015-04-11 22:10:31 +08:00
|
|
|
"column": self.quote_name(new_field.column),
|
|
|
|
"type": new_type,
|
2013-12-11 22:19:05 +08:00
|
|
|
},
|
|
|
|
[],
|
|
|
|
),
|
|
|
|
[],
|
|
|
|
)
|
|
|
|
|
2012-09-08 02:39:22 +08:00
|
|
|
def _alter_many_to_many(self, model, old_field, new_field, strict):
|
2012-09-18 17:37:30 +08:00
|
|
|
"""
|
|
|
|
Alters M2Ms to repoint their to= endpoints.
|
|
|
|
"""
|
2012-09-08 02:39:22 +08:00
|
|
|
# Rename the through table
|
2015-02-26 22:19:17 +08:00
|
|
|
if old_field.remote_field.through._meta.db_table != new_field.remote_field.through._meta.db_table:
|
|
|
|
self.alter_db_table(old_field.remote_field.through, old_field.remote_field.through._meta.db_table,
|
|
|
|
new_field.remote_field.through._meta.db_table)
|
2012-09-08 02:39:22 +08:00
|
|
|
# Repoint the FK to the other side
|
|
|
|
self.alter_field(
|
2015-02-26 22:19:17 +08:00
|
|
|
new_field.remote_field.through,
|
2012-09-24 20:17:38 +08:00
|
|
|
# We need the field that points to the target model, so we can tell alter_field to change it -
|
|
|
|
# this is m2m_reverse_field_name() (as opposed to m2m_field_name, which points to our model)
|
2015-02-26 22:19:17 +08:00
|
|
|
old_field.remote_field.through._meta.get_field(old_field.m2m_reverse_field_name()),
|
|
|
|
new_field.remote_field.through._meta.get_field(new_field.m2m_reverse_field_name()),
|
2012-09-08 02:39:22 +08:00
|
|
|
)
|
2014-09-17 13:34:10 +08:00
|
|
|
self.alter_field(
|
2015-02-26 22:19:17 +08:00
|
|
|
new_field.remote_field.through,
|
2014-09-17 13:34:10 +08:00
|
|
|
# for self-referential models we need to alter field from the other end too
|
2015-02-26 22:19:17 +08:00
|
|
|
old_field.remote_field.through._meta.get_field(old_field.m2m_field_name()),
|
|
|
|
new_field.remote_field.through._meta.get_field(new_field.m2m_field_name()),
|
2014-09-17 13:34:10 +08:00
|
|
|
)
|
2012-09-08 02:39:22 +08:00
|
|
|
|
2012-08-02 22:08:39 +08:00
|
|
|
def _create_index_name(self, model, column_names, suffix=""):
|
2012-09-18 17:37:30 +08:00
|
|
|
"""
|
|
|
|
Generates a unique name for an index/unique constraint.
|
|
|
|
"""
|
2012-08-02 22:08:39 +08:00
|
|
|
# If there is just one column in the index, use a default algorithm from Django
|
|
|
|
if len(column_names) == 1 and not suffix:
|
|
|
|
return truncate_name(
|
2014-12-31 00:19:59 +08:00
|
|
|
'%s_%s' % (model._meta.db_table, self._digest(column_names[0])),
|
2012-08-02 22:08:39 +08:00
|
|
|
self.connection.ops.max_name_length()
|
|
|
|
)
|
2012-09-24 20:18:14 +08:00
|
|
|
# Else generate the name for the index using a different algorithm
|
2012-08-02 22:08:39 +08:00
|
|
|
table_name = model._meta.db_table.replace('"', '').replace('.', '_')
|
2015-03-03 01:48:30 +08:00
|
|
|
index_unique_name = '_%s' % self._digest(table_name, *column_names)
|
2014-02-09 20:33:52 +08:00
|
|
|
max_length = self.connection.ops.max_name_length() or 200
|
2012-08-02 22:08:39 +08:00
|
|
|
# If the index name is too long, truncate it
|
2014-09-04 20:15:09 +08:00
|
|
|
index_name = ('%s_%s%s%s' % (
|
|
|
|
table_name, column_names[0], index_unique_name, suffix,
|
|
|
|
)).replace('"', '').replace('.', '_')
|
2014-02-09 20:33:52 +08:00
|
|
|
if len(index_name) > max_length:
|
2012-08-02 22:08:39 +08:00
|
|
|
part = ('_%s%s%s' % (column_names[0], index_unique_name, suffix))
|
2014-02-09 20:33:52 +08:00
|
|
|
index_name = '%s%s' % (table_name[:(max_length - len(part))], part)
|
2013-08-14 03:54:57 +08:00
|
|
|
# It shouldn't start with an underscore (Oracle hates this)
|
|
|
|
if index_name[0] == "_":
|
|
|
|
index_name = index_name[1:]
|
2012-09-24 20:23:25 +08:00
|
|
|
# If it's STILL too long, just hash it down
|
2014-02-09 20:33:52 +08:00
|
|
|
if len(index_name) > max_length:
|
|
|
|
index_name = hashlib.md5(force_bytes(index_name)).hexdigest()[:max_length]
|
2013-08-14 03:54:57 +08:00
|
|
|
# It can't start with a number on Oracle, so prepend D if we need to
|
|
|
|
if index_name[0].isdigit():
|
|
|
|
index_name = "D%s" % index_name[:-1]
|
2012-08-02 22:08:39 +08:00
|
|
|
return index_name
|
|
|
|
|
2014-12-05 00:56:11 +08:00
|
|
|
def _create_index_sql(self, model, fields, suffix="", sql=None):
|
|
|
|
"""
|
|
|
|
Return the SQL statement to create the index for one or several fields.
|
|
|
|
`sql` can be specified if the syntax differs from the standard (GIS
|
|
|
|
indexes, ...).
|
|
|
|
"""
|
|
|
|
if len(fields) == 1 and fields[0].db_tablespace:
|
|
|
|
tablespace_sql = self.connection.ops.tablespace_sql(fields[0].db_tablespace)
|
|
|
|
elif model._meta.db_tablespace:
|
|
|
|
tablespace_sql = self.connection.ops.tablespace_sql(model._meta.db_tablespace)
|
|
|
|
else:
|
|
|
|
tablespace_sql = ""
|
|
|
|
if tablespace_sql:
|
|
|
|
tablespace_sql = " " + tablespace_sql
|
|
|
|
|
2014-06-20 20:32:11 +08:00
|
|
|
columns = [field.column for field in fields]
|
2014-12-05 00:56:11 +08:00
|
|
|
sql_create_index = sql or self.sql_create_index
|
|
|
|
return sql_create_index % {
|
2014-06-20 20:32:11 +08:00
|
|
|
"table": self.quote_name(model._meta.db_table),
|
2014-09-17 01:37:18 +08:00
|
|
|
"name": self.quote_name(self._create_index_name(model, columns, suffix=suffix)),
|
2014-06-20 20:32:11 +08:00
|
|
|
"columns": ", ".join(self.quote_name(column) for column in columns),
|
2014-12-05 00:56:11 +08:00
|
|
|
"extra": tablespace_sql,
|
2014-06-20 20:32:11 +08:00
|
|
|
}
|
|
|
|
|
2014-12-05 00:56:11 +08:00
|
|
|
def _model_indexes_sql(self, model):
|
|
|
|
"""
|
|
|
|
Return all index SQL statements (field indexes, index_together) for the
|
|
|
|
specified model, as a list.
|
|
|
|
"""
|
|
|
|
if not model._meta.managed or model._meta.proxy or model._meta.swapped:
|
|
|
|
return []
|
|
|
|
output = []
|
|
|
|
for field in model._meta.local_fields:
|
|
|
|
if field.db_index and not field.unique:
|
|
|
|
output.append(self._create_index_sql(model, [field], suffix=""))
|
|
|
|
|
|
|
|
for field_names in model._meta.index_together:
|
2015-01-07 08:16:35 +08:00
|
|
|
fields = [model._meta.get_field(field) for field in field_names]
|
2014-12-05 00:56:11 +08:00
|
|
|
output.append(self._create_index_sql(model, fields, suffix="_idx"))
|
|
|
|
return output
|
|
|
|
|
2015-05-27 06:18:21 +08:00
|
|
|
def _rename_field_sql(self, table, old_field, new_field, new_type):
|
|
|
|
return self.sql_rename_column % {
|
|
|
|
"table": self.quote_name(table),
|
|
|
|
"old_column": self.quote_name(old_field.column),
|
|
|
|
"new_column": self.quote_name(new_field.column),
|
|
|
|
"type": new_type,
|
|
|
|
}
|
|
|
|
|
2014-09-16 18:46:50 +08:00
|
|
|
def _create_fk_sql(self, model, field, suffix):
|
|
|
|
from_table = model._meta.db_table
|
|
|
|
from_column = field.column
|
2015-02-26 22:19:17 +08:00
|
|
|
to_table = field.target_field.model._meta.db_table
|
|
|
|
to_column = field.target_field.column
|
2014-09-16 18:46:50 +08:00
|
|
|
suffix = suffix % {
|
|
|
|
"to_table": to_table,
|
|
|
|
"to_column": to_column,
|
|
|
|
}
|
|
|
|
|
|
|
|
return self.sql_create_fk % {
|
|
|
|
"table": self.quote_name(from_table),
|
2014-09-17 01:37:18 +08:00
|
|
|
"name": self.quote_name(self._create_index_name(model, [from_column], suffix=suffix)),
|
2014-09-16 18:46:50 +08:00
|
|
|
"column": self.quote_name(from_column),
|
|
|
|
"to_table": self.quote_name(to_table),
|
|
|
|
"to_column": self.quote_name(to_column),
|
2016-05-06 08:13:32 +08:00
|
|
|
"deferrable": self.connection.ops.deferrable_sql(),
|
2014-09-16 18:46:50 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
def _create_unique_sql(self, model, columns):
|
|
|
|
return self.sql_create_unique % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
2014-09-17 01:37:18 +08:00
|
|
|
"name": self.quote_name(self._create_index_name(model, columns, suffix="_uniq")),
|
2014-09-16 18:46:50 +08:00
|
|
|
"columns": ", ".join(self.quote_name(column) for column in columns),
|
|
|
|
}
|
|
|
|
|
|
|
|
def _delete_constraint_sql(self, template, model, name):
|
|
|
|
return template % {
|
|
|
|
"table": self.quote_name(model._meta.db_table),
|
2014-09-17 01:37:18 +08:00
|
|
|
"name": self.quote_name(name),
|
2014-09-16 18:46:50 +08:00
|
|
|
}
|
|
|
|
|
2014-09-04 20:15:09 +08:00
|
|
|
def _constraint_names(self, model, column_names=None, unique=None,
|
|
|
|
primary_key=None, index=None, foreign_key=None,
|
|
|
|
check=None):
|
2012-09-18 17:37:30 +08:00
|
|
|
"""
|
|
|
|
Returns all constraint names matching the columns and conditions
|
|
|
|
"""
|
2013-07-03 01:02:20 +08:00
|
|
|
column_names = list(column_names) if column_names else None
|
2014-01-09 23:05:15 +08:00
|
|
|
with self.connection.cursor() as cursor:
|
|
|
|
constraints = self.connection.introspection.get_constraints(cursor, model._meta.db_table)
|
2012-08-02 22:08:39 +08:00
|
|
|
result = []
|
|
|
|
for name, infodict in constraints.items():
|
2012-09-05 00:53:31 +08:00
|
|
|
if column_names is None or column_names == infodict['columns']:
|
2012-08-02 22:08:39 +08:00
|
|
|
if unique is not None and infodict['unique'] != unique:
|
|
|
|
continue
|
2012-09-05 00:53:31 +08:00
|
|
|
if primary_key is not None and infodict['primary_key'] != primary_key:
|
2012-08-02 22:08:39 +08:00
|
|
|
continue
|
2012-08-31 06:11:56 +08:00
|
|
|
if index is not None and infodict['index'] != index:
|
|
|
|
continue
|
2012-09-08 03:40:59 +08:00
|
|
|
if check is not None and infodict['check'] != check:
|
|
|
|
continue
|
2012-09-08 01:31:05 +08:00
|
|
|
if foreign_key is not None and not infodict['foreign_key']:
|
|
|
|
continue
|
2012-08-02 22:08:39 +08:00
|
|
|
result.append(name)
|
|
|
|
return result
|