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.

schema.py 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import copy
  2. import datetime
  3. import re
  4. from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  5. from django.db.utils import DatabaseError
  6. class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
  7. sql_create_column = "ALTER TABLE %(table)s ADD %(column)s %(definition)s"
  8. sql_alter_column_type = "MODIFY %(column)s %(type)s"
  9. sql_alter_column_null = "MODIFY %(column)s NULL"
  10. sql_alter_column_not_null = "MODIFY %(column)s NOT NULL"
  11. sql_alter_column_default = "MODIFY %(column)s DEFAULT %(default)s"
  12. sql_alter_column_no_default = "MODIFY %(column)s DEFAULT NULL"
  13. sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s"
  14. sql_delete_table = "DROP TABLE %(table)s CASCADE CONSTRAINTS"
  15. sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s"
  16. def quote_value(self, value):
  17. if isinstance(value, (datetime.date, datetime.time, datetime.datetime)):
  18. return "'%s'" % value
  19. elif isinstance(value, str):
  20. return "'%s'" % value.replace("\'", "\'\'").replace('%', '%%')
  21. elif isinstance(value, (bytes, bytearray, memoryview)):
  22. return "'%s'" % value.hex()
  23. elif isinstance(value, bool):
  24. return "1" if value else "0"
  25. else:
  26. return str(value)
  27. def remove_field(self, model, field):
  28. # If the column is an identity column, drop the identity before
  29. # removing the field.
  30. if self._is_identity_column(model._meta.db_table, field.column):
  31. self._drop_identity(model._meta.db_table, field.column)
  32. super().remove_field(model, field)
  33. def delete_model(self, model):
  34. # Run superclass action
  35. super().delete_model(model)
  36. # Clean up manually created sequence.
  37. self.execute("""
  38. DECLARE
  39. i INTEGER;
  40. BEGIN
  41. SELECT COUNT(1) INTO i FROM USER_SEQUENCES
  42. WHERE SEQUENCE_NAME = '%(sq_name)s';
  43. IF i = 1 THEN
  44. EXECUTE IMMEDIATE 'DROP SEQUENCE "%(sq_name)s"';
  45. END IF;
  46. END;
  47. /""" % {'sq_name': self.connection.ops._get_no_autofield_sequence_name(model._meta.db_table)})
  48. def alter_field(self, model, old_field, new_field, strict=False):
  49. try:
  50. super().alter_field(model, old_field, new_field, strict)
  51. except DatabaseError as e:
  52. description = str(e)
  53. # If we're changing type to an unsupported type we need a
  54. # SQLite-ish workaround
  55. if 'ORA-22858' in description or 'ORA-22859' in description:
  56. self._alter_field_type_workaround(model, old_field, new_field)
  57. # If an identity column is changing to a non-numeric type, drop the
  58. # identity first.
  59. elif 'ORA-30675' in description:
  60. self._drop_identity(model._meta.db_table, old_field.column)
  61. self.alter_field(model, old_field, new_field, strict)
  62. # If a primary key column is changing to an identity column, drop
  63. # the primary key first.
  64. elif 'ORA-30673' in description and old_field.primary_key:
  65. self._delete_primary_key(model, strict=True)
  66. self._alter_field_type_workaround(model, old_field, new_field)
  67. else:
  68. raise
  69. def _alter_field_type_workaround(self, model, old_field, new_field):
  70. """
  71. Oracle refuses to change from some type to other type.
  72. What we need to do instead is:
  73. - Add a nullable version of the desired field with a temporary name. If
  74. the new column is an auto field, then the temporary column can't be
  75. nullable.
  76. - Update the table to transfer values from old to new
  77. - Drop old column
  78. - Rename the new column and possibly drop the nullable property
  79. """
  80. # Make a new field that's like the new one but with a temporary
  81. # column name.
  82. new_temp_field = copy.deepcopy(new_field)
  83. new_temp_field.null = (new_field.get_internal_type() not in ('AutoField', 'BigAutoField'))
  84. new_temp_field.column = self._generate_temp_name(new_field.column)
  85. # Add it
  86. self.add_field(model, new_temp_field)
  87. # Explicit data type conversion
  88. # https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf
  89. # /Data-Type-Comparison-Rules.html#GUID-D0C5A47E-6F93-4C2D-9E49-4F2B86B359DD
  90. new_value = self.quote_name(old_field.column)
  91. old_type = old_field.db_type(self.connection)
  92. if re.match('^N?CLOB', old_type):
  93. new_value = "TO_CHAR(%s)" % new_value
  94. old_type = 'VARCHAR2'
  95. if re.match('^N?VARCHAR2', old_type):
  96. new_internal_type = new_field.get_internal_type()
  97. if new_internal_type == 'DateField':
  98. new_value = "TO_DATE(%s, 'YYYY-MM-DD')" % new_value
  99. elif new_internal_type == 'DateTimeField':
  100. new_value = "TO_TIMESTAMP(%s, 'YYYY-MM-DD HH24:MI:SS.FF')" % new_value
  101. elif new_internal_type == 'TimeField':
  102. # TimeField are stored as TIMESTAMP with a 1900-01-01 date part.
  103. new_value = "TO_TIMESTAMP(CONCAT('1900-01-01 ', %s), 'YYYY-MM-DD HH24:MI:SS.FF')" % new_value
  104. # Transfer values across
  105. self.execute("UPDATE %s set %s=%s" % (
  106. self.quote_name(model._meta.db_table),
  107. self.quote_name(new_temp_field.column),
  108. new_value,
  109. ))
  110. # Drop the old field
  111. self.remove_field(model, old_field)
  112. # Rename and possibly make the new field NOT NULL
  113. super().alter_field(model, new_temp_field, new_field)
  114. def normalize_name(self, name):
  115. """
  116. Get the properly shortened and uppercased identifier as returned by
  117. quote_name() but without the quotes.
  118. """
  119. nn = self.quote_name(name)
  120. if nn[0] == '"' and nn[-1] == '"':
  121. nn = nn[1:-1]
  122. return nn
  123. def _generate_temp_name(self, for_name):
  124. """Generate temporary names for workarounds that need temp columns."""
  125. suffix = hex(hash(for_name)).upper()[1:]
  126. return self.normalize_name(for_name + "_" + suffix)
  127. def prepare_default(self, value):
  128. return self.quote_value(value)
  129. def _field_should_be_indexed(self, model, field):
  130. create_index = super()._field_should_be_indexed(model, field)
  131. db_type = field.db_type(self.connection)
  132. if db_type is not None and db_type.lower() in self.connection._limited_data_types:
  133. return False
  134. return create_index
  135. def _unique_should_be_added(self, old_field, new_field):
  136. return (
  137. super()._unique_should_be_added(old_field, new_field) and
  138. not self._field_became_primary_key(old_field, new_field)
  139. )
  140. def _is_identity_column(self, table_name, column_name):
  141. with self.connection.cursor() as cursor:
  142. cursor.execute("""
  143. SELECT
  144. CASE WHEN identity_column = 'YES' THEN 1 ELSE 0 END
  145. FROM user_tab_cols
  146. WHERE table_name = %s AND
  147. column_name = %s
  148. """, [self.normalize_name(table_name), self.normalize_name(column_name)])
  149. row = cursor.fetchone()
  150. return row[0] if row else False
  151. def _drop_identity(self, table_name, column_name):
  152. self.execute('ALTER TABLE %(table)s MODIFY %(column)s DROP IDENTITY' % {
  153. 'table': self.quote_name(table_name),
  154. 'column': self.quote_name(column_name),
  155. })