pgutils.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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, from_state, to_state):
  20. apps = from_state.render()
  21. model = apps.get_model(app_label, self.model)
  22. statement = self.CREATE_SQL % {
  23. 'index_name': self.index_name,
  24. 'table': model._meta.db_table,
  25. 'field': self.field,
  26. 'condition': self.condition,
  27. }
  28. schema_editor.execute(statement)
  29. def database_backwards(self, app_label, schema_editor, from_state, to_state):
  30. schema_editor.execute(self.REMOVE_SQL % {'index_name': self.index_name})
  31. def describe(self):
  32. return "Create PostgreSQL partial index on field %s in %s for %s" % (self.field, self.model_name, self.values)