Created
February 15, 2014 17:18
-
-
Save JamesHarker/9022197 to your computer and use it in GitHub Desktop.
Using Postgres Schemas with Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace :all_tenants do | |
desc "Run migration for each tenant" | |
task "db:migrate" => %w[environment db:load_config] do | |
Tenant.find_each do |tenant| | |
p "Running migration for tenant#{tenant.id}" | |
tenant.scope_schema do | |
ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true | |
ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil) do |migration| | |
ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope) | |
end | |
end | |
end | |
Rake::Task["db:schema:dump"].execute | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
tasks = Rake.application.instance_variable_get '@tasks' | |
tasks.delete 'db:structure:dump' | |
namespace 'db' do | |
namespace 'structure' do | |
task :dump => [:environment, :load_config] do | |
configuration = ActiveRecord::Tasks::DatabaseTasks.current_config | |
filename = ENV['DB_STRUCTURE'] || File.join(Rails.root, "db", "structure.sql") | |
ENV['PGHOST'] = configuration['host'] if configuration['host'] | |
ENV['PGPORT'] = configuration['port'].to_s if configuration['port'] | |
ENV['PGPASSWORD'] = configuration['password'].to_s if configuration['password'] | |
ENV['PGUSER'] = configuration['username'].to_s if configuration['username'] | |
command = "pg_dump -i -s -x -O -f #{Shellwords.escape(filename)} --schema=public #{Shellwords.escape(configuration['database'])}" | |
raise 'Error dumping database' unless Kernel.system(command) | |
if ActiveRecord::Base.connection.supports_migrations? | |
File.open(filename, "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information } | |
end | |
# Dump ruby schema for reference | |
Rake::Task["db:schema:dump"].invoke | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment