Skip to content

Instantly share code, notes, and snippets.

@bradurani
Created May 18, 2017 23:32
Show Gist options
  • Save bradurani/37c7cd219a77b302ceea64c3eb729be0 to your computer and use it in GitHub Desktop.
Save bradurani/37c7cd219a77b302ceea64c3eb729be0 to your computer and use it in GitHub Desktop.
blog-migrating-databases-2
class AddColumnUsersIsAdmin < ActiveRecord::Migration
phase :pre_restart
def change
add_column :users, :is_admin, :boolean
end
end
class BackfillUsersIsAdminNoLock < ActiveRecord::Migration
phase :post_restart
disable_ddl_transaction!
def up
User.unscoped.find_in_batches(batch_size: batch_size) do |b|
User.unscoped.where(id: b.map(&:id)).update_all(is_admin: false)
end
end
def down
User.unscoped.find_in_batches(batch_size: batch_size) do |b|
User.unscoped.where(id: b.map(&:id)).update_all(is_admin: nil)
end
end
def batch_size
1000
end
end
class AddTemporaryIndexUsersIsAdmin < ActiveRecord::Migration
phase :post_restart
disable_ddl_transaction!
def change
add_index :users, :is_admin, where: 'is_admin IS NULL', algorithm: :concurrently,
name: 'temp_partial_index_on_users_is_admin'
end
end
class BackfillUsersIsAdminWithLock < ActiveRecord::Migration
phase :post_restart
def up
execute 'LOCK TABLE users IN ACCESS EXCLUSIVE MODE;'
User.unscoped.where(is_admin: nil).update_all(is_admin: false)
change_column_default :users, :is_admin, false
change_column_null :users, :is_admin, false
end
def down
change_column_null :users, :is_admin, true
change_column_default :users, :is_admin, nil
end
end
class RemoveTemporaryIndexUsersIsAdmin < ActiveRecord::Migration
phase :post_restart
disable_ddl_transaction!
def up
remove_index :users, algorithm: :concurrently,
name: 'temp_partial_index_on_users_is_admin'
end
def down
add_index :users, :is_admin, where: 'is_admin IS NULL', algorithm: :concurrently,
name: 'temp_partial_index_on_users_is_admin'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment