Froze rails gems
[depot.git] / vendor / rails / railties / lib / tasks / databases.rake
1 namespace :db do
2 namespace :create do
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:
7 #
8 # defaults: &defaults
9 # adapter: mysql
10 # username: root
11 # password:
12 # host: localhost
13 #
14 # development:
15 # database: blog_development
16 # <<: *defaults
17 next unless config['database']
18 # Only connect to local databases
19 local_database?(config) { create_database(config) }
20 end
21 end
22 end
23
24 desc 'Create the database defined in config/database.yml for the current RAILS_ENV'
25 task :create => :environment do
26 create_database(ActiveRecord::Base.configurations[RAILS_ENV])
27 end
28
29 def create_database(config)
30 begin
31 if config['adapter'] =~ /sqlite/
32 if File.exist?(config['database'])
33 $stderr.puts "#{config['database']} already exists"
34 else
35 begin
36 # Create the SQLite database
37 ActiveRecord::Base.establish_connection(config)
38 ActiveRecord::Base.connection
39 rescue
40 $stderr.puts $!, *($!.backtrace)
41 $stderr.puts "Couldn't create database for #{config.inspect}"
42 end
43 end
44 return # Skip the else clause of begin/rescue
45 else
46 ActiveRecord::Base.establish_connection(config)
47 ActiveRecord::Base.connection
48 end
49 rescue
50 case config['adapter']
51 when 'mysql'
52 @charset = ENV['CHARSET'] || 'utf8'
53 @collation = ENV['COLLATION'] || 'utf8_general_ci'
54 begin
55 ActiveRecord::Base.establish_connection(config.merge('database' => nil))
56 ActiveRecord::Base.connection.create_database(config['database'], :charset => (config['charset'] || @charset), :collation => (config['collation'] || @collation))
57 ActiveRecord::Base.establish_connection(config)
58 rescue
59 $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)"
60 end
61 when 'postgresql'
62 @encoding = config[:encoding] || ENV['CHARSET'] || 'utf8'
63 begin
64 ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
65 ActiveRecord::Base.connection.create_database(config['database'], config.merge('encoding' => @encoding))
66 ActiveRecord::Base.establish_connection(config)
67 rescue
68 $stderr.puts $!, *($!.backtrace)
69 $stderr.puts "Couldn't create database for #{config.inspect}"
70 end
71 end
72 else
73 $stderr.puts "#{config['database']} already exists"
74 end
75 end
76
77 namespace :drop do
78 desc 'Drops all the local databases defined in config/database.yml'
79 task :all => :environment do
80 ActiveRecord::Base.configurations.each_value do |config|
81 # Skip entries that don't have a database key
82 next unless config['database']
83 # Only connect to local databases
84 local_database?(config) { drop_database(config) }
85 end
86 end
87 end
88
89 desc 'Drops the database for the current RAILS_ENV'
90 task :drop => :environment do
91 config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
92 begin
93 drop_database(config)
94 rescue Exception => e
95 puts "Couldn't drop #{config['database']} : #{e.inspect}"
96 end
97 end
98
99 def local_database?(config, &block)
100 if %w( 127.0.0.1 localhost ).include?(config['host']) || config['host'].blank?
101 yield
102 else
103 puts "This task only modifies local databases. #{config['database']} is on a remote host."
104 end
105 end
106
107
108 desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x. Turn off output with VERBOSE=false."
109 task :migrate => :environment do
110 ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
111 ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
112 Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
113 end
114
115 namespace :migrate do
116 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.'
117 task :redo => :environment do
118 if ENV["VERSION"]
119 Rake::Task["db:migrate:down"].invoke
120 Rake::Task["db:migrate:up"].invoke
121 else
122 Rake::Task["db:rollback"].invoke
123 Rake::Task["db:migrate"].invoke
124 end
125 end
126
127 desc 'Resets your database using your migrations for the current environment'
128 task :reset => ["db:drop", "db:create", "db:migrate"]
129
130 desc 'Runs the "up" for a given migration VERSION.'
131 task :up => :environment do
132 version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
133 raise "VERSION is required" unless version
134 ActiveRecord::Migrator.run(:up, "db/migrate/", version)
135 Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
136 end
137
138 desc 'Runs the "down" for a given migration VERSION.'
139 task :down => :environment do
140 version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
141 raise "VERSION is required" unless version
142 ActiveRecord::Migrator.run(:down, "db/migrate/", version)
143 Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
144 end
145 end
146
147 desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
148 task :rollback => :environment do
149 step = ENV['STEP'] ? ENV['STEP'].to_i : 1
150 ActiveRecord::Migrator.rollback('db/migrate/', step)
151 Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
152 end
153
154 desc 'Drops and recreates the database from db/schema.rb for the current environment.'
155 task :reset => ['db:drop', 'db:create', 'db:schema:load']
156
157 desc "Retrieves the charset for the current environment's database"
158 task :charset => :environment do
159 config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
160 case config['adapter']
161 when 'mysql'
162 ActiveRecord::Base.establish_connection(config)
163 puts ActiveRecord::Base.connection.charset
164 when 'postgresql'
165 ActiveRecord::Base.establish_connection(config)
166 puts ActiveRecord::Base.connection.encoding
167 else
168 puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
169 end
170 end
171
172 desc "Retrieves the collation for the current environment's database"
173 task :collation => :environment do
174 config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
175 case config['adapter']
176 when 'mysql'
177 ActiveRecord::Base.establish_connection(config)
178 puts ActiveRecord::Base.connection.collation
179 else
180 puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
181 end
182 end
183
184 desc "Retrieves the current schema version number"
185 task :version => :environment do
186 puts "Current version: #{ActiveRecord::Migrator.current_version}"
187 end
188
189 desc "Raises an error if there are pending migrations"
190 task :abort_if_pending_migrations => :environment do
191 if defined? ActiveRecord
192 pending_migrations = ActiveRecord::Migrator.new(:up, 'db/migrate').pending_migrations
193
194 if pending_migrations.any?
195 puts "You have #{pending_migrations.size} pending migrations:"
196 pending_migrations.each do |pending_migration|
197 puts ' %4d %s' % [pending_migration.version, pending_migration.name]
198 end
199 abort %{Run "rake db:migrate" to update your database then try again.}
200 end
201 end
202 end
203
204 namespace :fixtures do
205 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."
206 task :load => :environment do
207 require 'active_record/fixtures'
208 ActiveRecord::Base.establish_connection(Rails.env)
209 base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
210 fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir
211
212 (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file|
213 Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*'))
214 end
215 end
216
217 desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
218 task :identify => :environment do
219 require "active_record/fixtures"
220
221 label, id = ENV["LABEL"], ENV["ID"]
222 raise "LABEL or ID required" if label.blank? && id.blank?
223
224 puts %Q(The fixture ID for "#{label}" is #{Fixtures.identify(label)}.) if label
225
226 base_dir = ENV['FIXTURES_PATH'] ? File.join(Rails.root, ENV['FIXTURES_PATH']) : File.join(Rails.root, 'test', 'fixtures')
227 Dir["#{base_dir}/**/*.yml"].each do |file|
228 if data = YAML::load(ERB.new(IO.read(file)).result)
229 data.keys.each do |key|
230 key_id = Fixtures.identify(key)
231
232 if key == label || key_id == id.to_i
233 puts "#{file}: #{key} (#{key_id})"
234 end
235 end
236 end
237 end
238 end
239 end
240
241 namespace :schema do
242 desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
243 task :dump => :environment do
244 require 'active_record/schema_dumper'
245 File.open(ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb", "w") do |file|
246 ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
247 end
248 end
249
250 desc "Load a schema.rb file into the database"
251 task :load => :environment do
252 file = ENV['SCHEMA'] || "#{RAILS_ROOT}/db/schema.rb"
253 load(file)
254 end
255 end
256
257 namespace :structure do
258 desc "Dump the database structure to a SQL file"
259 task :dump => :environment do
260 abcs = ActiveRecord::Base.configurations
261 case abcs[RAILS_ENV]["adapter"]
262 when "mysql", "oci", "oracle"
263 ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
264 File.open("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
265 when "postgresql"
266 ENV['PGHOST'] = abcs[RAILS_ENV]["host"] if abcs[RAILS_ENV]["host"]
267 ENV['PGPORT'] = abcs[RAILS_ENV]["port"].to_s if abcs[RAILS_ENV]["port"]
268 ENV['PGPASSWORD'] = abcs[RAILS_ENV]["password"].to_s if abcs[RAILS_ENV]["password"]
269 search_path = abcs[RAILS_ENV]["schema_search_path"]
270 search_path = "--schema=#{search_path}" if search_path
271 `pg_dump -i -U "#{abcs[RAILS_ENV]["username"]}" -s -x -O -f db/#{RAILS_ENV}_structure.sql #{search_path} #{abcs[RAILS_ENV]["database"]}`
272 raise "Error dumping database" if $?.exitstatus == 1
273 when "sqlite", "sqlite3"
274 dbfile = abcs[RAILS_ENV]["database"] || abcs[RAILS_ENV]["dbfile"]
275 `#{abcs[RAILS_ENV]["adapter"]} #{dbfile} .schema > db/#{RAILS_ENV}_structure.sql`
276 when "sqlserver"
277 `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /f db\\#{RAILS_ENV}_structure.sql /q /A /r`
278 `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /F db\ /q /A /r`
279 when "firebird"
280 set_firebird_env(abcs[RAILS_ENV])
281 db_string = firebird_db_string(abcs[RAILS_ENV])
282 sh "isql -a #{db_string} > #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql"
283 else
284 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
285 end
286
287 if ActiveRecord::Base.connection.supports_migrations?
288 File.open("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
289 end
290 end
291 end
292
293 namespace :test do
294 desc "Recreate the test database from the current schema.rb"
295 task :load => 'db:test:purge' do
296 ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
297 ActiveRecord::Schema.verbose = false
298 Rake::Task["db:schema:load"].invoke
299 end
300
301 desc "Recreate the test database from the current environment's database schema"
302 task :clone => %w(db:schema:dump db:test:load)
303
304 desc "Recreate the test databases from the development structure"
305 task :clone_structure => [ "db:structure:dump", "db:test:purge" ] do
306 abcs = ActiveRecord::Base.configurations
307 case abcs["test"]["adapter"]
308 when "mysql"
309 ActiveRecord::Base.establish_connection(:test)
310 ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
311 IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql").join.split("\n\n").each do |table|
312 ActiveRecord::Base.connection.execute(table)
313 end
314 when "postgresql"
315 ENV['PGHOST'] = abcs["test"]["host"] if abcs["test"]["host"]
316 ENV['PGPORT'] = abcs["test"]["port"].to_s if abcs["test"]["port"]
317 ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
318 `psql -U "#{abcs["test"]["username"]}" -f #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql #{abcs["test"]["database"]}`
319 when "sqlite", "sqlite3"
320 dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
321 `#{abcs["test"]["adapter"]} #{dbfile} < #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql`
322 when "sqlserver"
323 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
324 when "oci", "oracle"
325 ActiveRecord::Base.establish_connection(:test)
326 IO.readlines("#{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql").join.split(";\n\n").each do |ddl|
327 ActiveRecord::Base.connection.execute(ddl)
328 end
329 when "firebird"
330 set_firebird_env(abcs["test"])
331 db_string = firebird_db_string(abcs["test"])
332 sh "isql -i #{RAILS_ROOT}/db/#{RAILS_ENV}_structure.sql #{db_string}"
333 else
334 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
335 end
336 end
337
338 desc "Empty the test database"
339 task :purge => :environment do
340 abcs = ActiveRecord::Base.configurations
341 case abcs["test"]["adapter"]
342 when "mysql"
343 ActiveRecord::Base.establish_connection(:test)
344 ActiveRecord::Base.connection.recreate_database(abcs["test"]["database"], abcs["test"])
345 when "postgresql"
346 ActiveRecord::Base.clear_active_connections!
347 drop_database(abcs['test'])
348 create_database(abcs['test'])
349 when "sqlite","sqlite3"
350 dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
351 File.delete(dbfile) if File.exist?(dbfile)
352 when "sqlserver"
353 dropfkscript = "#{abcs["test"]["host"]}.#{abcs["test"]["database"]}.DP1".gsub(/\\/,'-')
354 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{dropfkscript}`
355 `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
356 when "oci", "oracle"
357 ActiveRecord::Base.establish_connection(:test)
358 ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
359 ActiveRecord::Base.connection.execute(ddl)
360 end
361 when "firebird"
362 ActiveRecord::Base.establish_connection(:test)
363 ActiveRecord::Base.connection.recreate_database!
364 else
365 raise "Task not supported by '#{abcs["test"]["adapter"]}'"
366 end
367 end
368
369 desc 'Check for pending migrations and load the test schema'
370 task :prepare => 'db:abort_if_pending_migrations' do
371 if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
372 Rake::Task[{ :sql => "db:test:clone_structure", :ruby => "db:test:load" }[ActiveRecord::Base.schema_format]].invoke
373 end
374 end
375 end
376
377 namespace :sessions do
378 desc "Creates a sessions migration for use with CGI::Session::ActiveRecordStore"
379 task :create => :environment do
380 raise "Task unavailable to this database (no migration support)" unless ActiveRecord::Base.connection.supports_migrations?
381 require 'rails_generator'
382 require 'rails_generator/scripts/generate'
383 Rails::Generator::Scripts::Generate.new.run(["session_migration", ENV["MIGRATION"] || "CreateSessions"])
384 end
385
386 desc "Clear the sessions table"
387 task :clear => :environment do
388 ActiveRecord::Base.connection.execute "DELETE FROM #{session_table_name}"
389 end
390 end
391 end
392
393 def drop_database(config)
394 case config['adapter']
395 when 'mysql'
396 ActiveRecord::Base.connection.drop_database config['database']
397 when /^sqlite/
398 FileUtils.rm(File.join(RAILS_ROOT, config['database']))
399 when 'postgresql'
400 ActiveRecord::Base.establish_connection(config.merge('database' => 'postgres', 'schema_search_path' => 'public'))
401 ActiveRecord::Base.connection.drop_database config['database']
402 end
403 end
404
405 def session_table_name
406 ActiveRecord::Base.pluralize_table_names ? :sessions : :session
407 end
408
409 def set_firebird_env(config)
410 ENV["ISC_USER"] = config["username"].to_s if config["username"]
411 ENV["ISC_PASSWORD"] = config["password"].to_s if config["password"]
412 end
413
414 def firebird_db_string(config)
415 FireRuby::Database.db_string_for(config.symbolize_keys)
416 end