Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add concurrent index in Postgres Rails migration
class IndexUsersEmails < ActiveRecord::Migration
def self.up
execute "END"
add_pg_index :users, :email, :lock => false
execute "BEGIN"
end
end
# lib/extensions/migrations_ext.rb
# This is here purely to allow me to use concurrent indexes
module ActiveRecord::ConnectionAdapters::SchemaStatements
# add_pg_index :users, :email, :lock => true
def add_pg_index(table_name, column_name, options = {})
column_names = Array.wrap(column_name)
index_name = index_name(table_name, :column => column_names)
if Hash === options # legacy support, since this param was a string
index_type = options[:unique] ? "UNIQUE" : ""
index_name = options[:name].to_s if options.key?(:name)
index_lock = options[:lock] ? "" : "CONCURRENTLY"
else
index_type = options
end
if index_name.length > index_name_length
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' is too long; the limit is #{index_name_length} characters"
end
if index_name_exists?(table_name, index_name, false)
raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists"
end
quoted_column_names = quoted_columns_for_index(column_names, options).join(", ")
execute "CREATE #{index_type} INDEX #{index_lock} #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{quoted_column_names})"
end
end
@thatandyrose

This comment has been minimized.

Copy link

@thatandyrose thatandyrose commented Aug 15, 2013

Thank you for this! Have you had any problems with it since you wrote this?

@thatandyrose

This comment has been minimized.

Copy link

@thatandyrose thatandyrose commented Aug 15, 2013

Another quick question. Why not put the execute END/BEGIN inside the add_pg_index method?

@nathany

This comment has been minimized.

Copy link

@nathany nathany commented Aug 19, 2013

I'm guessing that's a hack to break out of the transaction? http://robots.thoughtbot.com/post/56828751507/how-to-create-postgres-indexes-concurrently-in

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment