1from plain.models.backends.base.schema import BaseDatabaseSchemaEditor
2from plain.models.constants import LOOKUP_SEP
3from plain.models.fields import NOT_PROVIDED, F, UniqueConstraint
4
5
6class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
7 sql_rename_table = "RENAME TABLE %(old_table)s TO %(new_table)s"
8
9 sql_alter_column_null = "MODIFY %(column)s %(type)s NULL"
10 sql_alter_column_not_null = "MODIFY %(column)s %(type)s NOT NULL"
11 sql_alter_column_type = "MODIFY %(column)s %(type)s%(collation)s%(comment)s"
12 sql_alter_column_no_default_null = "ALTER COLUMN %(column)s SET DEFAULT NULL"
13
14 # No 'CASCADE' which works as a no-op in MySQL but is undocumented
15 sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s"
16
17 sql_delete_unique = "ALTER TABLE %(table)s DROP INDEX %(name)s"
18 sql_create_column_inline_fk = (
19 ", ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) "
20 "REFERENCES %(to_table)s(%(to_column)s)"
21 )
22 sql_delete_fk = "ALTER TABLE %(table)s DROP FOREIGN KEY %(name)s"
23
24 sql_delete_index = "DROP INDEX %(name)s ON %(table)s"
25 sql_rename_index = "ALTER TABLE %(table)s RENAME INDEX %(old_name)s TO %(new_name)s"
26
27 sql_create_pk = (
28 "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)"
29 )
30 sql_delete_pk = "ALTER TABLE %(table)s DROP PRIMARY KEY"
31
32 sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s"
33
34 sql_alter_table_comment = "ALTER TABLE %(table)s COMMENT = %(comment)s"
35 sql_alter_column_comment = None
36
37 @property
38 def sql_delete_check(self):
39 if self.connection.mysql_is_mariadb:
40 # The name of the column check constraint is the same as the field
41 # name on MariaDB. Adding IF EXISTS clause prevents migrations
42 # crash. Constraint is removed during a "MODIFY" column statement.
43 return "ALTER TABLE %(table)s DROP CONSTRAINT IF EXISTS %(name)s"
44 return "ALTER TABLE %(table)s DROP CHECK %(name)s"
45
46 @property
47 def sql_rename_column(self):
48 # MariaDB >= 10.5.2 and MySQL >= 8.0.4 support an
49 # "ALTER TABLE ... RENAME COLUMN" statement.
50 if self.connection.mysql_is_mariadb:
51 if self.connection.mysql_version >= (10, 5, 2):
52 return super().sql_rename_column
53 elif self.connection.mysql_version >= (8, 0, 4):
54 return super().sql_rename_column
55 return "ALTER TABLE %(table)s CHANGE %(old_column)s %(new_column)s %(type)s"
56
57 def quote_value(self, value):
58 self.connection.ensure_connection()
59 if isinstance(value, str):
60 value = value.replace("%", "%%")
61 # MySQLdb escapes to string, PyMySQL to bytes.
62 quoted = self.connection.connection.escape(
63 value, self.connection.connection.encoders
64 )
65 if isinstance(value, str) and isinstance(quoted, bytes):
66 quoted = quoted.decode()
67 return quoted
68
69 def _is_limited_data_type(self, field):
70 db_type = field.db_type(self.connection)
71 return (
72 db_type is not None
73 and db_type.lower() in self.connection._limited_data_types
74 )
75
76 def skip_default(self, field):
77 if not self._supports_limited_data_type_defaults:
78 return self._is_limited_data_type(field)
79 return False
80
81 def skip_default_on_alter(self, field):
82 if self._is_limited_data_type(field) and not self.connection.mysql_is_mariadb:
83 # MySQL doesn't support defaults for BLOB and TEXT in the
84 # ALTER COLUMN statement.
85 return True
86 return False
87
88 @property
89 def _supports_limited_data_type_defaults(self):
90 # MariaDB and MySQL >= 8.0.13 support defaults for BLOB and TEXT.
91 if self.connection.mysql_is_mariadb:
92 return True
93 return self.connection.mysql_version >= (8, 0, 13)
94
95 def _column_default_sql(self, field):
96 if (
97 not self.connection.mysql_is_mariadb
98 and self._supports_limited_data_type_defaults
99 and self._is_limited_data_type(field)
100 ):
101 # MySQL supports defaults for BLOB and TEXT columns only if the
102 # default value is written as an expression i.e. in parentheses.
103 return "(%s)"
104 return super()._column_default_sql(field)
105
106 def add_field(self, model, field):
107 super().add_field(model, field)
108
109 # Simulate the effect of a one-off default.
110 # field.default may be unhashable, so a set isn't used for "in" check.
111 if self.skip_default(field) and field.default not in (None, NOT_PROVIDED):
112 effective_default = self.effective_default(field)
113 self.execute(
114 f"UPDATE {self.quote_name(model._meta.db_table)} SET {self.quote_name(field.column)} = %s",
115 [effective_default],
116 )
117
118 def remove_constraint(self, model, constraint):
119 if (
120 isinstance(constraint, UniqueConstraint)
121 and constraint.create_sql(model, self) is not None
122 ):
123 self._create_missing_fk_index(
124 model,
125 fields=constraint.fields,
126 expressions=constraint.expressions,
127 )
128 super().remove_constraint(model, constraint)
129
130 def remove_index(self, model, index):
131 self._create_missing_fk_index(
132 model,
133 fields=[field_name for field_name, _ in index.fields_orders],
134 expressions=index.expressions,
135 )
136 super().remove_index(model, index)
137
138 def _field_should_be_indexed(self, model, field):
139 if not super()._field_should_be_indexed(model, field):
140 return False
141
142 storage = self.connection.introspection.get_storage_engine(
143 self.connection.cursor(), model._meta.db_table
144 )
145 # No need to create an index for ForeignKey fields except if
146 # db_constraint=False because the index from that constraint won't be
147 # created.
148 if (
149 storage == "InnoDB"
150 and field.get_internal_type() == "ForeignKey"
151 and field.db_constraint
152 ):
153 return False
154 return not self._is_limited_data_type(field)
155
156 def _create_missing_fk_index(
157 self,
158 model,
159 *,
160 fields,
161 expressions=None,
162 ):
163 """
164 MySQL can remove an implicit FK index on a field when that field is
165 covered by another index. "covered" here means
166 that the more complex index has the FK field as its first field (see
167 https://bugs.mysql.com/bug.php?id=37910).
168
169 Manually create an implicit FK index to make it possible to remove the
170 composed index.
171 """
172 first_field_name = None
173 if fields:
174 first_field_name = fields[0]
175 elif (
176 expressions
177 and self.connection.features.supports_expression_indexes
178 and isinstance(expressions[0], F)
179 and LOOKUP_SEP not in expressions[0].name
180 ):
181 first_field_name = expressions[0].name
182
183 if not first_field_name:
184 return
185
186 first_field = model._meta.get_field(first_field_name)
187 if first_field.get_internal_type() == "ForeignKey":
188 column = self.connection.introspection.identifier_converter(
189 first_field.column
190 )
191 with self.connection.cursor() as cursor:
192 constraint_names = [
193 name
194 for name, infodict in self.connection.introspection.get_constraints(
195 cursor, model._meta.db_table
196 ).items()
197 if infodict["index"] and infodict["columns"][0] == column
198 ]
199 # There are no other indexes that starts with the FK field, only
200 # the index that is expected to be deleted.
201 if len(constraint_names) == 1:
202 self.execute(
203 self._create_index_sql(model, fields=[first_field], suffix="")
204 )
205
206 def _set_field_new_type_null_status(self, field, new_type):
207 """
208 Keep the null property of the old field. If it has changed, it will be
209 handled separately.
210 """
211 if field.allow_null:
212 new_type += " NULL"
213 else:
214 new_type += " NOT NULL"
215 return new_type
216
217 def _alter_column_type_sql(
218 self, model, old_field, new_field, new_type, old_collation, new_collation
219 ):
220 new_type = self._set_field_new_type_null_status(old_field, new_type)
221 return super()._alter_column_type_sql(
222 model, old_field, new_field, new_type, old_collation, new_collation
223 )
224
225 def _field_db_check(self, field, field_db_params):
226 if self.connection.mysql_is_mariadb and self.connection.mysql_version >= (
227 10,
228 5,
229 2,
230 ):
231 return super()._field_db_check(field, field_db_params)
232 # On MySQL and MariaDB < 10.5.2 (no support for
233 # "ALTER TABLE ... RENAME COLUMN" statements), check constraints with
234 # the column name as it requires explicit recreation when the column is
235 # renamed.
236 return field_db_params["check"]
237
238 def _rename_field_sql(self, table, old_field, new_field, new_type):
239 new_type = self._set_field_new_type_null_status(old_field, new_type)
240 return super()._rename_field_sql(table, old_field, new_field, new_type)
241
242 def _alter_column_comment_sql(self, model, new_field, new_type, new_db_comment):
243 # Comment is alter when altering the column type.
244 return "", []
245
246 def _comment_sql(self, comment):
247 comment_sql = super()._comment_sql(comment)
248 return f" COMMENT {comment_sql}"