Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alembic + Sqlalchemy Multi Column Unique Constraint

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.

like image 551
Ansgar S. Avatar asked Apr 27 '16 16:04

Ansgar S.


1 Answers

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

like image 123
Andy Lau Avatar answered Sep 22 '22 16:09

Andy Lau