Rails and Database Session Variables
Ruby's ActiveRecord provides a very robust means of manipulating database table structures especially in the context of automated deployments such as Capistrano.
When there is a master-slave database configuration, it may not always be prudent to perform DDL statements on the master and let those propagate through to the slave, especially in high-volume sites where Rails deployments may involve multiple migrations since replication lag may occur and present some significant problems. In addition, when no downtime is specified, a DDL rollout may break the current application code, so a targeted deployment may be more prudent.
class AddAccounts < ActiveRecord::Migration
def self.up
execute("set SESSION sql_log_bin=0")
create_table :api_accounts do |t|
t.column "user_id", :int
t.column "name", :text
t.column "account",:text
t.column "created_at", :datetime
t.column "updated_at", :datetime
end
end
def self.down
execute("set SESSION sql_log_bin=0")
drop_table :api_accounts
end
end
But since this would be a hassle for developers and is easily overlooked, we can leverage Capistrano's architecture to monkey patch the ActiveRecord::Migration class so that this variable is set whenever the migrations are invoked. So we constructed a file, config/initializers/active_record.rb:
#opens the ActiveRecord::Migration class#use alias_method to add functionality to the ActiveRecord::Migration.migrate methodclass ActiveRecord::Migrationclass << selfalias_method :migrate_conn, :migratedef migrate(direction)ActiveRecord::Base.connection_pool.with_connection do |conn|@connection = connconnection.execute("SET SQL_LOG_BIN=0")@connection = nilendmigrate_conn(direction)endendend
We successfully developed and implemented this technique with the devops team at SlideShare last month to build rolling DDL scripting to multiple databases using Capistrano. It allowed them to have explicit control over which database was being updated, thereby giving them the means necessary to update one database while the other served the current application code.
Archives
- May 2012
- April 2012
- March 2012
- February 2012
- January 2012
- December 2011
- November 2011
- October 2011
- September 2011
- August 2011
- July 2011
- June 2011
- May 2011
- April 2011
- March 2011
- February 2011
- January 2011
- December 2010
- November 2010
- October 2010
- September 2010
- November 2009
- March 2008
- November 2007
- October 2007


Comments
Reply