2

I would like to execute a simple sql line each time a new connection is made (on that same connection)

Why? Using postgres, "set application_name = 'abc';" will allow me to keep track of the application using the connections when I query my database server for stats.

Haven't seen anything that would allow me to do this.

1 Answer 1

1

I solved a similar problem recently. I was changing the transaction isolation level after connecting. This example should help you out. It is based on the advice in the final example on this blog post.

# lib/active_record/application_name.rb
module ActiveRecord
  module ApplicationName
    def self.included(base)
      unless base.respond_to? :establish_connection_with_application_name
          base.extend ClassMethods
          base.class_eval do
            class << self
              alias_method_chain :establish_connection, :application_name
            end
          end
      end
    end

    module ClassMethods
      def establish_connection_with_application_name(*args)
        result = establish_connection_without_application_name(*args)
        ::ActiveRecord::Base.connection.execute("set application_name = 'abc';")
        result
      end
    end
  end
end

# lib/patches/active_record.rb
require 'active_record/application_name'

class ActiveRecord::Base
  include ActiveRecord::ApplicationName
end


# config/initializers/patches.rb
require 'patches/active_record'
Sign up to request clarification or add additional context in comments.

2 Comments

This isin't working but the idea was there. Activerecord dosen't pass internaly through establish_connection. It use the pools instead. Went in and added code around the new_connection method in ActiveRecord::ConnectionAdapters::ConnectionPool. Worked fine. If I can find time I'll release some nice code as a gem.
Ah, cool. In my environment we're calling establish_connection explicitly in a post_fork block in Unicorn, so it worked for me. Thanks for the advice though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.