Skip to content

Instantly share code, notes, and snippets.

@micahbf
Last active August 29, 2015 13:57
Show Gist options
  • Save micahbf/9627652 to your computer and use it in GitHub Desktop.
Save micahbf/9627652 to your computer and use it in GitHub Desktop.
Cache your clean test DB for blazingly fast test environment setup
# this rakefile is designed to be run alone. rails needs to be explicitly loaded if needed
require 'digest/sha1'
require 'fileutils'
require 'yaml'
namespace :db do
namespace :cached do
desc 'load the cached dump or regenerate if necessary'
task :setup_all do
rails_root = File.expand_path('../../..', __FILE__)
def rails_root.join(*paths)
File.join(self, *paths)
end
master_hash = lambda do
seed_path = rails_root.join('db', 'seed')
hash_paths = Dir.glob(File.join(seed_path, '*.{yml,csv}')).sort
hash_paths << rails_root.join('db', 'schema.rb')
hash_paths.reduce('') { |m, p| Digest::SHA1.hexdigest(m + File.read(p)) }
end
schema_migrated_to = File.open(rails_root.join('db', 'schema.rb')) do |f|
f.detect { |l| l =~ /:version => (\d+)/ }
$1.to_i
end
newest_migration = Dir.entries(rails_root.join('db', 'migrate')).sort.last.split('_').first.to_i #sup demeter
needs_migration = newest_migration > schema_migrated_to
FileUtils.mkdir_p(rails_root.join('db', 'cached'))
sql_dump_path = lambda { rails_root.join('db', 'cached', "all-#{master_hash.call}.sql") }
db_config = YAML.load_file(rails_root.join('config', 'database.yml'))['test']
password_string = db_config['password'] ? "-p#{db_config['password']} " : ""
current_sql_dump_path = sql_dump_path.call
if File.exists?(current_sql_dump_path) && !needs_migration
puts "Cached dump found, loading via SQL"
`mysqladmin -u#{db_config['username']} #{password_string}-f drop #{db_config['database']}`
`mysqladmin -u#{db_config['username']} #{password_string}create #{db_config['database']}`
`mysql -u#{db_config['username']} #{password_string}#{db_config['database']} < #{current_sql_dump_path}`
else
puts "No cached dump found or schema needs migration, loading all from scratch"
load rails_root.join('Rakefile') unless defined? Rails
Rake::Task['cruise:db_setup'].invoke
`mysqldump -u#{db_config['username']} #{password_string}#{db_config['database']} > #{sql_dump_path.call}`
end
end
desc 'delete caches not used for the given amount of days (default=7)'
task :clean, :age do |t, args|
args.with_defaults(:age => 7)
puts "Deleting DB caches not used in #{args.age} days"
db_cached_dir = File.expand_path('../../../db/cached', __FILE__)
files_deleted = 0
Dir.entries(db_cached_dir).each do |path|
next if path[0] == '.'
full_path = File.join(db_cached_dir, path)
if Time.now - File.atime(full_path) > 86400 * args.age.to_i
File.delete(full_path)
files_deleted += 1
end
end
puts "Deleted #{files_deleted} DB caches"
end
end
end
@perplexes
Copy link

Make a gem!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment