Upgraded Rails and RSpec
[monkeycharger.git] / vendor / rails / railties / lib / tasks / databases.rake
blob056415c50124472295007e1fa2406f305a601ce3
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         if config['host'] == 'localhost' || config['host'].blank?
20           create_database(config)
21         else
22           p "This task only creates local databases. #{config['database']} is on a remote host."
23         end
24       end
25     end
26   end
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])
31   end
33   def create_database(config)
34     begin
35       ActiveRecord::Base.establish_connection(config)
36       ActiveRecord::Base.connection
37     rescue
38       case config['adapter']
39       when 'mysql'
40         @charset   = ENV['CHARSET']   || 'utf8'
41         @collation = ENV['COLLATION'] || 'utf8_general_ci'
42         begin
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)
46         rescue
47           $stderr.puts "Couldn't create database for #{config.inspect}"
48         end
49       when 'postgresql'
50         `createdb "#{config['database']}" -E utf8`
51       when 'sqlite'
52         `sqlite "#{config['database']}"`
53       when 'sqlite3'
54         `sqlite3 "#{config['database']}"`
55       end
56     else
57       p "#{config['database']} already exists"
58     end
59   end
61   namespace :drop do
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?
69           drop_database(config)
70         else
71           p "This task only drops local databases. #{config['database']} is on a remote host."
72         end
73       end
74     end
75   end
77   desc 'Drops the database for the current RAILS_ENV'
78   task :drop => :environment do
79     drop_database(ActiveRecord::Base.configurations[RAILS_ENV || 'development'])
80   end
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
87   end
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)
94   end
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']
103     when 'mysql'
104       ActiveRecord::Base.establish_connection(config)
105       puts ActiveRecord::Base.connection.charset
106     else
107       puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
108     end
109   end
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']
115     when 'mysql'
116       ActiveRecord::Base.establish_connection(config)
117       puts ActiveRecord::Base.connection.collation
118     else
119       puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
120     end
121   end
123   desc "Retrieves the current schema version number"
124   task :version => :environment do
125     puts "Current version: #{ActiveRecord::Migrator.current_version}"
126   end
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, '.*'))
135       end
136     end
137   end
139   namespace :schema do
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)
145       end
146     end
148     desc "Load a schema.rb file into the database"
149     task :load => :environment do
150       file = ENV['SCHEMA'] || "db/schema.rb"
151       load(file)
152     end
153   end
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 }
163       when "postgresql"
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`
174       when "sqlserver"
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`
177       when "firebird"
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"
181       else
182         raise "Task not supported by '#{abcs["test"]["adapter"]}'"
183       end
185       if ActiveRecord::Base.connection.supports_migrations?
186         File.open("db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
187       end
188     end
189   end
191   namespace :test do
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
197     end
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"]
204       when "mysql"
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)
209         end
210       when "postgresql"
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`
218       when "sqlserver"
219         `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
220       when "oci", "oracle"
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)
224         end
225       when "firebird"
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}"
229       else
230         raise "Task not supported by '#{abcs["test"]["adapter"]}'"
231       end
232     end
234     desc "Empty the test database"
235     task :purge => :environment do
236       abcs = ActiveRecord::Base.configurations
237       case abcs["test"]["adapter"]
238       when "mysql"
239         ActiveRecord::Base.establish_connection(:test)
240         ActiveRecord::Base.connection.recreate_database(abcs["test"]["database"])
241       when "postgresql"
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)
253       when "sqlserver"
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`
257       when "oci", "oracle"
258         ActiveRecord::Base.establish_connection(:test)
259         ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
260           ActiveRecord::Base.connection.execute(ddl)
261         end
262       when "firebird"
263         ActiveRecord::Base.establish_connection(:test)
264         ActiveRecord::Base.connection.recreate_database!
265       else
266         raise "Task not supported by '#{abcs["test"]["adapter"]}'"
267       end
268     end
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
274       end
275     end
276   end
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"])
285     end
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}"
292     end
293   end
296 def drop_database(config)
297   case config['adapter']
298   when 'mysql'
299     ActiveRecord::Base.connection.drop_database config['database']
300   when /^sqlite/
301     FileUtils.rm_f(File.join(RAILS_ROOT, config['database']))
302   when 'postgresql'
303     `dropdb "#{config['database']}"`
304   end
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)