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"]
Related
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
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
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
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'
I've done this patch to my test_helper.rb
ENV["RAILS_ENV"] = ENV["RAILS_ENV_TEST"] || "test"
This works in that I can run
RAILS_ENV_TEST=test_dan ruby -Itest test/unit/post_test.rb
but I want to be able to run all kinds of test things, including rake db:test:clone but not using the environment test. How can I do this?
Most rake tasks that are namespaced with "test" will only run on your test environment and not in other environments. It's hardcoded into the task as to mitigate potentially devastating affects they might have in an environment such as production.
You can see that these tasks don't take into account the environment in which they are called in the source.
If you want to run these tasks in whatever environment you want, your best bet is to recreate these tasks and pass in the environment.
namespace :any_environment_test do
task :load => :environment do
...
task :clone => :environment do
...
In this specific case, it's a little trickier, as it sounds like you want to clone from any environment to any environment. If this is the case, you should probably have two vars that are passed, such as FROM_ENV= and TO_ENV=.
Long story longer, you're going to write custom tasks, but can inspire yourself from the link I posted above. :)