Run Rake task programmatically with specified environment - ruby-on-rails

I'm setting up a second database with my Ruby on Rails (3) application, so I want to create a rake task to create the second development database. I'm trying to overwrite the rake db:create task such that it does all the database creation that I need. However, it seems I can't find a suitable way to perform this task. I've tried a few approaches - establishing a connection to the database from the URL:
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('#tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
# database.yml contains an entry for secondary_development, this works, as confirmed from rails console
ActiveRecord::Base.establish_connection "postgresql://localhost/secondary_development"
Rake::Task["db:create"].invoke # this does nothing
end
# invoke original db_create task - this works
db_create.invoke
end
end
Another approach was to do:
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('#tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
Rails.env = "secondary_development"
Rake::Task["db:create"].invoke
end
# invoke original db_create task - this doesn't work like this
db_create.invoke
end
end
This time only the secondary_development db:create works and the database is created as desired, but the development database is no longer created using this approach.
From one answer I found elsewhere, I thought that reenabling the task would be necessary, but that didn't change anything here and appears not to be the issue.
Finally, an approach that has worked is:
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('#tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
system("rake db:create RAILS_ENV=secondary_development")
end
db_create.invoke
end
end
The only issue here is that because the rake task is being run via system, the Rails application has to load before being executed, so I'm essentially loading the application twice fully just to run the task - this will be 3 times when I add a test database into the mix.
So, the actual question(s):
Is it possible to run Rake::Task["..."] programmatically with a specified environment?
Why doesn't ActiveRecord::Base.establish_connection work in this way when creating the database? I had success when running this from Rails console.

I managed to find a solution to this. I believe the reason is that .invoke will not always invoke the task, but it will first determine whether it is necessary. Given that rake db:create is run on several occasions within the same task, .invoke deems the subsequent invocations as unnecessary and therefore does not run them. For the desired behaviour, .execute should be used instead.
# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('#tasks').delete('db:create')
namespace :db do
task :create do
if Rails.env == "development"
Rails.env = "secondary_development"
Rake::Task["db:create"].execute # execute rather than invoke
end
# Reset the Rails env to 'development', otherwise it remains as 'secondary_development', which is not what we want (or move this above the if)
Rails.env = "development"
db_create.execute
end
end

Related

How to run db:migrate from another rake task with parameters?

I'd like to call db:drop, db:create, db:migrate from another rake task and specify the database like the command "rake db:migrate db=test". That way I can call it for several different databases in a row.
But settings Rails.env = 'test' and then resetting it Rails.env to a new environment doesn't work.
But the above code always executes on the development environment (if i take out the development environment I'll get this error
How can I call these tasks multiple times and change the environment to us?
Once ActiveRecord sets the environment you have to tell it directly to change the environment. So this will work.
ActiveRecord::Tasks::DatabaseTasks.env = 'test'
Rake::Task["db:drop"].execute
Rake::Task["db:create"].execute
Rake::Task["db:migrate"].execute
ActiveRecord::Tasks::DatabaseTasks.env = 'development'
Rake::Task["db:drop"].execute
Rake::Task["db:create"].execute
Rake::Task["db:migrate"].execute
If you only want to use the test database temporarily, set the database connection to test and then set it back to the defaults when the task is finished:
Rails.env = 'test
Rake::Task['db:migrate'].invoke
Rails.env = ENV["RAILS_ENV"]

How can I create a rake task that will always run when any Rake task is ran?

From what I remember, in the documentation is specified that in the test environment, the database is always cleared even when you run rake ( with no arguments ). I'd like to achieve such a thing, so that it doesn't matter if I run a task or not, when I run rake, there's always a Rake task being executed. Is this possible? Is this where the default task kicks in?
Create a file called rakefile in the directory you want to run the task from.
This code will make it so that if you just type "rake" my_default_task will run:
task :default => 'my_default_task'
task :my_default_task do
puts "Now I am doing the task that Tempus wants done when he/she types 'rake' in the console."
end
task :my_not_default_task do
puts "This isn't the default task."
end
However, if you typed rake my_not_default_task, then my_default_task would NOT run. If you want it to run regardless here is one thing you can do:
task :default => 'my_default_task'
task :my_default_task do
puts "This is the default task"
end
task :my_not_default_task do
puts "This isn't the default task."
end
Rake::Task['my_default_task'].invoke
The last line in this code ensures that my_default_task runs even when you call some other task, so if you typed rake my_not_default_task the my_default_task'would also run.
EDIT:
When you're working with rails you can put the tasks above in a file in the lib/tasks folder with an extension of .rake and rails will automagically run them when you do rake
Jason Seifer has a real nice tutorial on rake.

How to drop test and development database in one rake task?

I tried to drop the test and development databases from one rake task like this:
task :regenerate do
Rails.env = "test"
Rake::Task["db:drop"].invoke
Rails.env = "development"
Rake::Task["db:drop"].invoke
end
The test database was dropped successfully. But the development database was not dropped.
Any ideas on how to make this work?
NB: This is on Rails 3.2.3
UPDATE:
Very odd, but reversing the order works:
task :regenerate do
Rails.env = "development"
Rake::Task["db:drop"].invoke
Rails.env = "test"
Rake::Task["db:drop"].invoke
end
What is going on?!
You can write it like this:
namespace :db do
desc "Database custom drop"
task :mydrop do
system("rake db:drop RAILS_ENV=test")
system("rake db:drop RAILS_ENV=development")
end
end
Reversing it does work, because there is some strange code in database_tasks.rb:
def each_current_configuration(environment)
environments = [environment]
environments << 'test' if environment == 'development'
configurations = ActiveRecord::Base.configurations.values_at(*environments)
configurations.compact.each do |configuration|
yield configuration unless configuration['database'].blank?
end
end
It always adds test if env is development. I solved the case of wanting to do a custom db:rebuild task for simultaneous development and test by running development first, and test second. In addition, before running the tasks, I call my set_env method which makes sure to set ActiveRecord::Tasks::DatabaseTasks.env, without this, the database connections don't seem to be handled discretely for environments as expected. I tried all other sorts of disconnect etc, but this worked without further code.
def set_env(env)
Rails.env = env.to_s
ENV['RAILS_ENV'] = env.to_s
ActiveRecord::Tasks::DatabaseTasks.env = env.to_s
end
Here is a gist of my full db.rake file with simultaneous multi-environment db:rebuild and db:truncate
On my system with Ruby 2 and Rails 3.2.13 I can run rake db:drop
This drops both test and development databases. Much easier now than messing with rake tasks

Log SQL queries during rake tasks

Similar to 'rails server' that prints every SQL query executed I would like to do the same for rake tasks.
What is the best way to achieve that?
Proper answer is to put this at the beginning of rake task:
ActiveRecord::Base.logger = Logger.new STDOUT
Depending on your environment, Rake will log sql queries just like any Rails process will & in the same logfile. So on your dev box, check your log/development.log file - it will contain your Rake task's queries. If you want queries logged in production, set the log level in your Rake task to DEBUG, and make sure the rake task depends on :environment.
desc "Task with SQL logging"
task :test_log => :environment do
Rails.logger.level = Logger::DEBUG
Your code here...
end
rake db:migrate --trace
The --trace will show details
echo '' > log/development.log
rake db:migrate:redo VERSION=20141017153933
cat log/development.log
I tried the above and couldn't get it to work. Syntax was fine, no errors, but no sql came to stdout (or the log). I'm using rails 3.2. I'm also running in a production environment.
To see the sql queries generated by my rake tasks, I used the technique found at http://eewang.github.io/blog/2013/07/29/how-to-use-rake-tasks-to-generate-migration-sql/
In particular, I just inserted this block in my task before the find() statements that generated the SQL queries I was intersted in:
ActiveRecord::Base.connection.class.class_eval do
# alias the adapter's execute for later use
alias :old_execute :execute
# define our own execute
def execute(sql, name = nil)
print "===== #{sql}\n"
old_execute sql, name
end
end
Then I could see the SQL on stdout. This is not my code - Eugene Wang came up with this technique.
You can create the following task (lib/tasks/db.rake):
task :show_sql do
ActiveRecord::Base.logger = Logger.new STDOUT
end
And use it like so:
$ bin/rake show_sql db:migrate

environment change in rake task

I am developing Rails v2.3 app with MySQL database and mysql2 gem. I faced a weird situation which is about changing the environment in rake task.
(all my setting and configurations for environment and database are correct, no problem for that.)
Here is my simple story :
I have a rake task like following:
namespace :db do
task :do_something => :environment do
#1. run under 'development' environment
my_helper.run_under_development_env
#2. change to 'custom' environment
RAILS_ENV='custom'
Rake::Task['db:create']
Rake::Task['db:migrate']
#3. change back to 'development' environment
RAILS_ENV='development'
#4. But it still run in 'customer' environment, why?
my_helper.run_under_development_env
end
end
The rake task is quite simple, what it does is:
1. Firstly, run a method from my_helper under "development" environment
2. Then, change to "custom" environment and run db:create and db:migrate
until now, everything is fine, the environment did change to "custom"
3. Then, change it back again to "development" environment
4. run helper method again under "development" environment
But, though I have changed the environment back to "development" in step 3, the last method still run in "custom" environment, why? and how to get rid of it?
--- P.S. ---
I have also checked a post related with environment change here, and tried to use the solution there (in step 2):
#2. change to 'custom' database
ActiveRecord::Base.establish_connection('custom')
Rake::Task['db:create']
Rake::Task['db:migrate']
to change the database connection instead of changing environment but, the db:create and db:migrate will still run under "development" database, though the linked post said it should run for "custom" database... weird
--------------- important update ---------------------
I just realize that the code in step 2:
#2. change to 'custom' environment
RAILS_ENV='custom'
Rake::Task['db:create']
Rake::Task['db:migrate']
it changes environment to "custom" only if the Rake::Task['db:create'] get called, if I comment out Rake::Task['db:create'] line, code will still run under 'development':
#2. change to 'custom' environment
RAILS_ENV='custom'
#Rake::Task['db:create']
#CODE WILL RUN STILL UNDER 'development' environment.
Why Rake::Task['db:create'] affects environment change in my case...?
I realize this question is from over a month ago, but what they heck - it's Christmas
it seems like running each rake task in its own process will simplify things when switching environments?
namespace :db do
task :do_something => :environment do
unless Rails.env.development? then
raise "Can only run under development environment, but specified env was #{Rails.env}"
end
#1. run under 'development' environment
my_helper.run_under_development_env
#2. do the giggity with custom environment
command = "bundle exec rake db:create RAILS_ENV=custom"
result = %x[#{command}]
raise "rake task failed..........\n#{result}" if result.include?('rake aborted!')
command = "bundle exec rake db:migrate RAILS_ENV=custom"
result = %x[#{command}]
raise "rake task failed..........\n#{result}" if result.include?('rake aborted!')
#3. back to development
my_helper.run_under_development_env
end
end
just type after the rake task RAILS_ENV='production'
in your case
rake db:do_something RAILS_ENV='custom'

Resources