Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alembic: How to add unique constraint to existing column

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?

like image 763
Ishwar Avatar asked May 16 '13 13:05

Ishwar


People also ask

What will happen if a column has unique key constraint?

When we will add a UNIQUE constraint on the same column multiple times then MySQL will create the index on that column for a number of times we have added the UNIQUE constraint.

How do I change unique constraints in MySQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.

How does a unique constraint work?

The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.


1 Answers

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') 
like image 181
Mario Ruggier Avatar answered Dec 01 '22 14:12

Mario Ruggier