Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #11602: databases.rake

File databases.rake, 14.7 kB (added by antun, 6 months ago)

Here's my fixed databases.rake file.

Line 
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 %w( 127.0.0.1 localhost ).include?(config['host']) || 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
27
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
32
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
60
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 %w( 127.0.0.1 localhost ).include?(config['host']) || 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
76
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
81
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
88
89   namespace :migrate do
90     desc  'Rollbacks the database one migration and re migrate up. If you want to rollback more than one step, define STEP=x'
91     task :redo => [ 'db:rollback', 'db:migrate' ]
92
93     desc 'Resets your database using your migrations for the current environment'
94     task :reset => ["db:drop", "db:create", "db:migrate"]
95   end
96
97   desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
98   task :rollback => :environment do
99     step = ENV['STEP'] ? ENV['STEP'].to_i : 1
100     version = ActiveRecord::Migrator.current_version - step
101     ActiveRecord::Migrator.migrate('db/migrate/', version)
102   end
103
104   desc 'Drops and recreates the database from db/schema.rb for the current environment.'
105   task :reset => ['db:drop', 'db:create', 'db:schema:load']
106
107   desc "Retrieves the charset for the current environment's database"
108   task :charset => :environment do
109     config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
110     case config['adapter']
111     when 'mysql'
112       ActiveRecord::Base.establish_connection(config)
113       puts ActiveRecord::Base.connection.charset
114     else
115       puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
116     end
117   end
118
119   desc "Retrieves the collation for the current environment's database"
120   task :collation => :environment do
121     config = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
122     case config['adapter']
123     when 'mysql'
124       ActiveRecord::Base.establish_connection(config)
125       puts ActiveRecord::Base.connection.collation
126     else
127       puts 'sorry, your database adapter is not supported yet, feel free to submit a patch'
128     end
129   end
130
131   desc "Retrieves the current schema version number"
132   task :version => :environment do
133     puts "Current version: #{ActiveRecord::Migrator.current_version}"
134   end
135
136   desc "Raises an error if there are pending migrations"
137   task :abort_if_pending_migrations => :environment do
138     if defined? ActiveRecord
139       pending_migrations = ActiveRecord::Migrator.new(:up, 'db/migrate').pending_migrations
140
141       if pending_migrations.any?
142         puts "You have #{pending_migrations.size} pending migrations:"
143         pending_migrations.each do |pending_migration|
144           puts '  %4d %s' % [pending_migration.version, pending_migration.name]
145         end
146         abort "Run `rake db:migrate` to update your database then try again."
147       end
148     end
149   end
150
151   namespace :fixtures do
152     desc "Load fixtures into the current environment's database.  Load specific fixtures using FIXTURES=x,y"
153     task :load => :environment do
154       require 'active_record/fixtures'
155       ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym)
156       (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : Dir.glob(File.join(RAILS_ROOT, 'test', 'fixtures', '*.{yml,csv}'))).each do |fixture_file|
157         Fixtures.create_fixtures('test/fixtures', File.basename(fixture_file, '.*'))
158       end
159     end
160    
161     desc "Search for a fixture given a LABEL or ID."
162     task :identify => :environment do
163       require "active_record/fixtures"
164
165       label, id = ENV["LABEL"], ENV["ID"]
166       raise "LABEL or ID required" if label.blank? && id.blank?
167      
168       puts %Q(The fixture ID for "#{label}" is #{Fixtures.identify(label)}.) if label
169      
170       Dir["#{RAILS_ROOT}/test/fixtures/**/*.yml"].each do |file|
171         if data = YAML::load(ERB.new(IO.read(file)).result)
172           data.keys.each do |key|
173             key_id = Fixtures.identify(key)
174            
175             if key == label || key_id == id.to_i
176               puts "#{file}: #{key} (#{key_id})"
177             end
178           end
179         end
180       end
181     end
182   end
183
184   namespace :schema do
185     desc "Create a db/schema.rb file that can be portably used against any DB supported by AR"
186     task :dump => :environment do
187       require 'active_record/schema_dumper'
188       File.open(ENV['SCHEMA'] || "db/schema.rb", "w") do |file|
189         ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
190       end
191     end
192
193     desc "Load a schema.rb file into the database"
194     task :load => :environment do
195       file = ENV['SCHEMA'] || "db/schema.rb"
196       load(file)
197     end
198   end
199
200   namespace :structure do
201     desc "Dump the database structure to a SQL file"
202     task :dump => :environment do
203       abcs = ActiveRecord::Base.configurations
204       case abcs[RAILS_ENV]["adapter"]
205       when "mysql", "oci", "oracle"
206         ActiveRecord::Base.establish_connection(abcs[RAILS_ENV])
207         File.open("db/#{RAILS_ENV}_structure.sql", "w+") { |f| f << ActiveRecord::Base.connection.structure_dump }
208       when "postgresql"
209         ENV['PGHOST']     = abcs[RAILS_ENV]["host"] if abcs[RAILS_ENV]["host"]
210         ENV['PGPORT']     = abcs[RAILS_ENV]["port"].to_s if abcs[RAILS_ENV]["port"]
211         ENV['PGPASSWORD'] = abcs[RAILS_ENV]["password"].to_s if abcs[RAILS_ENV]["password"]
212         search_path = abcs[RAILS_ENV]["schema_search_path"]
213         search_path = "--schema=#{search_path}" if search_path
214         `pg_dump -i -U "#{abcs[RAILS_ENV]["username"]}" -s -x -O -f db/#{RAILS_ENV}_structure.sql #{search_path} #{abcs[RAILS_ENV]["database"]}`
215         raise "Error dumping database" if $?.exitstatus == 1
216       when "sqlite", "sqlite3"
217         dbfile = abcs[RAILS_ENV]["database"] || abcs[RAILS_ENV]["dbfile"]
218         `#{abcs[RAILS_ENV]["adapter"]} #{dbfile} .schema > db/#{RAILS_ENV}_structure.sql`
219       when "sqlserver"
220         `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /f db\\#{RAILS_ENV}_structure.sql /q /A /r`
221         `scptxfr /s #{abcs[RAILS_ENV]["host"]} /d #{abcs[RAILS_ENV]["database"]} /I /F db\ /q /A /r`
222       when "firebird"
223         set_firebird_env(abcs[RAILS_ENV])
224         db_string = firebird_db_string(abcs[RAILS_ENV])
225         sh "isql -a #{db_string} > db/#{RAILS_ENV}_structure.sql"
226       else
227         raise "Task not supported by '#{abcs["test"]["adapter"]}'"
228       end
229
230       if ActiveRecord::Base.connection.supports_migrations?
231         File.open("db/#{RAILS_ENV}_structure.sql", "a") { |f| f << ActiveRecord::Base.connection.dump_schema_information }
232       end
233     end
234   end
235
236   namespace :test do
237     desc "Recreate the test database from the current environment's database schema"
238     task :clone => %w(db:schema:dump db:test:purge) do
239       ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
240       ActiveRecord::Schema.verbose = false
241       Rake::Task["db:schema:load"].invoke
242     end
243
244
245     desc "Recreate the test databases from the development structure"
246     task :clone_structure => [ "db:structure:dump", "db:test:purge" ] do
247       abcs = ActiveRecord::Base.configurations
248       case abcs["test"]["adapter"]
249       when "mysql"
250         ActiveRecord::Base.establish_connection(:test)
251         ActiveRecord::Base.connection.execute('SET foreign_key_checks = 0')
252         IO.readlines("db/#{RAILS_ENV}_structure.sql").join.split("\n\n").each do |table|
253           ActiveRecord::Base.connection.execute(table)
254         end
255       when "postgresql"
256         ENV['PGHOST']     = abcs["test"]["host"] if abcs["test"]["host"]
257         ENV['PGPORT']     = abcs["test"]["port"].to_s if abcs["test"]["port"]
258         ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
259         `psql -U "#{abcs["test"]["username"]}" -f db/#{RAILS_ENV}_structure.sql #{abcs["test"]["database"]}`
260       when "sqlite", "sqlite3"
261         dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
262         `#{abcs["test"]["adapter"]} #{dbfile} < db/#{RAILS_ENV}_structure.sql`
263       when "sqlserver"
264         `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
265       when "oci", "oracle"
266         ActiveRecord::Base.establish_connection(:test)
267         IO.readlines("db/#{RAILS_ENV}_structure.sql").join.split(";\n\n").each do |ddl|
268           ActiveRecord::Base.connection.execute(ddl)
269         end
270       when "firebird"
271         set_firebird_env(abcs["test"])
272         db_string = firebird_db_string(abcs["test"])
273         sh "isql -i db/#{RAILS_ENV}_structure.sql #{db_string}"
274       else
275         raise "Task not supported by '#{abcs["test"]["adapter"]}'"
276       end
277     end
278
279     desc "Empty the test database"
280     task :purge => :environment do
281       abcs = ActiveRecord::Base.configurations
282       case abcs["test"]["adapter"]
283       when "mysql"
284         ActiveRecord::Base.establish_connection(:test)
285         ActiveRecord::Base.connection.recreate_database(abcs["test"]["database"])
286       when "postgresql"
287         ENV['PGHOST']     = abcs["test"]["host"] if abcs["test"]["host"]
288         ENV['PGPORT']     = abcs["test"]["port"].to_s if abcs["test"]["port"]
289         ENV['PGPASSWORD'] = abcs["test"]["password"].to_s if abcs["test"]["password"]
290         enc_option = "-E #{abcs["test"]["encoding"]}" if abcs["test"]["encoding"]
291
292         ActiveRecord::Base.clear_active_connections!
293         `dropdb -U "#{abcs["test"]["username"]}" #{abcs["test"]["database"]}`
294         `createdb #{enc_option} -U "#{abcs["test"]["username"]}" #{abcs["test"]["database"]}`
295       when "sqlite","sqlite3"
296         dbfile = abcs["test"]["database"] || abcs["test"]["dbfile"]
297         File.delete(dbfile) if File.exist?(dbfile)
298       when "sqlserver"
299         dropfkscript = "#{abcs["test"]["host"]}.#{abcs["test"]["database"]}.DP1".gsub(/\\/,'-')
300         `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{dropfkscript}`
301         `osql -E -S #{abcs["test"]["host"]} -d #{abcs["test"]["database"]} -i db\\#{RAILS_ENV}_structure.sql`
302       when "oci", "oracle"
303         ActiveRecord::Base.establish_connection(:test)
304         ActiveRecord::Base.connection.structure_drop.split(";\n\n").each do |ddl|
305           ActiveRecord::Base.connection.execute(ddl)
306         end
307       when "firebird"
308         ActiveRecord::Base.establish_connection(:test)
309         ActiveRecord::Base.connection.recreate_database!
310       else
311         raise "Task not supported by '#{abcs["test"]["adapter"]}'"
312       end
313     end
314
315     desc 'Prepare the test database and load the schema'
316     task :prepare => %w(environment db:abort_if_pending_migrations) do
317       if defined?(ActiveRecord) && !ActiveRecord::Base.configurations.blank?
318         Rake::Task[{ :sql  => "db:test:clone_structure", :ruby => "db:test:clone" }[ActiveRecord::Base.schema_format]].invoke
319       end
320     end
321   end
322
323   namespace :sessions do
324     desc "Creates a sessions migration for use with CGI::Session::ActiveRecordStore"
325     task :create => :environment do
326       raise "Task unavailable to this database (no migration support)" unless ActiveRecord::Base.connection.supports_migrations?
327       require 'rails_generator'
328       require 'rails_generator/scripts/generate'
329       Rails::Generator::Scripts::Generate.new.run(["session_migration", ENV["MIGRATION"] || "CreateSessions"])
330     end
331
332     desc "Clear the sessions table"
333     task :clear => :environment do
334       session_table = 'session'
335       session_table = Inflector.pluralize(session_table) if ActiveRecord::Base.pluralize_table_names
336       ActiveRecord::Base.connection.execute "DELETE FROM #{session_table}"
337     end
338   end
339 end
340
341 def drop_database(config)
342   case config['adapter']
343   when 'mysql'
344     ActiveRecord::Base.connection.drop_database config['database']
345   when /^sqlite/
346     FileUtils.rm_f(File.join(RAILS_ROOT, config['database']))
347   when 'postgresql'
348     `dropdb "#{config['database']}"`
349   end
350 end
351
352 def session_table_name
353   ActiveRecord::Base.pluralize_table_names ? :sessions : :session
354 end
355
356 def set_firebird_env(config)
357   ENV["ISC_USER"]     = config["username"].to_s if config["username"]
358   ENV["ISC_PASSWORD"] = config["password"].to_s if config["password"]
359 end
360
361 def firebird_db_string(config)
362   FireRuby::Database.db_string_for(config.symbolize_keys)
363 end