Class: Devformance::SqlInstrumentor

Inherits:
Object
  • Object
show all
Defined in:
lib/devformance/sql_instrumentor.rb

Constant Summary collapse

THREAD_KEY =
:devformance_sql_collector

Class Method Summary collapse

Class Method Details

.around_runObject



5
6
7
8
9
10
# File 'lib/devformance/sql_instrumentor.rb', line 5

def self.around_run
  Thread.current[THREAD_KEY] = { queries: [], start: Time.current }
  yield
ensure
  Thread.current[THREAD_KEY] = nil
end

.queriesObject



25
26
27
# File 'lib/devformance/sql_instrumentor.rb', line 25

def self.queries
  Thread.current[THREAD_KEY]&.dig(:queries) || []
end

.record(event) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/devformance/sql_instrumentor.rb', line 12

def self.record(event)
  collector = Thread.current[THREAD_KEY]
  return unless collector

  ms  = event.duration.round(2)
  sql = event.payload[:sql].to_s.strip

  return if sql.match?(/\A(BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)/i)

  collector[:queries] << { sql: sql, ms: ms, at: Time.current.iso8601 }
  collector[:queries].last
end