Can I hook into ActiveRecord connection establishm

2019-08-13 01:09发布

问题:

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.