Updated README.rdoc again
[feedcatcher.git] / vendor / rails / railties / lib / tasks / databases.rake
1 namespace :db do
2 task :load_config => :rails_env do
3 require 'active_record'
4 ActiveRecord::Base.configurations = Rails::Configuration.new.database_configuration
5 end
6
7 namespace :create do
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:
12 #
13 # defaults: &defaults
14 # adapter: mysql
15 # username: root
16 # password:
17 # host: localhost
18 #
19 # development:
20 # database: blog_development
21 # <<: *defaults
22 next unless config['database']
23 # Only connect to local databases
24 local_database?(config) { create_database(config) }
25 end
26 end
27 end
28
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])
32 end
33
34 def create_database(config)
35 begin
36 if config['adapter'] =~ /sqlite/
37 if File.exist?(config['database'])
38 $stderr.puts "#{config['database']} already exists"
39 else
40 begin
41 # Create the SQLite database
42 ActiveRecord::Base.establish_connection(config)
43 ActiveRecord::Base.connection
44 rescue
45 $stderr.puts $!, *($!.backtrace)
46 $stderr.puts "Couldn't create database for #{config.inspect}"
47 end
48 end
49 return # Skip the else clause of begin/rescue
50 else
51 ActiveRecord::Base.establish_connection(config)
52 ActiveRecord::Base.connection
53 end
54 rescue
55 case config['adapter']
56 when 'mysql'
57 @charset = ENV['CHARSET'] || 'utf8'
58 @collation = ENV['COLLATION'] || 'utf8_general_ci'
59 begin
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)
63 rescue
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)"
65 end
66 when 'postgresql'
67 @encoding = config[:encoding] || ENV['CHARSET'] || 'utf8'
68 begin
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)
72 rescue
73 $stderr.puts $!, *($!.backtrace)
74 $stderr.puts "Couldn't create database for #{config.inspect}"
75 end
76 end
77 else
78 $stderr.puts "#{config['database']} already exists"
79 end
80 end
81
82 namespace :drop do
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) }
90 end
91 end
92 end
93
94 desc 'Drops the database for the current RAILS_ENV'
95 task :drop => :load_config do
96 config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
97 begin
98 drop_database(config)
99 rescue Exception => e
100 puts "Couldn't drop #{config['database']} : #{e.inspect}"
101 end
102 end
103
104 def local_database?(config, &block)
105 if %w( 127.0.0.1 localhost ).include?(config['host']) || config['host'].blank?
106 yield
107 else
108 puts "This task only modifies local databases. #{config['database']} is on a remote host."
109 end
110 end
111
112
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
118 end
119
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
123 if ENV["VERSION"]
124 Rake::Task["db:migrate:down"].invoke
125 Rake::Task["db:migrate:up"].invoke
126 else
127 Rake::Task["db:rollback"].invoke
128 Rake::Task["db:migrate"].invoke
129 end
130 end
131
132 desc 'Resets your database using your migrations for the current environment'
133 task :reset => ["db:drop", "db:create", "db:migrate"]
134
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
141 end
142
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
149 end
150 end
151
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
157 end
158
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']
161
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']
166 when 'mysql'
167 ActiveRecord::Base.establish_connection(config)
168 puts ActiveRecord::Base.connection.charset
169 when 'postgresql'
170 ActiveRecord::Base.establish_connection(config)
171 puts ActiveRecord::Base.connection.encoding
172 else
173 puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
174 end
175 end
176
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']
181 when 'mysql'
182 ActiveRecord::Base.establish_connection(config)
183 puts ActiveRecord::Base.connection.collation
184 else
185 puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
186 end
187 end
188
189 desc "Retrieves the current schema version number"
190 task :version => :environment do
191 puts "Current version: #{ActiveRecord::Migrator.current_version}"
192 end
193
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
198
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]
203 end
204 abort %{Run "rake db:migrate" to update your database then try again.}
205 end
206 end
207 end
208
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
216
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, '.*'))
219 end
220 end
221
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"
225
226 label, id = ENV["LABEL"], ENV["ID"]
227 raise "LABEL or ID required" if label.blank? && id.blank?
228
229 puts %Q(The fixture ID for "#{label}" is #{Fixtures.identify(label)}.) if label
230
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)
236
237 if key == label || key_id == id.to_i
238 puts "#{file}: #{key} (#{key_id})"
239 end
240 end
241 end
242 end
243 end
244 end
245
246 namespace :schema do
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)
252 end
253 Rake::Task["db:schema:dump"].reenable
254 end
255
256 desc "Load a schema.rb file into the database"
257 task :load => :environment do
258 file = ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb"
259 load(file)
260 end
261 end
262
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 }
271 when "postgresql"
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`
282 when "sqlserver"
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`
285 when "firebird"
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"
289 else
290 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
291 end
292
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 }
295 end
296 end
297 end
298
299 namespace :test do
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
305 end
306
307 desc "Recreate the test database from the current environment's database schema"
308 task :clone => %w(db:schema:dump db:test:load)
309
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"]
314 when "mysql"
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)
319 end
320 when "postgresql"
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`
328 when "sqlserver"
329 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
330 when "oci", "oracle"
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)
334 end
335 when "firebird"
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}"
339 else
340 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
341 end
342 end
343
344 desc "Empty the test database"
345 task :purge => :environment do
346 abcs = ActiveRecord::Base.configurations
347 case abcs["test"]["adapter"]
348 when "mysql"
349 ActiveRecord::Base.establish_connection(:test)
350 ActiveRecord::Base.connection.recreate_database(abcs["test"]["database"], abcs["test"])
351 when "postgresql"
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)
358 when "sqlserver"
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`
362 when "oci", "oracle"
363 ActiveRecord::Base.establish_connection(:test)
364 ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
365 ActiveRecord::Base.connection.execute(ddl)
366 end
367 when "firebird"
368 ActiveRecord::Base.establish_connection(:test)
369 ActiveRecord::Base.connection.recreate_database!
370 else
371 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
372 end
373 end
374
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
379 end
380 end
381 end
382
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"])
390 end
391
392 desc "Clear the sessions table"
393 task :clear => :environment do
394 ActiveRecord::Base.connection.execute "DELETE FROM #{session_table_name}"
395 end
396 end
397 end
398
399 def drop_database(config)
400 case config['adapter']
401 when 'mysql'
402 ActiveRecord::Base.establish_connection(config)
403 ActiveRecord::Base.connection.drop_database config['database']
404 when /^sqlite/
405 FileUtils.rm(File.join(RAILS_ROOT, config['database']))
406 when 'postgresql'
407 ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
408 ActiveRecord::Base.connection.drop_database config['database']
409 end
410 end
411
412 def session_table_name
413 ActiveRecord::Base.pluralize_table_names ? :sessions : :session
414 end
415
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"]
419 end
420
421 def firebird_db_string(config)
422 FireRuby::Database.db_string_for(config.symbolize_keys)
423 end