| 1 |
from django.contrib.postgres.signals import ( |
| 2 |
get_citext_oids, |
| 3 |
get_hstore_oids, |
| 4 |
register_type_handlers, |
| 5 |
) |
| 6 |
from django.db import NotSupportedError, router |
| 7 |
from django.db.migrations import AddConstraint, AddIndex, RemoveIndex |
| 8 |
from django.db.migrations.operations.base import Operation, OperationCategory |
| 9 |
from django.db.models.constraints import CheckConstraint |
| 10 |
|
| 11 |
|
| 12 |
class CreateExtension(Operation): |
| 13 |
reversible = True |
| 14 |
category = OperationCategory.ADDITION |
| 15 |
|
| 16 |
def __init__(self, name): |
| 17 |
self.name = name |
| 18 |
|
| 19 |
def state_forwards(self, app_label, state): |
| 20 |
pass |
| 21 |
|
| 22 |
def database_forwards(self, app_label, schema_editor, from_state, to_state): |
| 23 |
if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate( |
| 24 |
schema_editor.connection.alias, app_label |
| 25 |
): |
| 26 |
return |
| 27 |
if not self.extension_exists(schema_editor, self.name): |
| 28 |
schema_editor.execute( |
| 29 |
"CREATE EXTENSION IF NOT EXISTS %s" |
| 30 |
% schema_editor.quote_name(self.name) |
| 31 |
) |
| 32 |
# Clear cached, stale oids. |
| 33 |
get_hstore_oids.cache_clear() |
| 34 |
get_citext_oids.cache_clear() |
| 35 |
# Registering new type handlers cannot be done before the extension is |
| 36 |
# installed, otherwise a subsequent data migration would use the same |
| 37 |
# connection. |
| 38 |
register_type_handlers(schema_editor.connection) |
| 39 |
if hasattr(schema_editor.connection, "register_geometry_adapters"): |
| 40 |
schema_editor.connection.register_geometry_adapters( |
| 41 |
schema_editor.connection.connection, True |
| 42 |
) |
| 43 |
|
| 44 |
def database_backwards(self, app_label, schema_editor, from_state, to_state): |
| 45 |
if not router.allow_migrate(schema_editor.connection.alias, app_label): |
| 46 |
return |
| 47 |
if self.extension_exists(schema_editor, self.name): |
| 48 |
schema_editor.execute( |
| 49 |
"DROP EXTENSION IF EXISTS %s" % schema_editor.quote_name(self.name) |
| 50 |
) |
| 51 |
# Clear cached, stale oids. |
| 52 |
get_hstore_oids.cache_clear() |
| 53 |
get_citext_oids.cache_clear() |
| 54 |
|
| 55 |
def extension_exists(self, schema_editor, extension): |
| 56 |
with schema_editor.connection.cursor() as cursor: |
| 57 |
cursor.execute( |
| 58 |
"SELECT 1 FROM pg_extension WHERE extname = %s", |
| 59 |
[extension], |
| 60 |
) |
| 61 |
return bool(cursor.fetchone()) |
| 62 |
|
| 63 |
def describe(self): |
| 64 |
return "Creates extension %s" % self.name |
| 65 |
|
| 66 |
@property |
| 67 |
def migration_name_fragment(self): |
| 68 |
return "create_extension_%s" % self.name |
| 69 |
|
| 70 |
|
| 71 |
class BloomExtension(CreateExtension): |
| 72 |
def __init__(self): |
| 73 |
self.name = "bloom" |
| 74 |
|
| 75 |
|
| 76 |
class BtreeGinExtension(CreateExtension): |
| 77 |
def __init__(self): |
| 78 |
self.name = "btree_gin" |
| 79 |
|
| 80 |
|
| 81 |
class BtreeGistExtension(CreateExtension): |
| 82 |
def __init__(self): |
| 83 |
self.name = "btree_gist" |
| 84 |
|
| 85 |
|
| 86 |
class CITextExtension(CreateExtension): |
| 87 |
def __init__(self): |
| 88 |
self.name = "citext" |
| 89 |
|
| 90 |
|
| 91 |
class CryptoExtension(CreateExtension): |
| 92 |
def __init__(self): |
| 93 |
self.name = "pgcrypto" |
| 94 |
|
| 95 |
|
| 96 |
class HStoreExtension(CreateExtension): |
| 97 |
def __init__(self): |
| 98 |
self.name = "hstore" |
| 99 |
|
| 100 |
|
| 101 |
class TrigramExtension(CreateExtension): |
| 102 |
def __init__(self): |
| 103 |
self.name = "pg_trgm" |
| 104 |
|
| 105 |
|
| 106 |
class UnaccentExtension(CreateExtension): |
| 107 |
def __init__(self): |
| 108 |
self.name = "unaccent" |
| 109 |
|
| 110 |
|
| 111 |
class NotInTransactionMixin: |
| 112 |
def _ensure_not_in_transaction(self, schema_editor): |
| 113 |
if schema_editor.connection.in_atomic_block: |
| 114 |
raise NotSupportedError( |
| 115 |
"The %s operation cannot be executed inside a transaction " |
| 116 |
"(set atomic = False on the migration)." % self.__class__.__name__ |
| 117 |
) |
| 118 |
|
| 119 |
|
| 120 |
class AddIndexConcurrently(NotInTransactionMixin, AddIndex): |
| 121 |
"""Create an index using PostgreSQL's CREATE INDEX CONCURRENTLY syntax.""" |
| 122 |
|
| 123 |
atomic = False |
| 124 |
category = OperationCategory.ADDITION |
| 125 |
|
| 126 |
def describe(self): |
| 127 |
return "Concurrently create index %s on field(s) %s of model %s" % ( |
| 128 |
self.index.name, |
| 129 |
", ".join(self.index.fields), |
| 130 |
self.model_name, |
| 131 |
) |
| 132 |
|
| 133 |
def database_forwards(self, app_label, schema_editor, from_state, to_state): |
| 134 |
self._ensure_not_in_transaction(schema_editor) |
| 135 |
model = to_state.apps.get_model(app_label, self.model_name) |
| 136 |
if self.allow_migrate_model(schema_editor.connection.alias, model): |
| 137 |
schema_editor.add_index(model, self.index, concurrently=True) |
| 138 |
|
| 139 |
def database_backwards(self, app_label, schema_editor, from_state, to_state): |
| 140 |
self._ensure_not_in_transaction(schema_editor) |
| 141 |
model = from_state.apps.get_model(app_label, self.model_name) |
| 142 |
if self.allow_migrate_model(schema_editor.connection.alias, model): |
| 143 |
schema_editor.remove_index(model, self.index, concurrently=True) |
| 144 |
|
| 145 |
|
| 146 |
class RemoveIndexConcurrently(NotInTransactionMixin, RemoveIndex): |
| 147 |
"""Remove an index using PostgreSQL's DROP INDEX CONCURRENTLY syntax.""" |
| 148 |
|
| 149 |
atomic = False |
| 150 |
category = OperationCategory.REMOVAL |
| 151 |
|
| 152 |
def describe(self): |
| 153 |
return "Concurrently remove index %s from %s" % (self.name, self.model_name) |
| 154 |
|
| 155 |
def database_forwards(self, app_label, schema_editor, from_state, to_state): |
| 156 |
self._ensure_not_in_transaction(schema_editor) |
| 157 |
model = from_state.apps.get_model(app_label, self.model_name) |
| 158 |
if self.allow_migrate_model(schema_editor.connection.alias, model): |
| 159 |
from_model_state = from_state.models[app_label, self.model_name_lower] |
| 160 |
index = from_model_state.get_index_by_name(self.name) |
| 161 |
schema_editor.remove_index(model, index, concurrently=True) |
| 162 |
|
| 163 |
def database_backwards(self, app_label, schema_editor, from_state, to_state): |
| 164 |
self._ensure_not_in_transaction(schema_editor) |
| 165 |
model = to_state.apps.get_model(app_label, self.model_name) |
| 166 |
if self.allow_migrate_model(schema_editor.connection.alias, model): |
| 167 |
to_model_state = to_state.models[app_label, self.model_name_lower] |
| 168 |
index = to_model_state.get_index_by_name(self.name) |
| 169 |
schema_editor.add_index(model, index, concurrently=True) |
| 170 |
|
| 171 |
|
| 172 |
class CollationOperation(Operation): |
| 173 |
def __init__(self, name, locale, *, provider="libc", deterministic=True): |
| 174 |
self.name = name |
| 175 |
self.locale = locale |
| 176 |
self.provider = provider |
| 177 |
self.deterministic = deterministic |
| 178 |
|
| 179 |
def state_forwards(self, app_label, state): |
| 180 |
pass |
| 181 |
|
| 182 |
def deconstruct(self): |
| 183 |
kwargs = {"name": self.name, "locale": self.locale} |
| 184 |
if self.provider and self.provider != "libc": |
| 185 |
kwargs["provider"] = self.provider |
| 186 |
if self.deterministic is False: |
| 187 |
kwargs["deterministic"] = self.deterministic |
| 188 |
return ( |
| 189 |
self.__class__.__qualname__, |
| 190 |
[], |
| 191 |
kwargs, |
| 192 |
) |
| 193 |
|
| 194 |
def create_collation(self, schema_editor): |
| 195 |
args = {"locale": schema_editor.quote_name(self.locale)} |
| 196 |
if self.provider != "libc": |
| 197 |
args["provider"] = schema_editor.quote_name(self.provider) |
| 198 |
if self.deterministic is False: |
| 199 |
args["deterministic"] = "false" |
| 200 |
schema_editor.execute( |
| 201 |
"CREATE COLLATION %(name)s (%(args)s)" |
| 202 |
% { |
| 203 |
"name": schema_editor.quote_name(self.name), |
| 204 |
"args": ", ".join( |
| 205 |
f"{option}={value}" for option, value in args.items() |
| 206 |
), |
| 207 |
} |
| 208 |
) |
| 209 |
|
| 210 |
def remove_collation(self, schema_editor): |
| 211 |
schema_editor.execute( |
| 212 |
"DROP COLLATION %s" % schema_editor.quote_name(self.name), |
| 213 |
) |
| 214 |
|
| 215 |
|
| 216 |
class CreateCollation(CollationOperation): |
| 217 |
"""Create a collation.""" |
| 218 |
|
| 219 |
category = OperationCategory.ADDITION |
| 220 |
|
| 221 |
def database_forwards(self, app_label, schema_editor, from_state, to_state): |
| 222 |
if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate( |
| 223 |
schema_editor.connection.alias, app_label |
| 224 |
): |
| 225 |
return |
| 226 |
self.create_collation(schema_editor) |
| 227 |
|
| 228 |
def database_backwards(self, app_label, schema_editor, from_state, to_state): |
| 229 |
if not router.allow_migrate(schema_editor.connection.alias, app_label): |
| 230 |
return |
| 231 |
self.remove_collation(schema_editor) |
| 232 |
|
| 233 |
def describe(self): |
| 234 |
return f"Create collation {self.name}" |
| 235 |
|
| 236 |
@property |
| 237 |
def migration_name_fragment(self): |
| 238 |
return "create_collation_%s" % self.name.lower() |
| 239 |
|
| 240 |
def reduce(self, operation, app_label): |
| 241 |
if isinstance(operation, RemoveCollation) and self.name == operation.name: |
| 242 |
return [] |
| 243 |
return super().reduce(operation, app_label) |
| 244 |
|
| 245 |
|
| 246 |
class RemoveCollation(CollationOperation): |
| 247 |
"""Remove a collation.""" |
| 248 |
|
| 249 |
category = OperationCategory.REMOVAL |
| 250 |
|
| 251 |
def database_forwards(self, app_label, schema_editor, from_state, to_state): |
| 252 |
if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate( |
| 253 |
schema_editor.connection.alias, app_label |
| 254 |
): |
| 255 |
return |
| 256 |
self.remove_collation(schema_editor) |
| 257 |
|
| 258 |
def database_backwards(self, app_label, schema_editor, from_state, to_state): |
| 259 |
if not router.allow_migrate(schema_editor.connection.alias, app_label): |
| 260 |
return |
| 261 |
self.create_collation(schema_editor) |
| 262 |
|
| 263 |
def describe(self): |
| 264 |
return f"Remove collation {self.name}" |
| 265 |
|
| 266 |
@property |
| 267 |
def migration_name_fragment(self): |
| 268 |
return "remove_collation_%s" % self.name.lower() |
| 269 |
|
| 270 |
|
| 271 |
class AddConstraintNotValid(AddConstraint): |
| 272 |
""" |
| 273 |
Add a table constraint without enforcing validation, using PostgreSQL's |
| 274 |
NOT VALID syntax. |
| 275 |
""" |
| 276 |
|
| 277 |
category = OperationCategory.ADDITION |
| 278 |
|
| 279 |
def __init__(self, model_name, constraint): |
| 280 |
if not isinstance(constraint, CheckConstraint): |
| 281 |
raise TypeError( |
| 282 |
"AddConstraintNotValid.constraint must be a check constraint." |
| 283 |
) |
| 284 |
super().__init__(model_name, constraint) |
| 285 |
|
| 286 |
def describe(self): |
| 287 |
return "Create not valid constraint %s on model %s" % ( |
| 288 |
self.constraint.name, |
| 289 |
self.model_name, |
| 290 |
) |
| 291 |
|
| 292 |
def database_forwards(self, app_label, schema_editor, from_state, to_state): |
| 293 |
model = from_state.apps.get_model(app_label, self.model_name) |
| 294 |
if self.allow_migrate_model(schema_editor.connection.alias, model): |
| 295 |
constraint_sql = self.constraint.create_sql(model, schema_editor) |
| 296 |
if constraint_sql: |
| 297 |
# Constraint.create_sql returns interpolated SQL which makes |
| 298 |
# params=None a necessity to avoid escaping attempts on |
| 299 |
# execution. |
| 300 |
schema_editor.execute(str(constraint_sql) + " NOT VALID", params=None) |
| 301 |
|
| 302 |
@property |
| 303 |
def migration_name_fragment(self): |
| 304 |
return super().migration_name_fragment + "_not_valid" |
| 305 |
|
| 306 |
|
| 307 |
class ValidateConstraint(Operation): |
| 308 |
"""Validate a table NOT VALID constraint.""" |
| 309 |
|
| 310 |
category = OperationCategory.ALTERATION |
| 311 |
|
| 312 |
def __init__(self, model_name, name): |
| 313 |
self.model_name = model_name |
| 314 |
self.name = name |
| 315 |
|
| 316 |
def describe(self): |
| 317 |
return "Validate constraint %s on model %s" % (self.name, self.model_name) |
| 318 |
|
| 319 |
def database_forwards(self, app_label, schema_editor, from_state, to_state): |
| 320 |
model = from_state.apps.get_model(app_label, self.model_name) |
| 321 |
if self.allow_migrate_model(schema_editor.connection.alias, model): |
| 322 |
schema_editor.execute( |
| 323 |
"ALTER TABLE %s VALIDATE CONSTRAINT %s" |
| 324 |
% ( |
| 325 |
schema_editor.quote_name(model._meta.db_table), |
| 326 |
schema_editor.quote_name(self.name), |
| 327 |
) |
| 328 |
) |
| 329 |
|
| 330 |
def database_backwards(self, app_label, schema_editor, from_state, to_state): |
| 331 |
# PostgreSQL does not provide a way to make a constraint invalid. |
| 332 |
pass |
| 333 |
|
| 334 |
def state_forwards(self, app_label, state): |
| 335 |
pass |
| 336 |
|
| 337 |
@property |
| 338 |
def migration_name_fragment(self): |
| 339 |
return "%s_validate_%s" % (self.model_name.lower(), self.name.lower()) |
| 340 |
|
| 341 |
def deconstruct(self): |
| 342 |
return ( |
| 343 |
self.__class__.__name__, |
| 344 |
[], |
| 345 |
{ |
| 346 |
"model_name": self.model_name, |
| 347 |
"name": self.name, |
| 348 |
}, |
| 349 |
) |