Skip to content

Commit

Permalink
Add component to comment with the database role
Browse files Browse the repository at this point in the history
With multiple databases in Rails 6, it can be difficult to tell from
logging if your database query is being made against the leader or
follower database. This change adds a new component, `db_role`, which
can be used with the database host and name to annotate the query with
the current ActiveRecord role.
  • Loading branch information
geoffharcourt committed Oct 12, 2021
1 parent adc34ad commit 8e7998f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/marginalia/comment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ def self.database
end
end

def self.db_role
return if marginalia_adapter.pool.nil?
ActiveRecord::Base.current_role
end

if Gem::Version.new(ActiveRecord::VERSION::STRING) < Gem::Version.new('6.1')
def self.connection_config
return if marginalia_adapter.pool.nil?
Expand Down
12 changes: 12 additions & 0 deletions test/query_comments_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ def pool_db_config?
Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('6.1')
end

def database_role_available?
Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('6.0.0')
end

require "minitest/autorun"
require "mocha/minitest"
require 'logger'
Expand Down Expand Up @@ -259,6 +263,14 @@ def test_socket
end
end

if database_role_available?
def test_db_role
Marginalia::Comment.components = [:db_role]
API::V1::PostsController.action(:driver_only).call(@env)
assert_match %r{/\*db_role:writing}, @queries.first
end
end

def test_request_id
@env["action_dispatch.request_id"] = "some-uuid"
Marginalia::Comment.components = [:request_id]
Expand Down

0 comments on commit 8e7998f

Please sign in to comment.