简体   繁体   中英

Adding a null constraint on a unique-indexed column in a migration

I am trying to add a column to my db ( key ) that is both unique and not null. In my migration, I have code that populates the column. The problem is that the migration is failing because it adds this unique/non null constraint before it adds the data, then complains about there being an existing key.

Is this something where I need two migrations -- one to add the column/data, and then a later one to add the constraints? Or can this be done in one go?

Ideally , in this kind of scenario, it is advisable to create a new table, called Stage Table (STG_YOUr table_name ), which very similar to that of the original with fewer constraint. Do all the data transformation/ manipulation here and then once ready MERGE or insert into the original production table.

I wouldn't advise populating data in migrations. I've found it best to let migrations just focus on physical changes to the structure of your database. You should create rake tasks to manipulate your data. Really, you should put data manipulation methods in your models (and unit test them) and just have your rake task delegate to those methods. You can then run your rake task after running all of your migrations, or intermix single migrations and rake tasks.

Late answer but i hope this helps to others if not the one who asked the question!

According to me you should delete the column and make it again as shown:

alter table students drop column email;
alter table students add column email varchar (80) unique not null; 

Here email is the column that was unique but null so i dropped it and then re-added it to the table by desired properties.

Hope this helped ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM