1 def redefine_task(*args, &block)
2 task_name = Hash === args.first ? args.first.keys[0] : args.first
3 existing_task = Rake.application.lookup task_name
5 class << existing_task; public :instance_variable_set; end
6 existing_task.instance_variable_set "@prerequisites", FileList[]
7 existing_task.instance_variable_set "@actions", []
13 if Rake::Task["db:create"]
14 redefine_task :create => :environment do
15 create_database(ActiveRecord::Base.configurations[RAILS_ENV])
18 class << self; alias_method :previous_create_database, :create_database; end
19 def create_database(config)
21 ActiveRecord::Base.establish_connection(config)
22 ActiveRecord::Base.connection
32 ActiveRecord::Base.establish_connection(config.merge({'database' => nil, 'url' => url}))
33 ActiveRecord::Base.connection.create_database(config['database'])
34 ActiveRecord::Base.establish_connection(config)
36 previous_create_database(config)
41 redefine_task :drop => :environment do
42 config = ActiveRecord::Base.configurations[RAILS_ENV]
44 ActiveRecord::Base.establish_connection(config)
45 db = ActiveRecord::Base.connection.database_name
46 ActiveRecord::Base.connection.drop_database(db)
53 namespace :structure do
54 redefine_task :dump => :environment do
55 abcs = ActiveRecord::Base.configurations
56 ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
57 File.open("db/#{RAILS_ENV}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
58 if ActiveRecord::Base.connection.supports_migrations?
59 File.open("db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
65 redefine_task :clone_structure => [ "db:structure:dump", "db:test:purge" ] do
66 abcs = ActiveRecord::Base.configurations
67 abcs['test']['pg_params'] = '?allowEncodingChanges=true' if abcs['test']['adapter'] =~ /postgresql/i
68 ActiveRecord::Base.establish_connection(abcs["test"])
69 ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0') if abcs["test"]["adapter"] =~ /mysql/i
70 IO.readlines("db/#{RAILS_ENV}_structure.sql").join.split(";\n\n").each do |ddl|
71 ActiveRecord::Base.connection.execute(ddl.chomp(';'))
75 redefine_task :purge => :environment do
76 abcs = ActiveRecord::Base.configurations
77 config = abcs['test'].dup
78 if config['adapter'] =~ /postgresql/i
80 db = config['url'][/\/([^\/]*)$/, 1]
81 config['url'][/\/([^\/]*)$/, 1] if db_name
83 db = config['database']
84 config['database'] = 'postgres'
86 ActiveRecord::Base.establish_connection(config)
88 ActiveRecord::Base.establish_connection(config)
89 db = ActiveRecord::Base.connection.database_name
91 ActiveRecord::Base.connection.recreate_database(db)