flasksqlalchemyalembicflask-migratesqlalchemy-migrate

how to set unique value for each row on alembic migration


I added a unique attribute uid for MyModel model:

class MyModel(db.Model):
...
    uid = db.Column(db.String(50), nullable=False)
...
    __table_args__ = (UniqueConstraint('uid', name='unique_uid'),)

I have a migration:

def upgrade():
    op.add_column('mymodel', sa.Column('uid', sa.String(length=50), nullable=True))

    mymodel = table('mymodel', column('uid'))
    op.execute(mymodel.update().values(uid=generate_uid()))
    op.create_unique_constraint('unique_uid', 'mymodel', ['uid'])

    op.alter_column(
        table_name='mymodel',
        column_name='uid',
        nullable=False
    )

On run db upgrade i've got an error:

...
psycopg2.IntegrityError: could not create unique index "unique_uid"
DETAIL:  Key (uid)=(c92U6txA2) is duplicated.

How to set unique value for each row on op.execute(mymodel.update().values(uid=generate_uid()))?

$ pip freeze
alembic==0.8.6
Flask==0.10.1
Flask-Fixtures==0.3.3
Flask-Login==0.3.2
Flask-Migrate==1.8.0
Flask-Script==2.0.5
Flask-SQLAlchemy==2.1
itsdangerous==0.24
Jinja2==2.8
Mako==1.0.4
MarkupSafe==0.23
psycopg2==2.6.1
python-editor==1.0
requests==2.10.0
SQLAlchemy==1.0.13
Werkzeug==0.11.9

Solution

  • The possible solution:

    from sqlalchemy.orm import Session
    from alembic import op
    import sqlalchemy as sa
    
    def upgrade():
        conn = op.get_bind()
        session = Session(bind=conn)
    
        op.add_column('mymodel', sa.Column('uid', sa.String(length=50), nullable=True))
    
        for item in session.query(MyModel).filter_by(uid=None):
            item.uid = generate_uid()
        session.commit()
    
        op.create_unique_constraint('unique_uid', 'mymodel', ['uid'])
    
        op.alter_column(
            table_name='mymodel',
            column_name='uid',
            nullable=False
        )