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 Mar 27, 2021
1 parent 8c1e8ec commit 3ec6a96
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion gemfiles/5.2.gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ source "https://rubygems.org"
gem "mysql2", "~> 0.4.10"
gem "pg", "~> 0.15"
gem "sqlite3", "~> 1.3.6"
gem "rails", "= 5.2.2.1"
gem "rails", "= 5.2.5"

gemspec :path => "../"
8 changes: 8 additions & 0 deletions gemfiles/6.0.gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
source "https://rubygems.org"

gem "mysql2", "~> 0.4.10"
gem "pg", "~> 0.15"
gem "sqlite3", "~> 1.3.6"
gem "rails", "= 6.0.3"

gemspec :path => "../"
5 changes: 5 additions & 0 deletions lib/marginalia/comment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,11 @@ def self.db_host
end
end

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

def self.database
if self.connection_config.present?
self.connection_config[:database]
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 @@ -17,6 +17,10 @@ def adapter_pool_available?
Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new('3.2.19')
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 @@ -245,6 +249,14 @@ def test_db_host
assert_match %r{/\*db_host:localhost}, @queries.first
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_database
Marginalia::Comment.components = [:database]
API::V1::PostsController.action(:driver_only).call(@env)
Expand Down

0 comments on commit 3ec6a96

Please sign in to comment.