Class: BrainzLab::Development::Store
- Inherits:
-
Object
- Object
- BrainzLab::Development::Store
- Defined in:
- lib/brainzlab/development/store.rb
Overview
SQLite-backed store for development mode events
Constant Summary collapse
- DEFAULT_PATH =
'tmp/brainzlab.sqlite3'
Instance Method Summary collapse
-
#clear! ⇒ Object
Clear all events.
-
#close ⇒ Object
Close the database connection.
-
#initialize(config) ⇒ Store
constructor
A new instance of Store.
-
#insert(service:, event_type:, payload:) ⇒ Object
Insert an event into the store.
-
#query(service: nil, event_type: nil, since: nil, limit: 100) ⇒ Array<Hash>
Query events from the store.
-
#stats ⇒ Object
Get event counts by service.
Constructor Details
#initialize(config) ⇒ Store
Returns a new instance of Store.
13 14 15 16 17 18 |
# File 'lib/brainzlab/development/store.rb', line 13 def initialize(config) @config = config @db_path = config.development_db_path || DEFAULT_PATH @db = nil ensure_database! end |
Instance Method Details
#clear! ⇒ Object
Clear all events
79 80 81 |
# File 'lib/brainzlab/development/store.rb', line 79 def clear! db.execute('DELETE FROM events') end |
#close ⇒ Object
Close the database connection
84 85 86 87 |
# File 'lib/brainzlab/development/store.rb', line 84 def close @db&.close @db = nil end |
#insert(service:, event_type:, payload:) ⇒ Object
Insert an event into the store
24 25 26 27 28 29 |
# File 'lib/brainzlab/development/store.rb', line 24 def insert(service:, event_type:, payload:) db.execute( 'INSERT INTO events (service, event_type, payload, created_at) VALUES (?, ?, ?, ?)', [service.to_s, event_type.to_s, JSON.generate(payload), Time.now.utc.iso8601(3)] ) end |
#query(service: nil, event_type: nil, since: nil, limit: 100) ⇒ Array<Hash>
Query events from the store
37 38 39 40 41 42 43 44 45 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 |
# File 'lib/brainzlab/development/store.rb', line 37 def query(service: nil, event_type: nil, since: nil, limit: 100) conditions = [] params = [] if service conditions << 'service = ?' params << service.to_s end if event_type conditions << 'event_type = ?' params << event_type.to_s end if since conditions << 'created_at >= ?' params << since.utc.iso8601(3) end where_clause = conditions.empty? ? '' : "WHERE #{conditions.join(' AND ')}" params << limit sql = "SELECT id, service, event_type, payload, created_at FROM events #{where_clause} ORDER BY created_at DESC LIMIT ?" db.execute(sql, params).map do |row| { id: row[0], service: row[1].to_sym, event_type: row[2], payload: JSON.parse(row[3], symbolize_names: true), created_at: Time.parse(row[4]) } end end |
#stats ⇒ Object
Get event counts by service
73 74 75 76 |
# File 'lib/brainzlab/development/store.rb', line 73 def stats results = db.execute('SELECT service, COUNT(*) as count FROM events GROUP BY service') results.to_h { |row| [row[0].to_sym, row[1]] } end |