Reputation: 241
I'm attempting to create using sqlalchemy a multi column unique constraint that will be picked up by Alembic in it's automatic upgrade script generator.
I have create the constraint using:
from sqlalchemy import UniqueConstraint
in my model
UniqueConstraint('col1', 'col2', 'number', name='uix_table_col1_col2_col3')
However, this is not picked up by Alembic in it's automatic script generation.
I can manually create this in the Alembic script by adding in.
op.create_unique_constraint('uq_table_col1_col2_col3', 'table', ['col1', 'col2', 'col3'])
Is there a way to have this be automatically generated by Alembic?
Thank you for your help.
Upvotes: 24
Views: 10246
Reputation: 448
I can confirm that:
....
__table_args__ = (UniqueConstraint('col1', 'col2'),)
....
Adds the following to an alembic upgrade file:
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_unique_constraint(None, 'instruments', ['col1', 'col2'])
# ### end Alembic commands ###
Upvotes: 4
Reputation: 341
I was experiencing the same problem and found that if you're defining the table using the declarative model, you can add it the unique constraint to __table_args__
and Alembic will pick it up:
class MyClass(Base):
__tablename__ = 'table'
__table_args__ = (
UniqueConstraint('col1', 'col2', 'number', name='uix_table_col1_col2_col3'),
)
http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/table_config.html
Upvotes: 34