· 7 years ago · Sep 05, 2018, 05:52 PM
1require 'active_support/core_ext/object/inclusion'
2
3db_namespace = namespace :db do
4 task :load_config => :rails_env do
5 require 'active_record'
6 ActiveRecord::Base.configurations = Rails.application.config.database_configuration
7 ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a
8
9 if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
10 if engine.paths['db/migrate'].existent
11 ActiveRecord::Migrator.migrations_paths += engine.paths['db/migrate'].to_a
12 end
13 end
14 end
15
16 namespace :create do
17 # desc 'Create all the local databases defined in config/database.yml'
18 task :all => :load_config do
19 ActiveRecord::Base.configurations.each_value do |config|
20 # Skip entries that don't have a database key, such as the first entry here:
21 #
22 # defaults: &defaults
23 # adapter: mysql
24 # username: root
25 # password:
26 # host: localhost
27 #
28 # development:
29 # database: blog_development
30 # <<: *defaults
31 next unless config['database']
32 # Only connect to local databases
33 local_database?(config) { create_database(config) }
34 end
35 end
36 end
37
38 desc 'Create the database from config/database.yml for the current Rails.env (use db:create:all to create all dbs in the config)'
39 task :create => :load_config do
40 # Make the test database at the same time as the development one, if it exists
41 if Rails.env.development? && ActiveRecord::Base.configurations['test']
42 create_database(ActiveRecord::Base.configurations['test'])
43 end
44 create_database(ActiveRecord::Base.configurations[Rails.env])
45 end
46
47 def mysql_creation_options(config)
48 @charset = ENV['CHARSET'] || 'utf8'
49 @collation = ENV['COLLATION'] || 'utf8_unicode_ci'
50 {:charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation)}
51 end
52
53 def create_database(config)
54 begin
55 if config['adapter'] =~ /sqlite/
56 if File.exist?(config['database'])
57 $stderr.puts "#{config['database']} already exists"
58 else
59 begin
60 # Create the SQLite database
61 ActiveRecord::Base.establish_connection(config)
62 ActiveRecord::Base.connection
63 rescue Exception => e
64 $stderr.puts e, *(e.backtrace)
65 $stderr.puts "Couldn't create database for #{config.inspect}"
66 end
67 end
68 return # Skip the else clause of begin/rescue
69 else
70 ActiveRecord::Base.establish_connection(config)
71 ActiveRecord::Base.connection
72 end
73 rescue
74 case config['adapter']
75 when /mysql/
76 if config['adapter'] =~ /jdbc/
77 #FIXME After Jdbcmysql gives this class
78 require 'active_record/railties/jdbcmysql_error'
79 error_class = ArJdbcMySQL::Error
80 else
81 error_class = config['adapter'] =~ /mysql2/ ? Mysql2::Error : Mysql::Error
82 end
83 access_denied_error = 1045
84 begin
85 ActiveRecord::Base.establish_connection(config.merge('database' => nil))
86 ActiveRecord::Base.connection.create_database(config['database'], mysql_creation_options(config))
87 ActiveRecord::Base.establish_connection(config)
88 rescue error_class => sqlerr
89 if sqlerr.errno == access_denied_error
90 print "#{sqlerr.error}. \nPlease provide the root password for your mysql installation\n>"
91 root_password = $stdin.gets.strip
92 grant_statement = "GRANT ALL PRIVILEGES ON #{config['database']}.* " \
93 "TO '#{config['username']}'@'localhost' " \
94 "IDENTIFIED BY '#{config['password']}' WITH GRANT OPTION;"
95 ActiveRecord::Base.establish_connection(config.merge(
96 'database' => nil, 'username' => 'root', 'password' => root_password))
97 ActiveRecord::Base.connection.create_database(config['database'], mysql_creation_options(config))
98 ActiveRecord::Base.connection.execute grant_statement
99 ActiveRecord::Base.establish_connection(config)
100 else
101 $stderr.puts sqlerr.error
102 $stderr.puts "Couldn't create database for #{config.inspect}, charset: #{config['charset'] || @charset}, collation: #{config['collation'] || @collation}"
103 $stderr.puts "(if you set the charset manually, make sure you have a matching collation)" if config['charset']
104 end
105 end
106 when /postgresql/
107 @encoding = config['encoding'] || ENV['CHARSET'] || 'utf8'
108 begin
109 ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
110 ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding))
111 ActiveRecord::Base.establish_connection(config)
112 rescue Exception => e
113 $stderr.puts e, *(e.backtrace)
114 $stderr.puts "Couldn't create database for #{config.inspect}"
115 end
116 when /ibm_db/
117 begin
118 ActiveRecord::Base.establish_connection(config.merge('dbops' => true))
119 crtSuccessful = ActiveRecord::Base.connection.create_database(config['database'],config['codeSet'], config['mode'])
120 $stderr.puts "#{config['database']} creation successful" if crtSuccessful
121 ActiveRecord::Base.establish_connection(config)
122 rescue StandardError => error
123 $stderr.puts "#{config['database']} creation process failed: #{error}"
124 end
125 end
126 else
127 # Bug with 1.9.2 Calling return within begin still executes else
128 $stderr.puts "#{config['database']} already exists" unless config['adapter'] =~ /sqlite/
129 end
130 end
131
132 namespace :drop do
133 # desc 'Drops all the local databases defined in config/database.yml'
134 task :all => :load_config do
135 ActiveRecord::Base.configurations.each_value do |config|
136 # Skip entries that don't have a database key
137 next unless config['database']
138 begin
139 # Only connect to local databases
140 local_database?(config) { drop_database(config) }
141 rescue Exception => e
142 $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}"
143 end
144 end
145 end
146 end
147
148 desc 'Drops the database for the current Rails.env (use db:drop:all to drop all databases)'
149 task :drop => :load_config do
150 config = ActiveRecord::Base.configurations[Rails.env || 'development']
151 begin
152 drop_database(config)
153 rescue Exception => e
154 $stderr.puts "Couldn't drop #{config['database']} : #{e.inspect}"
155 end
156 end
157
158 def local_database?(config, &block)
159 if config['host'].in?(['127.0.0.1', 'localhost']) || config['host'].blank? || config['adapter'].to_s =~ /ibm_db/
160 yield
161 else
162 $stderr.puts "This task only modifies local databases. #{config['database']} is on a remote host."
163 end
164 end
165
166
167 desc "Migrate the database (options: VERSION=x, VERBOSE=false)."
168 task :migrate => [:environment, :load_config] do
169 ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
170 ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
171 db_namespace["schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
172 end
173
174 namespace :migrate do
175 # desc 'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
176 task :redo => [:environment, :load_config] do
177 if ENV['VERSION']
178 db_namespace['migrate:down'].invoke
179 db_namespace['migrate:up'].invoke
180 else
181 db_namespace['rollback'].invoke
182 db_namespace['migrate'].invoke
183 end
184 end
185
186 # desc 'Resets your database using your migrations for the current environment'
187 task :reset => ['db:drop', 'db:create', 'db:migrate']
188
189 # desc 'Runs the "up" for a given migration VERSION.'
190 task :up => [:environment, :load_config] do
191 version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil
192 raise 'VERSION is required' unless version
193 ActiveRecord::Migrator.run(:up, ActiveRecord::Migrator.migrations_paths, version)
194 db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
195 end
196
197 # desc 'Runs the "down" for a given migration VERSION.'
198 task :down => [:environment, :load_config] do
199 version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil
200 raise 'VERSION is required' unless version
201 ActiveRecord::Migrator.run(:down, ActiveRecord::Migrator.migrations_paths, version)
202 db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
203 end
204
205 desc 'Display status of migrations'
206 task :status => [:environment, :load_config] do
207 config = ActiveRecord::Base.configurations[Rails.env || 'development']
208 ActiveRecord::Base.establish_connection(config)
209 unless ActiveRecord::Base.connection.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
210 puts 'Schema migrations table does not exist yet.'
211 next # means "return" for rake task
212 end
213 db_list = ActiveRecord::Base.connection.select_values("SELECT version FROM #{ActiveRecord::Migrator.schema_migrations_table_name}")
214 file_list = []
215 ActiveRecord::Migrator.migrations_paths.each do |path|
216 Dir.foreach(path) do |file|
217 # only files matching "20091231235959_some_name.rb" pattern
218 if match_data = /^(\d{14})_(.+)\.rb$/.match(file)
219 status = db_list.delete(match_data[1]) ? 'up' : 'down'
220 file_list << [status, match_data[1], match_data[2].humanize]
221 end
222 end
223 end
224 db_list.map! do |version|
225 ['up', version, '********** NO FILE **********']
226 end
227 # output
228 puts "\ndatabase: #{config['database']}\n\n"
229 puts "#{'Status'.center(8)} #{'Migration ID'.ljust(14)} Migration Name"
230 puts "-" * 50
231 (db_list + file_list).sort_by {|migration| migration[1]}.each do |migration|
232 puts "#{migration[0].center(8)} #{migration[1].ljust(14)} #{migration[2]}"
233 end
234 puts
235 end
236 end
237
238 desc 'Rolls the schema back to the previous version (specify steps w/ STEP=n).'
239 task :rollback => [:environment, :load_config] do
240 step = ENV['STEP'] ? ENV['STEP'].to_i : 1
241 ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, step)
242 db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
243 end
244
245 # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).'
246 task :forward => [:environment, :load_config] do
247 step = ENV['STEP'] ? ENV['STEP'].to_i : 1
248 ActiveRecord::Migrator.forward(ActiveRecord::Migrator.migrations_paths, step)
249 db_namespace['schema:dump'].invoke if ActiveRecord::Base.schema_format == :ruby
250 end
251
252 # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
253 task :reset => [ 'db:drop', 'db:setup' ]
254
255 # desc "Retrieves the charset for the current environment's database"
256 task :charset => :environment do
257 config = ActiveRecord::Base.configurations[Rails.env || 'development']
258 case config['adapter']
259 when /mysql/
260 ActiveRecord::Base.establish_connection(config)
261 puts ActiveRecord::Base.connection.charset
262 when /postgresql/
263 ActiveRecord::Base.establish_connection(config)
264 puts ActiveRecord::Base.connection.encoding
265 when /sqlite/
266 ActiveRecord::Base.establish_connection(config)
267 puts ActiveRecord::Base.connection.encoding
268 else
269 $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
270 end
271 end
272
273 # desc "Retrieves the collation for the current environment's database"
274 task :collation => :environment do
275 config = ActiveRecord::Base.configurations[Rails.env || 'development']
276 case config['adapter']
277 when /mysql/
278 ActiveRecord::Base.establish_connection(config)
279 puts ActiveRecord::Base.connection.collation
280 else
281 $stderr.puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
282 end
283 end
284
285 desc 'Retrieves the current schema version number'
286 task :version => :environment do
287 puts "Current version: #{ActiveRecord::Migrator.current_version}"
288 end
289
290 # desc "Raises an error if there are pending migrations"
291 task :abort_if_pending_migrations => :environment do
292 if defined? ActiveRecord
293 pending_migrations = ActiveRecord::Migrator.new(:up, ActiveRecord::Migrator.migrations_paths).pending_migrations
294
295 if pending_migrations.any?
296 puts "You have #{pending_migrations.size} pending migrations:"
297 pending_migrations.each do |pending_migration|
298 puts ' %4d %s' % [pending_migration.version, pending_migration.name]
299 end
300 abort %{Run "rake db:migrate" to update your database then try again.}
301 end
302 end
303 end
304
305 desc 'Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)'
306 task :setup => [ 'db:create', 'db:schema:load', 'db:seed' ]
307
308 desc 'Load the seed data from db/seeds.rb'
309 task :seed => 'db:abort_if_pending_migrations' do
310 Rails.application.load_seed
311 end
312
313 namespace :fixtures do
314 desc "Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
315 task :load => :environment do
316 require 'active_record/fixtures'
317
318 ActiveRecord::Base.establish_connection(Rails.env)
319 base_dir = File.join [Rails.root, ENV['FIXTURES_PATH'] || %w{test fixtures}].flatten
320 fixtures_dir = File.join [base_dir, ENV['FIXTURES_DIR']].compact
321
322 (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir["#{fixtures_dir}/**/*.{yml,csv}"].map {|f| f[(fixtures_dir.size + 1)..-5] }).each do |fixture_file|
323 ActiveRecord::Fixtures.create_fixtures(fixtures_dir, fixture_file)
324 end
325 end
326
327 # desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
328 task :identify => :environment do
329 require 'active_record/fixtures'
330
331 label, id = ENV['LABEL'], ENV['ID']
332 raise 'LABEL or ID required' if label.blank? && id.blank?
333
334 puts %Q(The fixture ID for "#{label}" is #{ActiveRecord::Fixtures.identify(label)}.) if label
335
336 base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
337 Dir["#{base_dir}/**/*.yml"].each do |file|
338 if data = YAML::load(ERB.new(IO.read(file)).result)
339 data.keys.each do |key|
340 key_id = ActiveRecord::Fixtures.identify(key)
341
342 if key == label || key_id == id.to_i
343 puts "#{file}: #{key} (#{key_id})"
344 end
345 end
346 end
347 end
348 end
349 end
350
351 namespace :schema do
352 desc 'Create a db/schema.rb file that can be portably used against any DB supported by AR'
353 task :dump => [:environment, :load_config] do
354 require 'active_record/schema_dumper'
355 filename = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
356 File.open(filename, "w:utf-8") do |file|
357 ActiveRecord::Base.establish_connection(Rails.env)
358 ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
359 end
360 db_namespace['schema:dump'].reenable
361 end
362
363 desc 'Load a schema.rb file into the database'
364 task :load => :environment do
365 file = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
366 if File.exists?(file)
367 load(file)
368 else
369 abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded}
370 end
371 end
372 end
373
374 namespace :structure do
375 desc 'Dump the database structure to an SQL file'
376 task :dump => :environment do
377 abcs = ActiveRecord::Base.configurations
378 case abcs[Rails.env]['adapter']
379 when /mysql/, 'oci', 'oracle'
380 ActiveRecord::Base.establish_connection(abcs[Rails.env])
381 File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
382 when /postgresql/
383 ENV['PGHOST'] = abcs[Rails.env]['host'] if abcs[Rails.env]['host']
384 ENV['PGPORT'] = abcs[Rails.env]["port"].to_s if abcs[Rails.env]['port']
385 ENV['PGPASSWORD'] = abcs[Rails.env]['password'].to_s if abcs[Rails.env]['password']
386 search_path = abcs[Rails.env]['schema_search_path']
387 unless search_path.blank?
388 search_path = search_path.split(",").map{|search_path| "--schema=#{search_path.strip}" }.join(" ")
389 end
390 `pg_dump -i -U "#{abcs[Rails.env]['username']}" -s -x -O -f db/#{Rails.env}_structure.sql #{search_path} #{abcs[Rails.env]['database']}`
391 raise 'Error dumping database' if $?.exitstatus == 1
392 when /sqlite/
393 dbfile = abcs[Rails.env]['database'] || abcs[Rails.env]['dbfile']
394 `sqlite3 #{dbfile} .schema > db/#{Rails.env}_structure.sql`
395 when 'sqlserver'
396 `smoscript -s #{abcs[Rails.env]['host']} -d #{abcs[Rails.env]['database']} -u #{abcs[Rails.env]['username']} -p #{abcs[Rails.env]['password']} -f db\\#{Rails.env}_structure.sql -A -U`
397 when "firebird"
398 set_firebird_env(abcs[Rails.env])
399 db_string = firebird_db_string(abcs[Rails.env])
400 sh "isql -a #{db_string} > #{Rails.root}/db/#{Rails.env}_structure.sql"
401 else
402 raise "Task not supported by '#{abcs[Rails.env]["adapter"]}'"
403 end
404
405 if ActiveRecord::Base.connection.supports_migrations?
406 File.open("#{Rails.root}/db/#{Rails.env}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
407 end
408 end
409 end
410
411 namespace :test do
412 # desc "Recreate the test database from the current schema.rb"
413 task :load => 'db:test:purge' do
414 ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
415 ActiveRecord::Schema.verbose = false
416 db_namespace['schema:load'].invoke
417 end
418
419 # desc "Recreate the test database from the current environment's database schema"
420 task :clone => %w(db:schema:dump db:test:load)
421
422 # desc "Recreate the test databases from the development structure"
423 task :clone_structure => [ 'db:structure:dump', 'db:test:purge' ] do
424 abcs = ActiveRecord::Base.configurations
425 case abcs['test']['adapter']
426 when /mysql/
427 ActiveRecord::Base.establish_connection(:test)
428 ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
429 IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split("\n\n").each do |table|
430 ActiveRecord::Base.connection.execute(table)
431 end
432 when /postgresql/
433 ENV['PGHOST'] = abcs['test']['host'] if abcs['test']['host']
434 ENV['PGPORT'] = abcs['test']['port'].to_s if abcs['test']['port']
435 ENV['PGPASSWORD'] = abcs['test']['password'].to_s if abcs['test']['password']
436 `psql -U "#{abcs['test']['username']}" -f "#{Rails.root}/db/#{Rails.env}_structure.sql" #{abcs['test']['database']} #{abcs['test']['template']}`
437 when /sqlite/
438 dbfile = abcs['test']['database'] || abcs['test']['dbfile']
439 `sqlite3 #{dbfile} < "#{Rails.root}/db/#{Rails.env}_structure.sql"`
440 when 'sqlserver'
441 `sqlcmd -S #{abcs['test']['host']} -d #{abcs['test']['database']} -U #{abcs['test']['username']} -P #{abcs['test']['password']} -i db\\#{Rails.env}_structure.sql`
442 when 'oci', 'oracle','ibm_db'
443 ActiveRecord::Base.establish_connection(:test)
444 IO.readlines("#{Rails.root}/db/#{Rails.env}_structure.sql").join.split(";\n\n").each do |ddl|
445 ActiveRecord::Base.connection.execute(ddl)
446 end
447 when 'firebird'
448 set_firebird_env(abcs['test'])
449 db_string = firebird_db_string(abcs['test'])
450 sh "isql -i #{Rails.root}/db/#{Rails.env}_structure.sql #{db_string}"
451 else
452 raise "Task not supported by '#{abcs['test']['adapter']}'"
453 end
454 end
455
456 # desc "Empty the test database"
457 task :purge => :environment do
458 abcs = ActiveRecord::Base.configurations
459 case abcs['test']['adapter']
460 when /mysql/
461 ActiveRecord::Base.establish_connection(:test)
462 ActiveRecord::Base.connection.recreate_database(abcs['test']['database'], mysql_creation_options(abcs['test']))
463 when /postgresql/
464 ActiveRecord::Base.clear_active_connections!
465 drop_database(abcs['test'])
466 create_database(abcs['test'])
467 when /sqlite/
468 dbfile = abcs['test']['database'] || abcs['test']['dbfile']
469 File.delete(dbfile) if File.exist?(dbfile)
470 when 'sqlserver'
471 test = abcs.deep_dup['test']
472 test_database = test['database']
473 test['database'] = 'master'
474 ActiveRecord::Base.establish_connection(test)
475 ActiveRecord::Base.connection.recreate_database!(test_database)
476 when "oci", "oracle"
477 ActiveRecord::Base.establish_connection(:test)
478 ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
479 ActiveRecord::Base.connection.execute(ddl)
480 end
481 when 'firebird'
482 ActiveRecord::Base.establish_connection(:test)
483 ActiveRecord::Base.connection.recreate_database!
484 when 'ibm_db'
485 drop_database(abcs['test'])
486 create_database(abcs['test'])
487 else
488 raise "Task not supported by '#{abcs['test']['adapter']}'"
489 end
490 end
491
492 # desc 'Check for pending migrations and load the test schema'
493 task :prepare => 'db:abort_if_pending_migrations' do
494 if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
495 db_namespace[{ :sql => 'test:clone_structure', :ruby => 'test:load' }[ActiveRecord::Base.schema_format]].invoke
496 end
497 end
498 end
499
500 namespace :sessions do
501 # desc "Creates a sessions migration for use with ActiveRecord::SessionStore"
502 task :create => :environment do
503 raise 'Task unavailable to this database (no migration support)' unless ActiveRecord::Base.connection.supports_migrations?
504 require 'rails/generators'
505 Rails::Generators.configure!
506 require 'rails/generators/rails/session_migration/session_migration_generator'
507 Rails::Generators::SessionMigrationGenerator.start [ ENV['MIGRATION'] || 'add_sessions_table' ]
508 end
509
510 # desc "Clear the sessions table"
511 task :clear => :environment do
512 ActiveRecord::Base.connection.execute "DELETE FROM #{session_table_name}"
513 end
514 end
515end
516
517namespace :railties do
518 namespace :install do
519 # desc "Copies missing migrations from Railties (e.g. plugins, engines). You can specify Railties to use with FROM=railtie1,railtie2"
520 task :migrations => :'db:load_config' do
521 to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map {|n| n.strip }
522 railties = ActiveSupport::OrderedHash.new
523 Rails.application.railties.all do |railtie|
524 next unless to_load == :all || to_load.include?(railtie.railtie_name)
525
526 if railtie.respond_to?(:paths) && (path = railtie.paths['db/migrate'].first)
527 railties[railtie.railtie_name] = path
528 end
529 end
530
531 on_skip = Proc.new do |name, migration|
532 puts "NOTE: Migration #{migration.basename} from #{name} has been skipped. Migration with the same name already exists."
533 end
534
535 on_copy = Proc.new do |name, migration, old_path|
536 puts "Copied migration #{migration.basename} from #{name}"
537 end
538
539 ActiveRecord::Migration.copy( ActiveRecord::Migrator.migrations_paths.first, railties,
540 :on_skip => on_skip, :on_copy => on_copy)
541 end
542 end
543end
544
545task 'test:prepare' => 'db:test:prepare'
546
547def drop_database(config)
548 case config['adapter']
549 when /mysql/
550 ActiveRecord::Base.establish_connection(config)
551 ActiveRecord::Base.connection.drop_database config['database']
552 when /sqlite/
553 require 'pathname'
554 path = Pathname.new(config['database'])
555 file = path.absolute? ? path.to_s : File.join(Rails.root, path)
556
557 FileUtils.rm(file)
558 when /postgresql/
559 ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
560 ActiveRecord::Base.connection.drop_database config['database']
561 when /ibm_db/
562 ActiveRecord::Base.establish_connection(config.merge('dbops' => true))
563 drpSuccessful = ActiveRecord::Base.connection.drop_database config['database']
564 $stderr.puts "#{config['database']} drop successful" if drpSuccessful
565 ActiveRecord::Base.connection.disconnect!
566 drpSuccessful
567 end
568end
569
570def session_table_name
571 ActiveRecord::SessionStore::Session.table_name
572end
573
574def set_firebird_env(config)
575 ENV['ISC_USER'] = config['username'].to_s if config['username']
576 ENV['ISC_PASSWORD'] = config['password'].to_s if config['password']
577end
578
579def firebird_db_string(config)
580 FireRuby::Database.db_string_for(config.symbolize_keys)
581end