Skip to content

Instantly share code, notes, and snippets.

@nofxx
Created August 25, 2009 23:48
Show Gist options
  • Save nofxx/175143 to your computer and use it in GitHub Desktop.
Save nofxx/175143 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# Simple script to rename all columns/index/seq on rails app postgresql db
#
# Usage: pg_rename foo bar
#
require 'rubygems'
require 'activerecord'
require 'annotate/annotate_models'
require 'config/boot'
require 'config/environment'
SUBJ = ARGV.delete_at(0)
NEWN = ARGV.delete_at(0)
SUBJP = SUBJ.pluralize
NEWNP = NEWN.pluralize
def get_all_and_migrate(files)
out = { :up => [], :down => [] }
files.each do |file|
klass = AnnotateModels.get_model_class(file)
next unless klass.respond_to? :columns
klass.columns.each do |col|
if col.name =~ /#{SUBJ}_id/
out[:up] << " rename_column :#{klass.table_name}, :#{col.name}, :#{NEWN}_id"
out[:down] << " rename_column :#{klass.table_name}, :#{NEWN}_id, :#{col.name}"
end
end rescue nil
indexes = klass.connection.indexes(klass.table_name)
next if indexes.empty?
indexes.each do |index|
if index.name =~ /#{SUBJ}/
new_name = index.name.gsub(Regexp.new(SUBJP),NEWNP)
out[:up] << " rename_index :#{index.name}, :#{new_name}"
out[:down] << " rename_index :#{new_name}, :#{index.name}"
end
end
end
out
end
result = get_all_and_migrate(AnnotateModels.get_model_files) #.each { |k| get_and_print_columns k }
puts "Migration ----"
puts
puts '
# Monkeypatching...
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter
def rename_index(old_index, new_index)
execute "ALTER INDEX #{old_index} RENAME TO #{new_index};"
end
def rename_seq(old_seq, new_seq)
execute "ALTER TABLE #{old_seq} RENAME TO #{new_seq}"
end
end
end
end'
puts <<EOT
class BatchRename#{SUBJ.capitalize}To#{NEWN.capitalize} < ActiveRecord::Migration
def self.up
rename_table :#{SUBJP}, :#{NEWNP}
rename_seq :#{SUBJP}_id_seq, :#{NEWNP}_id_seq
#{result[:up].join("\n")}
end
def self.down
rename_table :#{NEWNP}, :#{SUBJP}
rename_seq :#{NEWNP}_id_seq, :#{SUBJP}_id_seq
#{result[:down].join("\n")}
end
end
EOT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment