Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #57 #58

Merged
merged 6 commits into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
SQLAlchemy enums.

"""

import logging

from alembic.operations.ops import UpgradeOps
Expand Down
11 changes: 9 additions & 2 deletions alembic_postgresql_enum/get_enum_data/declared_enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,16 @@ def get_declared_enums(
if column_type.name not in enum_name_to_values:
enum_name_to_values[column_type.name] = get_enum_values(column_type)

column_default = get_column_default(connection, schema, table.name, column.name)
table_schema = table.schema or default_schema
column_default = get_column_default(connection, table.schema, table.name, column.name)
enum_name_to_table_references[column_type.name].add(
TableReference(table.name, column.name, column_type_wrapper, column_default)
TableReference(
table_schema=table_schema,
table_name=table.name,
column_name=column.name,
column_type=column_type_wrapper,
existing_server_default=column_default,
)
)

return DeclaredEnumValues(
Expand Down
7 changes: 5 additions & 2 deletions alembic_postgresql_enum/get_enum_data/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,16 @@ def __repr__(self):
class TableReference:
table_name: str
column_name: str
table_schema: str = None
RustyGuard marked this conversation as resolved.
Show resolved Hide resolved
column_type: ColumnType = ColumnType.COMMON
existing_server_default: str = None

def __repr__(self):
result_str = "TableReference("
result_str += f"{self.table_name!r}, "
result_str += f"{self.column_name!r}, "
if self.table_schema:
result_str += f"table_schema={self.table_schema!r}, "
result_str += f"table_name={self.table_name!r}, "
result_str += f"column_name={self.column_name!r}, "
if self.column_type != ColumnType.COMMON:
result_str += f"column_type=ColumnType.{self.column_type.name}, "
if self.existing_server_default is not None:
Expand Down
38 changes: 24 additions & 14 deletions alembic_postgresql_enum/operations/sync_enum_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,16 +82,12 @@ def _set_enum_values(
column_default = table_reference.existing_server_default

if column_default is not None:
drop_default(connection, schema, table_reference)
drop_default(
connection, table_reference.table_schema, table_reference.table_name, table_reference.column_name
RustyGuard marked this conversation as resolved.
Show resolved Hide resolved
)

try:
cast_old_enum_type_to_new(
connection,
schema,
table_reference,
enum_type_name,
enum_values_to_rename,
)
cast_old_enum_type_to_new(connection, table_reference, enum_type_name, enum_values_to_rename)
except DataError as error:
raise ValueError(
f"""New enum values can not be set due to some row containing reference to old enum value.
Expand All @@ -102,7 +98,13 @@ def _set_enum_values(
if column_default is not None:
column_default = rename_default_if_required(schema, column_default, enum_name, enum_values_to_rename)

set_default(connection, schema, table_reference, column_default)
set_default(
connection,
table_reference.table_schema,
table_reference.table_name,
table_reference.column_name,
column_default,
)

drop_comparison_operators(connection, schema, enum_name, temporary_enum_name)
drop_type(connection, schema, temporary_enum_name)
Expand All @@ -111,7 +113,7 @@ def _set_enum_values(
def sync_enum_values(
cls,
operations,
schema: str,
enum_schema: str,
enum_name: str,
new_values: List[str],
affected_columns: List[Tuple[str, str]],
Expand All @@ -121,7 +123,7 @@ def sync_enum_values(
Replace enum values with `new_values`
:param operations:
...
:param str schema:
:param str enum_schema:
Schema name.
:param enum_name:
Enumeration type name.
Expand Down Expand Up @@ -151,8 +153,16 @@ def sync_enum_values(
column_type = affected_column[2]
else:
column_type = ColumnType.COMMON
column_default = get_column_default(connection, schema, table_name, column_name)
table_references.append(TableReference(table_name, column_name, column_type, column_default))
column_default = get_column_default(connection, enum_schema, table_name, column_name)
table_references.append(
TableReference(
table_name,
column_name,
table_schema=enum_schema,
column_type=column_type,
existing_server_default=column_default,
)
)

elif isinstance(affected_column, TableReference):
table_references.append(affected_column)
Expand All @@ -161,7 +171,7 @@ def sync_enum_values(

cls._set_enum_values(
connection,
schema,
enum_schema,
enum_name,
new_values,
table_references,
Expand Down
26 changes: 10 additions & 16 deletions alembic_postgresql_enum/sql_commands/column_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@

import sqlalchemy

from alembic_postgresql_enum.get_enum_data import TableReference

if TYPE_CHECKING:
from sqlalchemy.engine import Connection


def get_column_default(
connection: "Connection",
schema: str,
table_name: str,
column_name: str,
connection: "Connection", table_schema: str, table_name: str, column_name: str
) -> Union[str, None]:
RustyGuard marked this conversation as resolved.
Show resolved Hide resolved
"""Result example: "'active'::order_status" """
default_value = connection.execute(
Expand All @@ -21,7 +16,7 @@ def get_column_default(
SELECT column_default
FROM information_schema.columns
WHERE
table_schema = '{schema}' AND
table_schema = '{table_schema}' AND
table_name = '{table_name}' AND
column_name = '{column_name}'
"""
Expand All @@ -30,27 +25,26 @@ def get_column_default(
return default_value


def drop_default(
connection: "Connection",
schema: str,
table_reference: TableReference,
):
def drop_default(connection: "Connection", table_schema: str, table_name: str, column_name: str):
connection.execute(
sqlalchemy.text(
f"""ALTER TABLE {schema}.{table_reference.table_name} ALTER COLUMN {table_reference.column_name} DROP DEFAULT"""
f"""ALTER TABLE {table_schema}.{table_name}
ALTER COLUMN {column_name} DROP DEFAULT"""
)
)


def set_default(
connection: "Connection",
schema: str,
table_reference: TableReference,
table_schema: str,
table_name: str,
column_name: str,
default_value: str,
):
connection.execute(
sqlalchemy.text(
f"""ALTER TABLE {schema}.{table_reference.table_name} ALTER COLUMN {table_reference.column_name} SET DEFAULT {default_value}"""
f"""ALTER TABLE {table_schema}.{table_name}
ALTER COLUMN {column_name} SET DEFAULT {default_value}"""
)
)

Expand Down
19 changes: 7 additions & 12 deletions alembic_postgresql_enum/sql_commands/enum_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

def cast_old_array_enum_type_to_new(
connection: "Connection",
schema: str,
table_reference: TableReference,
enum_type_name: str,
enum_values_to_rename: List[Tuple[str, str]],
Expand All @@ -22,7 +21,8 @@ def cast_old_array_enum_type_to_new(

connection.execute(
sqlalchemy.text(
f"""ALTER TABLE {schema}.{table_reference.table_name} ALTER COLUMN {table_reference.column_name} TYPE {enum_type_name}[]
f"""ALTER TABLE {table_reference.table_schema}.{table_reference.table_name}
ALTER COLUMN {table_reference.column_name} TYPE {enum_type_name}[]
USING {cast_clause}::{enum_type_name}[]
"""
)
Expand All @@ -31,25 +31,19 @@ def cast_old_array_enum_type_to_new(

def cast_old_enum_type_to_new(
connection: "Connection",
schema: str,
table_reference: TableReference,
enum_type_name: str,
enum_values_to_rename: List[Tuple[str, str]],
):
if table_reference.column_type == ColumnType.ARRAY:
cast_old_array_enum_type_to_new(
connection,
schema,
table_reference,
enum_type_name,
enum_values_to_rename,
)
cast_old_array_enum_type_to_new(connection, table_reference, enum_type_name, enum_values_to_rename)
return

if enum_values_to_rename:
connection.execute(
sqlalchemy.text(
f"""ALTER TABLE {schema}.{table_reference.table_name} ALTER COLUMN {table_reference.column_name} TYPE {enum_type_name}
f"""ALTER TABLE {table_reference.table_schema}.{table_reference.table_name}
ALTER COLUMN {table_reference.column_name} TYPE {enum_type_name}
USING CASE
{' '.join(
f"WHEN {table_reference.column_name}::text = '{old_value}' THEN '{new_value}'::{enum_type_name}"
Expand All @@ -63,7 +57,8 @@ def cast_old_enum_type_to_new(
else:
connection.execute(
sqlalchemy.text(
f"""ALTER TABLE {schema}.{table_reference.table_name} ALTER COLUMN {table_reference.column_name} TYPE {enum_type_name}
f"""ALTER TABLE {table_reference.table_schema}.{table_reference.table_name}
ALTER COLUMN {table_reference.column_name} TYPE {enum_type_name}
USING {table_reference.column_name}::text::{enum_type_name}
"""
)
Expand Down
8 changes: 7 additions & 1 deletion tests/get_enum_data/test_get_declared_enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ def test_with_user_schema(connection: "Connection"):

assert function_result.enum_values == {USER_STATUS_ENUM_NAME: tuple(enum_variants)}
assert function_result.enum_table_references == {
USER_STATUS_ENUM_NAME: frozenset((TableReference(USER_TABLE_NAME, USER_STATUS_COLUMN_NAME),))
USER_STATUS_ENUM_NAME: frozenset(
(
TableReference(
table_schema=DEFAULT_SCHEMA, table_name=USER_TABLE_NAME, column_name=USER_STATUS_COLUMN_NAME
),
)
)
}


Expand Down
8 changes: 7 additions & 1 deletion tests/get_enum_data/test_type_decorator_enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,12 @@ def test_get_declared_enums_for_custom_enum(connection: "Connection"):
}
assert function_result.enum_table_references == {
ORDER_DELIVERY_STATUS_ENUM_NAME: frozenset(
(TableReference(ORDER_TABLE_NAME, ORDER_DELIVERY_STATUS_COLUMN_NAME),)
(
TableReference(
table_schema=DEFAULT_SCHEMA,
table_name=ORDER_TABLE_NAME,
column_name=ORDER_DELIVERY_STATUS_COLUMN_NAME,
),
)
)
}
21 changes: 16 additions & 5 deletions tests/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,24 @@ def get_declared_enum_values_with_orders_and_users() -> DeclaredEnumValues:
enum_table_references={
"user_status_enum": frozenset(
(
TableReference("users", "user_status"),
TableReference("users", "last_user_status"),
TableReference("orders", "user_status"),
TableReference(table_schema=DEFAULT_SCHEMA, table_name="users", column_name="user_status"),
TableReference(table_schema=DEFAULT_SCHEMA, table_name="users", column_name="last_user_status"),
TableReference(table_schema=DEFAULT_SCHEMA, table_name="orders", column_name="user_status"),
)
),
"order_status_enum": frozenset(
(TableReference(table_schema=DEFAULT_SCHEMA, table_name="orders", column_name="order_status"),)
),
"car_color_enum": frozenset(
(
TableReference(
table_schema=DEFAULT_SCHEMA,
table_name="cars",
column_name="colors",
column_type=ColumnType.ARRAY,
),
)
),
"order_status_enum": frozenset((TableReference("orders", "order_status"),)),
"car_color_enum": frozenset((TableReference("cars", "colors", ColumnType.ARRAY),)),
},
)

Expand Down
31 changes: 26 additions & 5 deletions tests/sync_enum_values/test_array_column.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ def test_add_new_enum_value_render_with_array(connection: "Connection"):
template_args["upgrades"]
== f"""# ### commands auto generated by Alembic - please adjust! ###
op.sync_enum_values('{DEFAULT_SCHEMA}', '{CAR_COLORS_ENUM_NAME}', [{', '.join(map(repr, new_enum_variants))}],
[TableReference('{CAR_TABLE_NAME}', '{CAR_COLORS_COLUMN_NAME}', column_type=ColumnType.ARRAY)],
[TableReference(table_schema='{DEFAULT_SCHEMA}', table_name='{CAR_TABLE_NAME}', column_name='{CAR_COLORS_COLUMN_NAME}', column_type=ColumnType.ARRAY)],
enum_values_to_rename=[])
# ### end Alembic commands ###"""
)
assert (
template_args["downgrades"]
== f"""# ### commands auto generated by Alembic - please adjust! ###
op.sync_enum_values('{DEFAULT_SCHEMA}', '{CAR_COLORS_ENUM_NAME}', [{', '.join(map(repr, old_enum_variants))}],
[TableReference('{CAR_TABLE_NAME}', '{CAR_COLORS_COLUMN_NAME}', column_type=ColumnType.ARRAY)],
[TableReference(table_schema='{DEFAULT_SCHEMA}', table_name='{CAR_TABLE_NAME}', column_name='{CAR_COLORS_COLUMN_NAME}', column_type=ColumnType.ARRAY)],
enum_values_to_rename=[])
# ### end Alembic commands ###"""
)
Expand Down Expand Up @@ -87,7 +87,14 @@ def test_add_new_enum_value_diff_tuple_with_array(connection: "Connection"):
SyncEnumValuesOp.operation_name,
old_enum_variants,
new_enum_variants,
[TableReference(CAR_TABLE_NAME, CAR_COLORS_COLUMN_NAME, ColumnType.ARRAY)],
[
TableReference(
table_schema=DEFAULT_SCHEMA,
table_name=CAR_TABLE_NAME,
column_name=CAR_COLORS_COLUMN_NAME,
column_type=ColumnType.ARRAY,
)
],
)


Expand Down Expand Up @@ -124,7 +131,14 @@ def test_remove_enum_value_diff_tuple_with_array(connection: "Connection"):
assert operation_name == SyncEnumValuesOp.operation_name
assert old_values == old_enum_variants
assert new_values == new_enum_variants
assert affected_columns == [TableReference(CAR_TABLE_NAME, CAR_COLORS_COLUMN_NAME, ColumnType.ARRAY)]
assert affected_columns == [
TableReference(
table_schema=DEFAULT_SCHEMA,
table_name=CAR_TABLE_NAME,
column_name=CAR_COLORS_COLUMN_NAME,
column_type=ColumnType.ARRAY,
)
]


def test_rename_enum_value_diff_tuple_with_array(connection: "Connection"):
Expand Down Expand Up @@ -161,4 +175,11 @@ def test_rename_enum_value_diff_tuple_with_array(connection: "Connection"):
assert operation_name == SyncEnumValuesOp.operation_name
assert old_values == old_enum_variants
assert new_values == new_enum_variants
assert affected_columns == [TableReference(CAR_TABLE_NAME, CAR_COLORS_COLUMN_NAME, ColumnType.ARRAY)]
assert affected_columns == [
TableReference(
table_schema=DEFAULT_SCHEMA,
table_name=CAR_TABLE_NAME,
column_name=CAR_COLORS_COLUMN_NAME,
column_type=ColumnType.ARRAY,
)
]
Loading
Loading