3 desc 'Create all the local databases defined in config/database.yml'
4 task :all => :environment do
5 ActiveRecord::Base.configurations.each_value do |config|
6 # Skip entries that don't have a database key, such as the first entry here:
15 # database: blog_development
17 next unless config['database']
18 # Only connect to local databases
19 if config['host'] == 'localhost' || config['host'].blank?
20 create_database(config)
22 p "This task only creates local databases. #{config['database']} is on a remote host."
28 desc 'Create the database defined in config/database.yml for the current RAILS_ENV'
29 task :create => :environment do
30 create_database(ActiveRecord::Base.configurations[RAILS_ENV])
33 def create_database(config)
35 ActiveRecord::Base.establish_connection(config)
36 ActiveRecord::Base.connection
38 case config['adapter']
40 @charset = ENV['CHARSET'] || 'utf8'
41 @collation = ENV['COLLATION'] || 'utf8_general_ci'
43 ActiveRecord::Base.establish_connection(config.merge({'database' => nil}))
44 ActiveRecord::Base.connection.create_database(config['database'], {:charset => @charset, :collation => @collation})
45 ActiveRecord::Base.establish_connection(config)
47 $stderr.puts "Couldn't create database for #{config.inspect}"
50 `createdb "#{config['database']}" -E utf8`
52 `sqlite "#{config['database']}"`
54 `sqlite3 "#{config['database']}"`
57 p "#{config['database']} already exists"
62 desc 'Drops all the local databases defined in config/database.yml'
63 task :all => :environment do
64 ActiveRecord::Base.configurations.each_value do |config|
65 # Skip entries that don't have a database key
66 next unless config['database']
67 # Only connect to local databases
68 if config['host'] == 'localhost' || config['host'].blank?
71 p "This task only drops local databases. #{config['database']} is on a remote host."
77 desc 'Drops the database for the current RAILS_ENV'
78 task :drop => :environment do
79 drop_database(ActiveRecord::Base.configurations[RAILS_ENV || 'development'])
82 desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x. Turn off output with VERBOSE=false."
83 task :migrate => :environment do
84 ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
85 ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
86 Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
89 desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
90 task :rollback => :environment do
91 step = ENV['STEP'] ? ENV['STEP'].to_i : 1
92 version = ActiveRecord::Migrator.current_version - step
93 ActiveRecord::Migrator.migrate('db/migrate/', version)
96 desc 'Drops and recreates the database from db/schema.rb for the current environment.'
97 task :reset => ['db:drop', 'db:create', 'db:schema:load']
99 desc "Retrieves the charset for the current environment's database"
100 task :charset => :environment do
101 config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
102 case config['adapter']
104 ActiveRecord::Base.establish_connection(config)
105 puts ActiveRecord::Base.connection.charset
107 puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
111 desc "Retrieves the collation for the current environment's database"
112 task :collation => :environment do
113 config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
114 case config['adapter']
116 ActiveRecord::Base.establish_connection(config)
117 puts ActiveRecord::Base.connection.collation
119 puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
123 desc "Retrieves the current schema version number"
124 task :version => :environment do
125 puts "Current version: #{ActiveRecord::Migrator.current_version}"
128 namespace :fixtures do
129 desc "Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y"
130 task :load => :environment do
131 require 'active_record/fixtures'
132 ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
133 (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir.glob(File.join(RAILS_ROOT, 'test', 'fixtures', '*.{yml,csv}'))).each do |fixture_file|
134 Fixtures.create_fixtures('test/fixtures', File.basename(fixture_file, '.*'))
140 desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
141 task :dump => :environment do
142 require 'active_record/schema_dumper'
143 File.open(ENV['SCHEMA'] || "db/schema.rb", "w") do |file|
144 ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
148 desc "Load a schema.rb file into the database"
149 task :load => :environment do
150 file = ENV['SCHEMA'] || "db/schema.rb"
155 namespace :structure do
156 desc "Dump the database structure to a SQL file"
157 task :dump => :environment do
158 abcs = ActiveRecord::Base.configurations
159 case abcs[RAILS_ENV]["adapter"]
160 when "mysql", "oci", "oracle"
161 ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
162 File.open("db/#{RAILS_ENV}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
164 ENV['PGHOST'] = abcs[RAILS_ENV]["host"] if abcs[RAILS_ENV]["host"]
165 ENV['PGPORT'] = abcs[RAILS_ENV]["port"].to_s if abcs[RAILS_ENV]["port"]
166 ENV['PGPASSWORD'] = abcs[RAILS_ENV]["password"].to_s if abcs[RAILS_ENV]["password"]
167 search_path = abcs[RAILS_ENV]["schema_search_path"]
168 search_path = "--schema=#{search_path}" if search_path
169 `pg_dump -i -U "#{abcs[RAILS_ENV]["username"]}" -s -x -O -f db/#{RAILS_ENV}_structure.sql #{search_path} #{abcs[RAILS_ENV]["database"]}`
170 raise "Error dumping database" if $?.exitstatus == 1
171 when "sqlite", "sqlite3"
172 dbfile = abcs[RAILS_ENV]["database"] || abcs[RAILS_ENV]["dbfile"]
173 `#{abcs[RAILS_ENV]["adapter"]} #{dbfile} .schema > db/#{RAILS_ENV}_structure.sql`
175 `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /f db\\#{RAILS_ENV}_structure.sql /q /A /r`
176 `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /F db\ /q /A /r`
178 set_firebird_env(abcs[RAILS_ENV])
179 db_string = firebird_db_string(abcs[RAILS_ENV])
180 sh "isql -a #{db_string} > db/#{RAILS_ENV}_structure.sql"
182 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
185 if ActiveRecord::Base.connection.supports_migrations?
186 File.open("db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
192 desc "Recreate the test database from the current environment's database schema"
193 task :clone => %w(db:schema:dump db:test:purge) do
194 ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
195 ActiveRecord::Schema.verbose = false
196 Rake::Task["db:schema:load"].invoke
200 desc "Recreate the test databases from the development structure"
201 task :clone_structure => [ "db:structure:dump", "db:test:purge" ] do
202 abcs = ActiveRecord::Base.configurations
203 case abcs["test"]["adapter"]
205 ActiveRecord::Base.establish_connection(:test)
206 ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
207 IO.readlines("db/#{RAILS_ENV}_structure.sql").join.split("\n\n").each do |table|
208 ActiveRecord::Base.connection.execute(table)
211 ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"]
212 ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"]
213 ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
214 `psql -U "#{abcs["test"]["username"]}" -f db/#{RAILS_ENV}_structure.sql #{abcs["test"]["database"]}`
215 when "sqlite", "sqlite3"
216 dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
217 `#{abcs["test"]["adapter"]} #{dbfile} < db/#{RAILS_ENV}_structure.sql`
219 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
221 ActiveRecord::Base.establish_connection(:test)
222 IO.readlines("db/#{RAILS_ENV}_structure.sql").join.split(";\n\n").each do |ddl|
223 ActiveRecord::Base.connection.execute(ddl)
226 set_firebird_env(abcs["test"])
227 db_string = firebird_db_string(abcs["test"])
228 sh "isql -i db/#{RAILS_ENV}_structure.sql #{db_string}"
230 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
234 desc "Empty the test database"
235 task :purge => :environment do
236 abcs = ActiveRecord::Base.configurations
237 case abcs["test"]["adapter"]
239 ActiveRecord::Base.establish_connection(:test)
240 ActiveRecord::Base.connection.recreate_database(abcs["test"]["database"])
242 ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"]
243 ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"]
244 ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
245 enc_option = "-E #{abcs["test"]["encoding"]}" if abcs["test"]["encoding"]
247 ActiveRecord::Base.clear_active_connections!
248 `dropdb -U "#{abcs["test"]["username"]}" #{abcs["test"]["database"]}`
249 `createdb #{enc_option} -U "#{abcs["test"]["username"]}" #{abcs["test"]["database"]}`
250 when "sqlite","sqlite3"
251 dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
252 File.delete(dbfile) if File.exist?(dbfile)
254 dropfkscript = "#{abcs["test"]["host"]}.#{abcs["test"]["database"]}.DP1".gsub(/\\/,'-')
255 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{dropfkscript}`
256 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
258 ActiveRecord::Base.establish_connection(:test)
259 ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
260 ActiveRecord::Base.connection.execute(ddl)
263 ActiveRecord::Base.establish_connection(:test)
264 ActiveRecord::Base.connection.recreate_database!
266 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
270 desc 'Prepare the test database and load the schema'
271 task :prepare => :environment do
272 if defined?(ActiveRecord::Base) && !ActiveRecord::Base.configurations.blank?
273 Rake::Task[{ :sql => "db:test:clone_structure", :ruby => "db:test:clone" }[ActiveRecord::Base.schema_format]].invoke
278 namespace :sessions do
279 desc "Creates a sessions migration for use with CGI::Session::ActiveRecordStore"
280 task :create => :environment do
281 raise "Task unavailable to this database (no migration support)" unless ActiveRecord::Base.connection.supports_migrations?
282 require 'rails_generator'
283 require 'rails_generator/scripts/generate'
284 Rails::Generator::Scripts::Generate.new.run(["session_migration", ENV["MIGRATION"] || "CreateSessions"])
287 desc "Clear the sessions table"
288 task :clear => :environment do
289 session_table = 'session'
290 session_table = Inflector.pluralize(session_table) if ActiveRecord::Base.pluralize_table_names
291 ActiveRecord::Base.connection.execute "DELETE FROM #{session_table}"
296 def drop_database(config)
297 case config['adapter']
299 ActiveRecord::Base.connection.drop_database config['database']
301 FileUtils.rm_f(File.join(RAILS_ROOT, config['database']))
303 `dropdb "#{config['database']}"`
307 def session_table_name
308 ActiveRecord::Base.pluralize_table_names ? :sessions : :session
311 def set_firebird_env(config)
312 ENV["ISC_USER"] = config["username"].to_s if config["username"]
313 ENV["ISC_PASSWORD"] = config["password"].to_s if config["password"]
316 def firebird_db_string(config)
317 FireRuby::Database.db_string_for(config.symbolize_keys)