2 task :load_config => :rails_env do
3 require 'active_record'
4 ActiveRecord::Base.configurations = Rails::Configuration.new.database_configuration
8 desc 'Create all the local databases defined in config/database.yml'
9 task :all => :load_config do
10 ActiveRecord::Base.configurations.each_value do |config|
11 # Skip entries that don't have a database key, such as the first entry here:
20 # database: blog_development
22 next unless config['database']
23 # Only connect to local databases
24 local_database?(config) { create_database(config) }
29 desc 'Create the database defined in config/database.yml for the current RAILS_ENV'
30 task :create => :load_config do
31 create_database(ActiveRecord::Base.configurations[RAILS_ENV])
34 def create_database(config)
36 if config['adapter'] =~ /sqlite/
37 if File.exist?(config['database'])
38 $stderr.puts "#{config['database']} already exists"
41 # Create the SQLite database
42 ActiveRecord::Base.establish_connection(config)
43 ActiveRecord::Base.connection
45 $stderr.puts $!, *($!.backtrace)
46 $stderr.puts "Couldn't create database for #{config.inspect}"
49 return # Skip the else clause of begin/rescue
51 ActiveRecord::Base.establish_connection(config)
52 ActiveRecord::Base.connection
55 case config['adapter']
57 @charset = ENV['CHARSET'] || 'utf8'
58 @collation = ENV['COLLATION'] || 'utf8_general_ci'
60 ActiveRecord::Base.establish_connection(config.merge('database' => nil))
61 ActiveRecord::Base.connection.create_database(config['database'], :charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation))
62 ActiveRecord::Base.establish_connection(config)
64 $stderr.puts "Couldn't create database for #{config.inspect}, charset: #{config['charset'] || @charset}, collation: #{config['collation'] || @collation} (if you set the charset manually, make sure you have a matching collation)"
67 @encoding = config[:encoding] || ENV['CHARSET'] || 'utf8'
69 ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
70 ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding))
71 ActiveRecord::Base.establish_connection(config)
73 $stderr.puts $!, *($!.backtrace)
74 $stderr.puts "Couldn't create database for #{config.inspect}"
78 $stderr.puts "#{config['database']} already exists"
83 desc 'Drops all the local databases defined in config/database.yml'
84 task :all => :load_config do
85 ActiveRecord::Base.configurations.each_value do |config|
86 # Skip entries that don't have a database key
87 next unless config['database']
88 # Only connect to local databases
89 local_database?(config) { drop_database(config) }
94 desc 'Drops the database for the current RAILS_ENV'
95 task :drop => :load_config do
96 config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
100 puts "Couldn't drop #{config['database']} : #{e.inspect}"
104 def local_database?(config, &block)
105 if %w( 127.0.0.1 localhost ).include?(config['host']) || config['host'].blank?
108 puts "This task only modifies local databases. #{config['database']} is on a remote host."
113 desc "Migrate the database through scripts in db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false."
114 task :migrate => :environment do
115 ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
116 ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
117 Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
120 namespace :migrate do
121 desc 'Rollbacks the database one migration and re migrate up. If you want to rollback more than one step, define STEP=x. Target specific version with VERSION=x.'
122 task :redo => :environment do
124 Rake::Task["db:migrate:down"].invoke
125 Rake::Task["db:migrate:up"].invoke
127 Rake::Task["db:rollback"].invoke
128 Rake::Task["db:migrate"].invoke
132 desc 'Resets your database using your migrations for the current environment'
133 task :reset => ["db:drop", "db:create", "db:migrate"]
135 desc 'Runs the "up" for a given migration VERSION.'
136 task :up => :environment do
137 version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
138 raise "VERSION is required" unless version
139 ActiveRecord::Migrator.run(:up, "db/migrate/", version)
140 Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
143 desc 'Runs the "down" for a given migration VERSION.'
144 task :down => :environment do
145 version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
146 raise "VERSION is required" unless version
147 ActiveRecord::Migrator.run(:down, "db/migrate/", version)
148 Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
152 desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
153 task :rollback => :environment do
154 step = ENV['STEP'] ? ENV['STEP'].to_i : 1
155 ActiveRecord::Migrator.rollback('db/migrate/', step)
156 Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
159 desc 'Drops and recreates the database from db/schema.rb for the current environment.'
160 task :reset => ['db:drop', 'db:create', 'db:schema:load']
162 desc "Retrieves the charset for the current environment's database"
163 task :charset => :environment do
164 config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
165 case config['adapter']
167 ActiveRecord::Base.establish_connection(config)
168 puts ActiveRecord::Base.connection.charset
170 ActiveRecord::Base.establish_connection(config)
171 puts ActiveRecord::Base.connection.encoding
173 puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
177 desc "Retrieves the collation for the current environment's database"
178 task :collation => :environment do
179 config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
180 case config['adapter']
182 ActiveRecord::Base.establish_connection(config)
183 puts ActiveRecord::Base.connection.collation
185 puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
189 desc "Retrieves the current schema version number"
190 task :version => :environment do
191 puts "Current version: #{ActiveRecord::Migrator.current_version}"
194 desc "Raises an error if there are pending migrations"
195 task :abort_if_pending_migrations => :environment do
196 if defined? ActiveRecord
197 pending_migrations = ActiveRecord::Migrator.new(:up, 'db/migrate').pending_migrations
199 if pending_migrations.any?
200 puts "You have #{pending_migrations.size} pending migrations:"
201 pending_migrations.each do |pending_migration|
202 puts ' %4d %s' % [pending_migration.version, pending_migration.name]
204 abort %{Run "rake db:migrate" to update your database then try again.}
209 namespace :fixtures do
210 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."
211 task :load => :environment do
212 require 'active_record/fixtures'
213 ActiveRecord::Base.establish_connection(Rails.env)
214 base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
215 fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir
217 (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file|
218 Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*'))
222 desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
223 task :identify => :environment do
224 require "active_record/fixtures"
226 label, id = ENV["LABEL"], ENV["ID"]
227 raise "LABEL or ID required" if label.blank? && id.blank?
229 puts %Q(The fixture ID for "#{label}" is #{Fixtures.identify(label)}.) if label
231 base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
232 Dir["#{base_dir}/**/*.yml"].each do |file|
233 if data = YAML::load(ERB.new(IO.read(file)).result)
234 data.keys.each do |key|
235 key_id = Fixtures.identify(key)
237 if key == label || key_id == id.to_i
238 puts "#{file}: #{key} (#{key_id})"
247 desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
248 task :dump => :environment do
249 require 'active_record/schema_dumper'
250 File.open(ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb", "w") do |file|
251 ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
253 Rake::Task["db:schema:dump"].reenable
256 desc "Load a schema.rb file into the database"
257 task :load => :environment do
258 file = ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb"
263 namespace :structure do
264 desc "Dump the database structure to a SQL file"
265 task :dump => :environment do
266 abcs = ActiveRecord::Base.configurations
267 case abcs[RAILS_ENV]["adapter"]
268 when "mysql", "oci", "oracle"
269 ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
270 File.open("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
272 ENV['PGHOST'] = abcs[RAILS_ENV]["host"] if abcs[RAILS_ENV]["host"]
273 ENV['PGPORT'] = abcs[RAILS_ENV]["port"].to_s if abcs[RAILS_ENV]["port"]
274 ENV['PGPASSWORD'] = abcs[RAILS_ENV]["password"].to_s if abcs[RAILS_ENV]["password"]
275 search_path = abcs[RAILS_ENV]["schema_search_path"]
276 search_path = "--schema=#{search_path}" if search_path
277 `pg_dump -i -U "#{abcs[RAILS_ENV]["username"]}" -s -x -O -f db/#{RAILS_ENV}_structure.sql #{search_path} #{abcs[RAILS_ENV]["database"]}`
278 raise "Error dumping database" if $?.exitstatus == 1
279 when "sqlite", "sqlite3"
280 dbfile = abcs[RAILS_ENV]["database"] || abcs[RAILS_ENV]["dbfile"]
281 `#{abcs[RAILS_ENV]["adapter"]} #{dbfile} .schema > db/#{RAILS_ENV}_structure.sql`
283 `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /f db\\#{RAILS_ENV}_structure.sql /q /A /r`
284 `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /F db\ /q /A /r`
286 set_firebird_env(abcs[RAILS_ENV])
287 db_string = firebird_db_string(abcs[RAILS_ENV])
288 sh "isql -a #{db_string} > #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql"
290 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
293 if ActiveRecord::Base.connection.supports_migrations?
294 File.open("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
300 desc "Recreate the test database from the current schema.rb"
301 task :load => 'db:test:purge' do
302 ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
303 ActiveRecord::Schema.verbose = false
304 Rake::Task["db:schema:load"].invoke
307 desc "Recreate the test database from the current environment's database schema"
308 task :clone => %w(db:schema:dump db:test:load)
310 desc "Recreate the test databases from the development structure"
311 task :clone_structure => [ "db:structure:dump", "db:test:purge" ] do
312 abcs = ActiveRecord::Base.configurations
313 case abcs["test"]["adapter"]
315 ActiveRecord::Base.establish_connection(:test)
316 ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
317 IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql").join.split("\n\n").each do |table|
318 ActiveRecord::Base.connection.execute(table)
321 ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"]
322 ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"]
323 ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
324 `psql -U "#{abcs["test"]["username"]}" -f #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql #{abcs["test"]["database"]}`
325 when "sqlite", "sqlite3"
326 dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
327 `#{abcs["test"]["adapter"]} #{dbfile} < #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql`
329 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
331 ActiveRecord::Base.establish_connection(:test)
332 IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql").join.split(";\n\n").each do |ddl|
333 ActiveRecord::Base.connection.execute(ddl)
336 set_firebird_env(abcs["test"])
337 db_string = firebird_db_string(abcs["test"])
338 sh "isql -i #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql #{db_string}"
340 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
344 desc "Empty the test database"
345 task :purge => :environment do
346 abcs = ActiveRecord::Base.configurations
347 case abcs["test"]["adapter"]
349 ActiveRecord::Base.establish_connection(:test)
350 ActiveRecord::Base.connection.recreate_database(abcs["test"]["database"], abcs["test"])
352 ActiveRecord::Base.clear_active_connections!
353 drop_database(abcs['test'])
354 create_database(abcs['test'])
355 when "sqlite","sqlite3"
356 dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
357 File.delete(dbfile) if File.exist?(dbfile)
359 dropfkscript = "#{abcs["test"]["host"]}.#{abcs["test"]["database"]}.DP1".gsub(/\\/,'-')
360 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{dropfkscript}`
361 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
363 ActiveRecord::Base.establish_connection(:test)
364 ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
365 ActiveRecord::Base.connection.execute(ddl)
368 ActiveRecord::Base.establish_connection(:test)
369 ActiveRecord::Base.connection.recreate_database!
371 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
375 desc 'Check for pending migrations and load the test schema'
376 task :prepare => 'db:abort_if_pending_migrations' do
377 if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
378 Rake::Task[{ :sql => "db:test:clone_structure", :ruby => "db:test:load" }[ActiveRecord::Base.schema_format]].invoke
383 namespace :sessions do
384 desc "Creates a sessions migration for use with ActiveRecord::SessionStore"
385 task :create => :environment do
386 raise "Task unavailable to this database (no migration support)" unless ActiveRecord::Base.connection.supports_migrations?
387 require 'rails_generator'
388 require 'rails_generator/scripts/generate'
389 Rails::Generator::Scripts::Generate.new.run(["session_migration", ENV["MIGRATION"] || "CreateSessions"])
392 desc "Clear the sessions table"
393 task :clear => :environment do
394 ActiveRecord::Base.connection.execute "DELETE FROM #{session_table_name}"
399 def drop_database(config)
400 case config['adapter']
402 ActiveRecord::Base.establish_connection(config)
403 ActiveRecord::Base.connection.drop_database config['database']
405 FileUtils.rm(File.join(RAILS_ROOT, config['database']))
407 ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
408 ActiveRecord::Base.connection.drop_database config['database']
412 def session_table_name
413 ActiveRecord::Base.pluralize_table_names ? :sessions : :session
416 def set_firebird_env(config)
417 ENV["ISC_USER"] = config["username"].to_s if config["username"]
418 ENV["ISC_PASSWORD"] = config["password"].to_s if config["password"]
421 def firebird_db_string(config)
422 FireRuby::Database.db_string_for(config.symbolize_keys)