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