如何在Rails中执行数据库连接时执行查询?

syc*_*uny 6 postgresql database-connection ruby-on-rails

我有一些初始化函数,我用它来设置PostgreSQL中数据库服务器端(即不是rails)的审计日志记录.至少有一个具有将予发行(设置当前用户)将数据插入或更新任何审计表,否则整个查询将失败壮观之前.

在代码中运行任何保存操作之前,我可以轻松地调用它们,但DRY让我觉得我应该在尽可能少的地方重复代码,特别是因为这与数据库不可知论的理想大相径庭.目前我正在尝试覆盖初始化程序中的ActiveRecord :: Base.establish_connection以进行设置,以便在我自动连接时立即运行查询,但它不会像我期望的那样运行.这是初始化程序中的代码:

class ActiveRecord::Base
  # extend the class methods, not the instance methods
  class << self
    alias :old_establish_connection :establish_connection # hide the default

    def establish_connection(*args)
      ret = old_establish_connection(*args) # call the default

      # set up necessary session variables for audit logging
      # call these after calling default, to make sure conn is established 1st
      db = self.class.connection
      db.execute("SELECT SV.set('current_user', 'test@localhost')")
      db.execute("SELECT SV.set('audit_notes', NULL)") # end "empty variable" err

      ret # return the default's original value
    end
  end
end

puts "Loaded custom establish_connection into ActiveRecord::Base"
sycobuny:~/rails$ ruby script/server 
=> Booting WEBrick
=> Rails 2.3.5 application starting on http://0.0.0.0:3000
Loaded custom establish_connection into ActiveRecord::Base

这不会给我任何错误,不幸的是我无法检查内部方法是什么样的(我使用的是ActiveRecord :: Base.method(:establish_connection)),但显然每次调用时都会创建一个新的Method对象,这看似毫无价值,因为我无法检查object_id是否有任何有价值的信息,我也无法反转编译).

但是,代码似乎永远不会被调用,因为任何在数据库对象上运行保存或更新的尝试都会失败,正如我之前预测的那样.如果这不是在连接数据库时立即执行代码的正确方法,那么它是什么?

Tra*_*ick 3

Rails 使用连接池,因此最好的选择是对 ActiveRecord::ConnectionAdapters::ConnectionPool#new_connection 使用 alias_method_chain

module ActiveRecord
  Module ConnectionAdapters
    class ConnectionPool
      alias_method_chain :new_connection, :my_stuff
      private
      def new_connection_with_my_stuff
        c = new_connection_without_my_stuff
        # Do your stuff with 
        # c.exec(<your sql command>)
        c
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)