public
Last active

Rails SQL schema load support for PostgreSQL. Put both files in `lib/tasks`.

  • Download Gist
schema_format.rake
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
import File.expand_path(File.dirname(__FILE__) + '/schema_format.rb')
 
namespace :db do
# Define PG environment utility methods
task :pg_env => :environment do
def pg_get_config
ActiveRecord::Base.configurations.fetch(Rails.env).tap do |config|
ENV['PGHOST'] = config['host'].to_s if config.key?('host')
ENV['PGPORT'] = config['port'].to_s if config.key?('port')
ENV['PGPASSWORD'] = config['password'].to_s if config.key?('password')
end
end
 
def pg_make_dump(target, username, database)
%x( pg_dump -f #{target} -c -U #{username} #{database} )
end
 
def pg_load_dump(source, username, database, template = nil)
%x( psql -U "#{username}" -f #{source} #{database} #{template} )
end
end
 
namespace :structure do
desc "Load structure.sql file into the current environment's database"
task :load => :pg_env do
# Loads the db/structure.sql file into current environment's database.
#
pg_load_dump Rails.root.join('db/structure.sql').to_s,
*pg_get_config.values_at('username', 'database', 'template')
end
end
 
namespace :data do
desc "Save a dump of the database in db/data.NOW.sql"
task :dump => :pg_env do
target = Rails.root.join('db', "data.#{Time.now.to_f}.sql")
 
print "** Dumping data to #{target}..."
pg_make_dump target, *pg_get_config.values_at('username', 'database')
puts 'done'
end
 
desc "Load a dump of the database from ENV['DUMP']"
task :load => :pg_env do
source = ENV['DUMP'].presence or
raise ArgumentError, "Invoke as rake db:data:load DUMP=/path/to/data.sql"
print "**Restoring data from #{source}..."
pg_load_dump source, *pg_get_config.values_at('username', 'database')
puts 'done'
end
end
end
schema_format.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13
# h/t http://stackoverflow.com/questions/4698467
#
if Rails.application.config.active_record.schema_format == :sql
 
Rake::Task['db:schema:dump'].clear.enhance(['environment']) do
Rake::Task['db:structure:dump'].invoke
end
 
Rake::Task['db:schema:load'].clear.enhance(['environment']) do
Rake::Task['db:structure:load'].invoke
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.