Skip to content

Instantly share code, notes, and snippets.

@nesquena
Created July 14, 2011 00:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nesquena/1081618 to your computer and use it in GitHub Desktop.
Save nesquena/1081618 to your computer and use it in GitHub Desktop.
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
@nathany
Copy link

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