Class: SQLiteSweep::Aggregator
- Inherits:
-
Object
- Object
- SQLiteSweep::Aggregator
- Defined in:
- lib/sqlitesweep/aggregator.rb
Overview
Thread-safe accumulator for query results. Supports three modes:
:sum - Running total of the first column value from each database.
:average - Running total divided by the number of databases queried.
:list - Delegates to a ResultFile that streams rows to a JSONL file.
For :sum and :average, the first value of the first row from each query result is extracted and added to a running total. This means your query should return a single numeric value (e.g. SELECT count(*) FROM …).
All methods are mutex-protected and safe to call from multiple worker threads.
Instance Attribute Summary collapse
-
#count ⇒ Integer
readonly
Number of databases successfully queried.
-
#error_count ⇒ Integer
readonly
Number of databases that produced errors.
Instance Method Summary collapse
-
#add(result) ⇒ Object
Records a successful query result.
-
#initialize(action, result_file: nil) ⇒ Aggregator
constructor
A new instance of Aggregator.
-
#record_error ⇒ Object
Records a failed query (increments error count).
-
#value ⇒ String
Returns the final aggregated value as a string.
Constructor Details
#initialize(action, result_file: nil) ⇒ Aggregator
Returns a new instance of Aggregator.
31 32 33 34 35 36 37 38 |
# File 'lib/sqlitesweep/aggregator.rb', line 31 def initialize(action, result_file: nil) @action = action @result_file = result_file @mutex = Mutex.new @total = 0.0 @count = 0 @error_count = 0 end |
Instance Attribute Details
#count ⇒ Integer (readonly)
Returns Number of databases successfully queried.
23 24 25 |
# File 'lib/sqlitesweep/aggregator.rb', line 23 def count @count end |
#error_count ⇒ Integer (readonly)
Returns Number of databases that produced errors.
26 27 28 |
# File 'lib/sqlitesweep/aggregator.rb', line 26 def error_count @error_count end |
Instance Method Details
#add(result) ⇒ Object
Records a successful query result.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/sqlitesweep/aggregator.rb', line 43 def add(result) @mutex.synchronize do case @action when :sum, :average result.rows.each do |row| value = row.values.first @total += value.to_f end when :list @result_file&.write(result) end @count += 1 end end |
#record_error ⇒ Object
Records a failed query (increments error count).
59 60 61 |
# File 'lib/sqlitesweep/aggregator.rb', line 59 def record_error @mutex.synchronize { @error_count += 1 } end |
#value ⇒ String
Returns the final aggregated value as a string.
67 68 69 70 71 72 73 74 75 76 |
# File 'lib/sqlitesweep/aggregator.rb', line 67 def value case @action when :sum format_number(@total) when :average @count > 0 ? format_number(@total / @count) : "0" when :list @result_file&.path end end |