Question

I have a table 'test' having a column 'Name' with no constraints. I need to ALTER this column by giving it a UNIQUE constraint. How should I do it?

Should I use op.alter_column('???') or create_unique_constraint('???')? Isn't create_unique_constraint for new column and not for existing one?

Was it helpful?

Solution

To add, you'd need: https://alembic.sqlalchemy.org/en/latest/ops.html#alembic.operations.Operations.create_unique_constraint

from alembic import op
op.create_unique_constraint('uq_user_name', 'user', ['name'], schema='my_schema')

To drop, you'd need: https://alembic.sqlalchemy.org/en/latest/ops.html#alembic.operations.Operations.drop_constraint

op.drop_constraint('uq_user_name', 'user', schema='my_schema')

OTHER TIPS

Note: SQLAlchemy Migrations

Updated = Version: 0.7.3

  1. to add unique constraints use create() on UniqueConstraint
  2. to remove unique contraints use drop() on UniqueConstraint

Create a migration script. The script can be created in 2 ways.

# create manage.py
migrate manage manage.py --repository=migrations --url=postgresql://<user>:<password>@localhost:5432/<db_name>
# create script file
python manage.py script "Add Unique Contraints"

Or if you don't want to create manage.py then use the below commands

migrate script --repository=migrations --url=postgresql://<user>:<password?@localhost:5432/<db_name> "Add Unique Contraint"

it will create 00x_Add_Unique_Constraints.py

File: 00x_Add_Unique_Constraints.py

from migrate import UniqueConstraint
from sqlalchemy import MetaData, Table


def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine; bind
    # migrate_engine to your metadata
    # Table Name: user_table
    # Column Name: first_name

    metadata = MetaData(bind=migrate_engine)
    user_table = Table('user_table', metadata, autoload=True)
    UniqueConstraint(user_table.c.first_name, table=user_table).create() 


def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    # Table Name: user_table
    # Column Name: first_name

    metadata = MetaData(bind=migrate_engine)
    user_table = Table('user_table', metadata, autoload=True)
    UniqueConstraint(user_table.c.first_name, table=user_table).drop()

Following Mario Ruggier's answer, I tried using his example code for my MySQL database and I didn't use the schema arguments because my database didn't have a schema.

I used:

from alembic import op
op.create_unique_constraint('uq_user_name', 'user', ['name'])

to drop the unique constraint, and

op.drop_constraint(constraint_name='uq_user_name', table_name='user', type_='unique')

Notice the different that I used a third argument, type_='unique', because without it, MySQL would return an error message that states something like

No generic 'DROP CONSTRAINT' in MySQL - please specify constraint type ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top