Skip to content

Commit 791790e

Browse files
committed
Decompose migration operations into individual sql functions
1 parent fb0efe3 commit 791790e

File tree

1 file changed

+27
-14
lines changed

1 file changed

+27
-14
lines changed

postgres_composite_types/operations.py

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,26 @@
55
__all__ = ["BaseOperation"]
66

77

8+
def sql_field_definition(field_name, field, schema_editor):
9+
quoted_name = schema_editor.quote_name(field_name)
10+
db_type = field.db_type(schema_editor.connection)
11+
return f"{quoted_name} {db_type}"
12+
13+
14+
def sql_create_type(type_name, fields, schema_editor):
15+
fields_list = ", ".join(
16+
sql_field_definition(field_name, field, schema_editor)
17+
for field_name, field in fields
18+
)
19+
quoted_name = schema_editor.quote_name(type_name)
20+
return f"CREATE TYPE {quoted_name} AS ({fields_list})"
21+
22+
23+
def sql_drop_type(type_name, schema_editor):
24+
quoted_name = schema_editor.quote_name(type_name)
25+
return f"DROP TYPE {quoted_name}"
26+
27+
828
class BaseOperation(Operation):
929
"""Base class for the DB operation that relates to this type."""
1030

@@ -18,20 +38,13 @@ def describe(self):
1838
return f"Creates type {self.Meta.db_type}"
1939

2040
def database_forwards(self, app_label, schema_editor, from_state, to_state):
21-
connection = schema_editor.connection
22-
fields = ", ".join(
23-
f"{schema_editor.quote_name(name)} {field.db_type(connection)}"
24-
for name, field in self.Meta.fields
41+
schema_editor.execute(
42+
sql_create_type(self.Meta.db_type, self.Meta.fields, schema_editor)
43+
)
44+
self.Meta.model.register_composite(schema_editor.connection)
45+
composite_type_created.send(
46+
self.Meta.model, connection=schema_editor.connection
2547
)
26-
27-
type_name = schema_editor.quote_name(self.Meta.db_type)
28-
29-
schema_editor.execute(f"CREATE TYPE {type_name} AS ({fields})")
30-
31-
self.Meta.model.register_composite(connection)
32-
33-
composite_type_created.send(self.Meta.model, connection=connection)
3448

3549
def database_backwards(self, app_label, schema_editor, from_state, to_state):
36-
type_name = schema_editor.quote_name(self.Meta.db_type)
37-
schema_editor.execute(f"DROP TYPE {type_name}")
50+
return sql_drop_type(self.Meta.db_type, schema_editor=schema_editor)

0 commit comments

Comments
 (0)