pgutils.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from django.db.migrations.operations import RunSQL
  2. class CreatePartialIndex(RunSQL):
  3. CREATE_SQL = """
  4. CREATE INDEX %(index_name)s ON %(table)s (%(field)s)
  5. WHERE %(condition)s;
  6. """
  7. REMOVE_SQL = """
  8. DROP INDEX %(index_name)s
  9. """
  10. def __init__(self, field, index_name, condition):
  11. self.model, self.field = field.split('.')
  12. self.index_name = index_name
  13. self.condition = condition
  14. @property
  15. def reversible(self):
  16. return True
  17. def state_forwards(self, app_label, state):
  18. pass
  19. def database_forwards(self, app_label, schema_editor,
  20. from_state, to_state):
  21. apps = from_state.render()
  22. model = apps.get_model(app_label, self.model)
  23. statement = self.CREATE_SQL % {
  24. 'index_name': self.index_name,
  25. 'table': model._meta.db_table,
  26. 'field': self.field,
  27. 'condition': self.condition,
  28. }
  29. schema_editor.execute(statement)
  30. def database_backwards(self, app_label, schema_editor,
  31. from_state, to_state):
  32. schema_editor.execute(
  33. self.REMOVE_SQL % {'index_name': self.index_name})
  34. def describe(self):
  35. message = "Create PostgreSQL partial index on field %s in %s for %s"
  36. formats = (self.field, self.model_name, self.values)
  37. return message % formats