Locking Tables with Rails ActiveRecord

If you wanted to lock a table for writes using ActiveRecord (this may come in handy for other things as well), it is possible. You can do so by accessing the connection.execute method available to the model itself.

Here's an example of Model.connection.execute

Model.connection.execute( "LOCK TABLES #{Model.table_name} WRITE" )
Model.connection.execute( "UNLOCK TABLES" )

However, there is a better way recommended (updated from comments) which is to make the actual models methods like this:

class Model
  def self.lock(options = {})
    sql = "LOCK TABLES #{table_name}"
    sql += ' WRITE' if options[:write]
    sql += ' READ'  if options[:read]
    execute sql
  def self.unlock
    execute "UNLOCK TABLES"

There's also talk of an API extension from Zach Dennis to do something along the lines of this: Model.lock :write=>true, :read=>true, etc.. Model.unlock That'd be nice to see Zach!