Can I hook into ActiveRecord connection establishment?

我与影子孤独终老i 提交于 2019-12-13 02:22:49

问题


I would like to add a user-defined function using Sqlite3's create_function, which will be used by database triggers.

Is there a way to hook into ActiveRecord connection establishment to run some code each time a connection to the database is made, where one could create the function and make it available to the triggers? This would also be useful for setting pragmas on the connection.


回答1:


Here is what I've found on my own. Using an initializer in app/config/initializers I do this:

ActiveRecord::ConnectionAdapters::AbstractAdapter.class_eval do
  alias_method :orig_initialize, :initialize

  def initialize(connection, logger = nil, pool = nil)
    orig_initialize(connection, logger, pool)
    if connection.is_a? SQLite3::Database
      # 'reverse' is just an example :^)
      connection.create_function('reverse', 1) { |func, value| func.result = if value then value.to_s.reverse end }
    end
  end
end

I'm not sure if this class gets reloaded, but I'll cross that bridge if I get to it.



来源:https://stackoverflow.com/questions/18318873/can-i-hook-into-activerecord-connection-establishment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!