sqlalchemy / alembic

A database migrations tool for SQLAlchemy.
MIT License
2.61k stars 234 forks source link

Alembic doesn't work properly with postgres schemas #1409

Closed MoxForever closed 5 months ago

MoxForever commented 5 months ago

Trying to make migration for model with custom schema in PostgreSQL, but alembic just recreate model every migration

Example model:

class User(Base):
    __tablename__ = 'users'
    __table_args__ = {"schema": "users"}

    id = Column(Integer, primary_key=True)
    username = Column(String(50), unique=True)
    email = Column(String(50))
    new_field = Column(Integer)

Migration 1:

def upgrade() -> None:
    op.execute("CREATE SCHEMA users")       # added by hand
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('users',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('username', sa.String(length=50), nullable=True),
    sa.Column('email', sa.String(length=50), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('username'),
    schema='users'
    )
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('users', schema='users')
    # ### end Alembic commands ###
    op.execute("DROP SCHEMA users")       # added by hand

Migration 2:

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('users',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('username', sa.String(length=50), nullable=True),
    sa.Column('email', sa.String(length=50), nullable=True),
    sa.Column('new_field', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('username'),
    schema='users'
    )
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('users', schema='users')
    # ### end Alembic commands ###

Full code example: https://github.com/MoxForever/test_alembic