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’*/

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



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/pg_reports/annotation_parser.rb', line 50

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



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pg_reports/annotation_parser.rb', line 14

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

  result
end

.strip_annotations(query) ⇒ String

Extract clean query without annotations

Parameters:

  • query (String)

    SQL query with annotations

Returns:

  • (String)

    Clean query



41
42
43
44
45
# File 'lib/pg_reports/annotation_parser.rb', line 41

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

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