Alembic PostgreSQL Enum

1.10.0 · active · verified Sat Apr 11

alembic-postgresql-enum provides autogenerate support for the creation, alteration, and deletion of PostgreSQL enums within Alembic migration scripts. It addresses limitations where Alembic's default autogenerate often fails to detect and generate migrations for enum value changes (like deletions or reordering). The library is actively maintained, with the latest version 1.10.0 released in February 2026.

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a SQLAlchemy model with a PostgreSQL ENUM. The core functionality of `alembic-postgresql-enum` is activated by importing the library at the top of your `migrations/env.py` file. After doing so, any changes to your Python enum definitions (like adding, removing, or renaming values) will be automatically detected by `alembic revision --autogenerate`, generating the appropriate `op.sync_enum_values` calls to synchronize the database enum type.

import os
import enum
from sqlalchemy import Column, Integer
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import declarative_base

# This is a simplified example. In a real Alembic setup,
# you would define your models and then run 'alembic revision --autogenerate'
# after importing alembic_postgresql_enum in env.py

Base = declarative_base()

class ResourceState(enum.Enum):
    ACTIVE = 'active'
    INACTIVE = 'inactive'
    ARCHIVED = 'archived'

class Resource(Base):
    __tablename__ = 'resources'
    id = Column(Integer, primary_key=True)
    state = Column(postgresql.ENUM(ResourceState, name='resource_state'), nullable=False)

# To simulate a change for autogeneration (e.g., adding a new enum value):
# 1. Initially define ResourceState with just ACTIVE and INACTIVE.
# 2. Run alembic revision --autogenerate. A migration will be created for the initial enum.
# 3. Add 'ARCHIVED' to ResourceState (as shown above).
# 4. Ensure 'import alembic_postgresql_enum' is at the top of your migrations/env.py.
# 5. Run alembic revision --autogenerate again.
#    The library should now generate an 'op.sync_enum_values' call to add 'ARCHIVED'.

print("Alembic-PostgreSQL-Enum quickstart concept: Define your SQLAlchemy models with PostgreSQL ENUMs.")
print("Ensure 'import alembic_postgresql_enum' is added to your migrations/env.py.")
print("Modify your enum definition (add, remove, rename values), then run 'alembic revision --autogenerate'.")
print("The library will generate the necessary SQL for enum synchronization.")

view raw JSON →