alembic-postgresql-enum icon indicating copy to clipboard operation
alembic-postgresql-enum copied to clipboard

Support enum rename

Open cdeil opened this issue 7 months ago • 1 comments

Could you please add support to rename enums?

We have such renames in our project and it would help us a lot.

In your example from the README you have MyEnum and when I rename it to TheEnum then I get this migration proposed from alembic revision --autogenerate:

    sa.Enum('one', 'two', 'three', name='theenum').create(op.get_bind())
    op.alter_column('example_table', 'enum_field',
               existing_type=postgresql.ENUM('one', 'two', 'three', name='myenum'),
               type_=postgresql.ENUM('one', 'two', 'three', name='theenum'),
               existing_nullable=True,
               postgresql_using='enum_field::theenum')
    sa.Enum('one', 'two', 'three', name='myenum').drop(op.get_bind())

It generates this SQL:

CREATE TYPE theenum AS ENUM ('one', 'two', 'three');
ALTER TABLE example_table ALTER COLUMN enum_field TYPE theenum USING enum_field::theenum;
DROP TYPE myenum;

The ALTER TABLE command errors like this:

[42846] ERROR: cannot cast type myenum to theenum
Position: 80

The following change makes the migration succeed:

-               postgresql_using='enum_field::theenum')
+               postgresql_using='enum_field::text::theenum')

Can you make this work out of the box? Or if not document the proper way to do it in the README? (is it to add ::text or something else?)

Thank you!

cdeil avatar May 02 '25 10:05 cdeil

(alembic-postgresql-enum-venv) russellm@L-PW00KQRA:~/deepfield-bootstrap/alembic-postgresql-enum(develop)$ gd 1
diff --git a/alembic_postgresql_enum/add_postgres_using_to_text.py b/alembic_postgresql_enum/add_postgres_using_to_text.py
index adf33ba..bb3ee3f 100644
--- a/alembic_postgresql_enum/add_postgres_using_to_text.py
+++ b/alembic_postgresql_enum/add_postgres_using_to_text.py
@@ -40,7 +40,7 @@ log = logging.getLogger(f"alembic.{__name__}")
 
 def add_postgres_using_to_alter_operation(op: AlterColumnOp):
     assert op.modify_type is not None
-    op.kw["postgresql_using"] = f"{op.column_name}::{op.modify_type.name}"
+    op.kw["postgresql_using"] = f"{op.column_name}::text::{op.modify_type.name}"
     log.info("postgresql_using added to %r.%r alteration", op.table_name, op.column_name)
     op.__class__ = PostgresUsingAlterColumnOp
 
(alembic-postgresql-enum-venv) russellm@L-PW00KQRA:~/deepfield-bootstrap/alembic-postgresql-enum(develop)$ 

???

Apteryx0 avatar May 16 '25 21:05 Apteryx0