Class: Dontbugme::Store::Sqlite

Inherits:
Base
  • Object
show all
Defined in:
lib/dontbugme/store/sqlite.rb

Instance Method Summary collapse

Constructor Details

#initialize(path: nil) ⇒ Sqlite

Returns a new instance of Sqlite.



9
10
11
12
13
# File 'lib/dontbugme/store/sqlite.rb', line 9

def initialize(path: nil)
  @path = path || Dontbugme.config.sqlite_path
  ensure_directory
  ensure_schema
end

Instance Method Details

#cleanup(before:) ⇒ Object



74
75
76
77
# File 'lib/dontbugme/store/sqlite.rb', line 74

def cleanup(before:)
  cutoff = before.is_a?(Time) ? before.iso8601 : before.to_s
  db.execute('DELETE FROM traces WHERE started_at < ?', cutoff)
end

#find_trace(trace_id) ⇒ Object



39
40
41
42
43
44
# File 'lib/dontbugme/store/sqlite.rb', line 39

def find_trace(trace_id)
  row = db.execute('SELECT id, kind, identifier, status, started_at, duration_ms, correlation_id, metadata_json, spans_json, error_json FROM traces WHERE id = ?', trace_id).first
  return nil unless row

  row_to_trace(row)
end

#save_trace(trace) ⇒ Object



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

def save_trace(trace)
  data = trace.to_h
  correlation_id = data[:correlation_id] || data[:metadata]&.dig(:correlation_id)
   = json_safe(data[:metadata])
  spans_json = json_safe(data[:spans])
  error_json = data[:error] ? json_safe(data[:error]) : nil
  db.execute(
    'INSERT OR REPLACE INTO traces (id, kind, identifier, status, started_at, duration_ms, correlation_id, metadata_json, spans_json, error_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
    data[:id],
    data[:kind].to_s,
    sanitize_identifier(data[:identifier]),
    data[:status].to_s,
    data[:started_at],
    data[:duration_ms],
    correlation_id,
    ,
    spans_json,
    error_json
  )
rescue SQLite3::ReadOnlyException
  # Database is read-only (e.g. production deploy with SQLite on read-only filesystem).
  # Silently skip persistence to avoid crashing the app.
end

#search(filters = {}) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/dontbugme/store/sqlite.rb', line 46

def search(filters = {})
  sql = 'SELECT id, kind, identifier, status, started_at, duration_ms, correlation_id, metadata_json, spans_json, error_json FROM traces WHERE 1=1'
  params = []

  if filters[:status]
    sql += ' AND status = ?'
    params << filters[:status].to_s
  end
  if filters[:kind]
    sql += ' AND kind = ?'
    params << filters[:kind].to_s
  end
  if filters[:identifier]
    sql += ' AND identifier LIKE ?'
    params << "%#{filters[:identifier]}%"
  end
  if filters[:correlation_id]
    sql += ' AND correlation_id = ?'
    params << filters[:correlation_id].to_s
  end

  sql += ' ORDER BY started_at DESC LIMIT ?'
  params << (filters[:limit] || filters['limit'] || 100)

  rows = db.execute(sql, *params)
  rows.map { |row| row_to_trace(row) }
end