Module: QueryGuard::Trace
- Defined in:
- lib/query_guard/trace.rb
Overview
Block-based tracing API for manual query tracking. Usable in console, tests, and Rails controllers/jobs.
Defined Under Namespace
Classes: Report
Class Method Summary collapse
-
.trace(label, context: {}) ⇒ Object
Trace a block of code and capture query stats.
Class Method Details
.trace(label, context: {}) ⇒ Object
Trace a block of code and capture query stats. Returns [result, report] tuple.
Example:
result, report = QueryGuard.trace("load users") do
User.where(active: true).limit(10).to_a
end
puts report.query_count
puts report.total_duration_ms
With context:
result, report = QueryGuard.trace("process batch", context: { batch_id: 123 }) do
# ... code ...
end
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/query_guard/trace.rb', line 67 def trace(label, context: {}) # Initialize thread-local stats previous_stats = Thread.current[:query_guard_stats] Thread.current[:query_guard_stats] = { request_id: "trace-#{SecureRandom.hex(4)}", count: 0, total_duration_ms: 0.0, violations: [], fingerprints: Hash.new(0), response_bytes: 0, queries: [], request: context } # Execute the block result = yield # Capture stats stats = Thread.current[:query_guard_stats] violations = stats[:violations].dup # Check budget if configured if QueryGuard.respond_to?(:config) && QueryGuard.config budget = QueryGuard.config.budget if budget budget_violations = budget.check(label, stats) violations.concat(budget_violations) end end # Build report report = Report.new(label, context, stats, violations) [result, report] ensure # Restore previous stats Thread.current[:query_guard_stats] = previous_stats end |