add_hash_partition.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from psqlextra.backend.migrations.state import PostgresHashPartitionState
  2. from .partition import PostgresPartitionOperation
  3. class PostgresAddHashPartition(PostgresPartitionOperation):
  4. """Adds a new hash partition to a :see:PartitionedPostgresModel.
  5. Each partition will hold the rows for which the hash value of the
  6. partition key divided by the specified modulus will produce the
  7. specified remainder.
  8. """
  9. def __init__(
  10. self, model_name: str, name: str, modulus: int, remainder: int
  11. ):
  12. """Initializes new instance of :see:AddHashPartition.
  13. Arguments:
  14. model_name:
  15. The name of the :see:PartitionedPostgresModel.
  16. name:
  17. The name to give to the new partition table.
  18. modulus:
  19. Integer value by which the key is divided.
  20. remainder:
  21. The remainder of the hash value when divided by modulus.
  22. """
  23. super().__init__(model_name, name)
  24. self.modulus = modulus
  25. self.remainder = remainder
  26. def state_forwards(self, app_label, state):
  27. model = state.models[(app_label, self.model_name_lower)]
  28. model.add_partition(
  29. PostgresHashPartitionState(
  30. app_label=app_label,
  31. model_name=self.model_name,
  32. name=self.name,
  33. modulus=self.modulus,
  34. remainder=self.remainder,
  35. )
  36. )
  37. state.reload_model(app_label, self.model_name_lower)
  38. def database_forwards(self, app_label, schema_editor, from_state, to_state):
  39. model = to_state.apps.get_model(app_label, self.model_name)
  40. if self.allow_migrate_model(schema_editor.connection.alias, model):
  41. schema_editor.add_hash_partition(
  42. model, self.name, self.modulus, self.remainder
  43. )
  44. def database_backwards(
  45. self, app_label, schema_editor, from_state, to_state
  46. ):
  47. model = from_state.apps.get_model(app_label, self.model_name)
  48. if self.allow_migrate_model(schema_editor.connection.alias, model):
  49. schema_editor.delete_partition(model, self.name)
  50. def deconstruct(self):
  51. name, args, kwargs = super().deconstruct()
  52. kwargs["modulus"] = self.modulus
  53. kwargs["remainder"] = self.remainder
  54. return name, args, kwargs
  55. def describe(self) -> str:
  56. return "Creates hash partition %s on %s" % (self.name, self.model_name)