Module: PgReports::AnnotationParser

Defined in:
lib/pg_reports/annotation_parser.rb

Overview

Parses SQL query comments to extract source location and metadata Supports:

  • Marginalia format: /*application:myapp,controller:users,action:index*/

  • Rails QueryLogs: /*action=‘index’,controller=‘users’,source_location=‘app/foo.rb:42’*/

Class Method Summary collapse

Class Method Details

.format_for_display(annotation) ⇒ String

Format annotation for display

Parameters:

  • annotation (Hash)

    Parsed annotation

Returns:

  • (String)

    Human-readable string



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/pg_reports/annotation_parser.rb', line 62

def format_for_display(annotation)
  return nil if annotation.empty?

  parts = []

  # Source location
  if annotation[:file]
    loc = annotation[:file].to_s
    loc += ":#{annotation[:line]}" if annotation[:line]
    parts << loc
  end

  # Method
  parts << "##{annotation[:method]}" if annotation[:method]

  # Controller/action
  if annotation[:controller]
    ca = annotation[:controller].to_s
    ca += "##{annotation[:action]}" if annotation[:action]
    parts << ca
  end

  parts.join(" ")
end

.parse(query) ⇒ Hash

Parse annotation from query text

Parameters:

  • query (String)

    SQL query text

Returns:

  • (Hash)

    Parsed annotation data



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/pg_reports/annotation_parser.rb', line 16

def parse(query)
  return {} if query.nil? || query.empty?

  # Extract all comments from query
  comments = query.scan(%r{/\*(.+?)\*/}).flatten

  return {} if comments.empty?

  result = {}

  comments.each do |comment|
    # Try short format first: "path/to/file.rb:42"
    if (match = comment.match(%r{^(.+):(\d+)$}))
      result[:file] = match[1]
      result[:line] = match[2]
    else
      parsed = parse_comment(comment)
      result.merge!(parsed)
    end
  end

  # Rails QueryLogs custom tag — Rails URL-encodes tag values (CGI.escape) to keep
  # SQL comments safe, so "/" → "%2F" and ":" → "%3A". Decode then split into :file/:line.
  if result[:source_location] && !result[:file]
    decoded = CGI.unescape(result[:source_location].to_s)
    if (match = decoded.match(%r{^(.+):(\d+)$}))
      result[:file] = match[1]
      result[:line] = match[2]
    end
  end

  result
end

.strip_annotations(query) ⇒ String

Extract clean query without annotations

Parameters:

  • query (String)

    SQL query with annotations

Returns:

  • (String)

    Clean query



53
54
55
56
57
# File 'lib/pg_reports/annotation_parser.rb', line 53

def strip_annotations(query)
  return query if query.nil?

  query.gsub(%r{/\*.+?\*/\s*}, "").strip
end