Created
October 28, 2009 21:21
-
-
Save newtonapple/220855 to your computer and use it in GitHub Desktop.
Rakefile: The bare minimal you'll need to clone a test db from your env.
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
require 'rubygems' | |
require 'rake' | |
require 'activerecord' | |
CURRENT_ENV = ENV['RAILS_ENV'] || 'development' | |
ROOT_PATH = File.dirname(__FILE__) | |
DB_CONFIG = YAML.load_file(File.join(ROOT_PATH, 'config', 'database.yml')) | |
namespace :db do | |
namespace :structure do | |
desc "Dump the database structure to a SQL file" | |
task :dump do | |
ActiveRecord::Base.establish_connection(DB_CONFIG[CURRENT_ENV]) | |
db_path = File.join(ROOT_PATH, 'db') | |
mkdir db_path unless File.exists? db_path | |
File.open(File.join(db_path, "#{CURRENT_ENV}_structure.sql"), 'w+') { |f| f << ActiveRecord::Base.connection.structure_dump } | |
end | |
end | |
namespace :test do | |
TEST_CONFIG = DB_CONFIG['test'] | |
desc "Create test database if it doesn't already exists" | |
task :create do | |
ActiveRecord::Base.establish_connection(TEST_CONFIG.merge('database'=>nil)) | |
ActiveRecord::Base.connection.create_database(TEST_CONFIG['database'], :charset => (TEST_CONFIG['charset'] || @charset), :collation => (TEST_CONFIG['collation'] || @collation)) | |
ActiveRecord::Base.establish_connection(TEST_CONFIG) | |
end | |
desc 'Empty the test database' | |
task :purge do | |
ActiveRecord::Base.establish_connection(TEST_CONFIG) | |
ActiveRecord::Base.connection.recreate_database(TEST_CONFIG['database'], TEST_CONFIG) | |
end | |
desc "Recreate the test databases from the development structure" | |
task :clone_structure => ['db:structure:dump', 'db:test:purge'] do | |
ActiveRecord::Base.establish_connection(TEST_CONFIG) | |
ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0') | |
IO.readlines("#{ROOT_PATH}/db/#{CURRENT_ENV}_structure.sql").join.split("\n\n").each do |table| | |
ActiveRecord::Base.connection.execute(table) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment