简体   繁体   中英

rails - shouldn't I use default values in rails migration

I am not sure whether I should ask this question on SO or not. But I have to as I don't have clear idea about my doubt. I was told not to set default values in rails migrations and use null values instead in a code review by our CTO. And his explanation is like this once the database gets huge enough, migrations with defaults runs slow and may throw database timeout errors . But I think at the database level it is fast enough to execute as its an initial setup of things. Am I right?

Using default values in add column migrations takes time when number of table rows is huge.

This is a tip given by Postgres Doc: https://www.postgresql.org/docs/9.5/static/ddl-alter.html

Tip: Adding a column with a default requires updating each row of the table (to store the new column value). However, if no default is specified, PostgreSQL is able to avoid the physical update. So if you intend to fill the column with mostly nondefault values, it's best to add the column with no default, insert the correct values using UPDATE, and then add any desired default as described below.

Look it this way .. Size of 'NULL' in comparison to size of default values both in bytes terms.

This difference for few rows of data maybe in KBs or less but when the size of the database is big, it will have multiplier effect. So during migration the default values option will definitely need to do more work.

The downtime (or migration) time may be critical in many cases, hence its the role of the DBAs and the developers to ensure the optimum usage of available resources, this includes time.

You may like to evaluate this using a dummy database and a benchmarking tool for more clarity.

As @dnsh correctly stated in their answer , using default values can make the migration slower.

Additionally, if the column is supposed to be non-null in the end, you can first create it with null: true , then do something like Entity.all.each { |e| e.prop = 'foo' } Entity.all.each { |e| e.prop = 'foo' } to set the "default" value and then use change_column to set null: false . This can be done in a single migration.

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