Search code examples
pythonsqlalchemyalembic

How to use existing postgres enum in alembic migration?


I have a new migration using alembic. My database has a enum name myenum.

This is the migration script:

def upgrade():
    op.create_table(
        "test_table",
        # ...
        sa.Column("enum_col", sa.Enum("A", "B", "C", name="myenum"), server_default="A", nullable=False)
        # ...
    )

But when I migrate the script, it excepts:

DuplicateObject: "myenum" already exists

I need to know how to use the existing enum in migration.

I've tried create_type=False as shown in the answer here. But It doesn't help either.


Solution

  • The built-in Enum type of SQLAlchemy doesn't support create_type. You can use the ENUM type from the postgres dialect which support create_type=False.

    from sqlalchemy.dialects import postgresql as pg
    def upgrade():
        op.create_table(
            "test_table",
            # ...
            sa.Column("enum_col", 
                      pg.ENUM("A", "B", "C", 
                      name="myenum", create_type=False), 
                      server_default="A", nullable=False)
            # ...
        )
    

    See the docs for some additional information about create_type.