Module: MetrixWire::Instrument::Pg

Defined in:
lib/metrixwire/instrument/pg.rb

Overview

Patches the pg gem (PG::Connection) so raw queries outside Rails become db_query spans with a row count. Guarded: skips silently if pg isn't loaded. Also detects BEGIN…COMMIT/ROLLBACK to emit a transaction span.

Defined Under Namespace

Modules: Patch

Class Method Summary collapse

Class Method Details

.control_statement?(sql) ⇒ Boolean

Returns:

  • (Boolean)


61
62
63
64
65
# File 'lib/metrixwire/instrument/pg.rb', line 61

def control_statement?(sql)
  /\A\s*(BEGIN|START\s+TRANSACTION|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/i.match?(sql)
rescue StandardError
  false
end

.handle_transaction(conn, sql) ⇒ Object

Emit a transaction span on COMMIT/ROLLBACK, timed from the BEGIN.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/metrixwire/instrument/pg.rb', line 45

def handle_transaction(conn, sql)
  stmt = sql.strip
  if /\A(BEGIN|START\s+TRANSACTION)\b/i.match?(stmt)
    conn.instance_variable_set(:@__metrixwire_tx_start, MetrixWire.monotonic_ms)
  elsif /\A(COMMIT|ROLLBACK)\b/i.match?(stmt)
    started = conn.instance_variable_get(:@__metrixwire_tx_start)
    conn.instance_variable_set(:@__metrixwire_tx_start, nil)
    if started
      Helpers.add_span("custom", "DB transaction", MetrixWire.monotonic_ms - started,
                       meta: { kind: "transaction" })
    end
  end
rescue StandardError
  nil
end

.installObject



11
12
13
14
15
16
17
18
19
# File 'lib/metrixwire/instrument/pg.rb', line 11

def install
  return unless defined?(::PG::Connection)
  return if ::PG::Connection.instance_variable_get(:@__metrixwire_patched)

  ::PG::Connection.prepend(Patch)
  ::PG::Connection.instance_variable_set(:@__metrixwire_patched, true)
rescue StandardError
  nil
end