Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming SQL queries in Rails / ActiveRecord

When using Rails with ActiveRecord (and PostgreSQL), executing "simple" queries adds a name to them, e.g. calling

Article.all
# => Article Load (2.6ms)  SELECT "articles".* FROM "articles"

names the query Article Load. However, when executing slightly more complex queries, no name is being generated, as for example with

Article.group(:article_group_id).count
# => (1.2ms)  SELECT COUNT(*) AS count_all, "articles"."article_group_id" AS articles_article_group_id FROM "articles" GROUP BY "articles"."article_group_id"

I can add a name if executing a custom query using the execute method:

ActiveRecord::Base.connection.execute("SELECT * FROM articles", "My custom query name")
# => My custom query name (2.5ms)  SELECT * FROM articles

But is there a way to add a custom name to a query built with the ActiveRecord-methods?

If you wonder why: The name is useful for all kinds of monitoring, e.g. when looking at slow queries in AppSignal.

like image 361
Timitry Avatar asked Nov 07 '22 01:11

Timitry


1 Answers

Since you just want to custom query name for monitoring purpose, so i think you only need to change the query name in the ActiveRecord::ConnectionAdapters#log method, this method is the one log the sql query that be executed, include the query name.

Here is my solution:

# lib/active_record/base.rb
# note that MUST be base.rb
# otherwise you need to add initializer to extend Rails core
#
module ActiveRecord
  module ConnectionAdapters
    class AbstractAdapter
      attr_accessor :log_tag

      private

      alias old_log log
      def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil)
        if name != 'SCHEMA'
          name = @log_tag
          @log_tag = nil # reset
        end

        old_log(sql, name, binds, type_casted_binds, statement_name) do
          yield
        end
      end
    end
  end

  module QueryMethods
    def log_tag(tag_name) # class method
      spawn.log_tag(tag_name)
      self
    end
  end

  module Querying
    delegate :log_tag, to: :all
  end

  class Relation
    def log_tag(tag_name) # instance method
      conn = klass.connection
      conn.log_tag = tag_name
      self
    end
  end
end

Demo

Task.log_tag("DEMO").group(:status).count
# DEMO (0.7ms)  SELECT COUNT(*) AS count_all, "tasks"."status" AS tasks_status FROM "tasks" GROUP BY "tasks"."status"

Task.where(status: 6).log_tag("SIX").first(20)
# SIX (0.8ms)  SELECT "tasks".* FROM "tasks" WHERE "tasks"."status" = ? ORDER BY "tasks"."id" ASC LIMIT ?

Task.where(status: 6).first(20)
# (0.8ms)  SELECT "tasks".* FROM "tasks" WHERE "tasks"."status" = ? ORDER BY "tasks"."id" ASC LIMIT ?

Note

In case you want to fix query name for specific query, you can use a hash with key is the whole the specific sql string (or hash of whole sql, such as the way Rails core cache query: query_signature = ActiveSupport::Digest.hexdigest(to_sql)) and the value is the query name you want.

# set up before hand
ActiveRecord::ConnectionAdapters::LogTags[Product.where...to_sql] = "DEMO"
# AbstractAdapter
LogTags = Hash.new
def log(sql, name...)
  name = LogTags[sql]
  # ...
end 
like image 59
Lam Phan Avatar answered Nov 12 '22 16:11

Lam Phan