Class: PeriodicCalculations::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/periodic_calculations/query.rb

Constant Summary collapse

INTERVAL_UNIT =
[:day, :week, :month, :year]

Instance Method Summary collapse

Constructor Details

#initialize(relation, query_options) ⇒ Array<Array>

Builds a periodic operation query with PostgresSQL window functions

Parameters:

  • relation (ActiveRecord::Relation)

    Object to build query from

  • query_options (QueryOptions)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/periodic_calculations/query.rb', line 13

def initialize(relation, query_options)
  @relation = relation
  @target_column = query_options.target_column
  @timestamp_column = query_options.timestamp_column
  @operation = query_options.operation.upcase
  @window_function = query_options.cumulative ? "ORDER" : "PARTITION"
  @binds = {
    :unit     => query_options.interval_unit,
    :interval => "1 #{query_options.interval_unit.upcase}",
    :start    => query_options.window_start,
    :end      => query_options.window_end,
    :offset   => "#{query_options.timezone_offset} seconds"
  }
end

Instance Method Details

#executeObject



28
29
30
31
32
33
34
# File 'lib/periodic_calculations/query.rb', line 28

def execute
  ActiveRecord::Base.connection_pool.with_connection do |connection|
    connection.execute(sanitized_sql).map do |elem|
      [Date.parse(elem["frame"]).to_time, elem["result"].to_i]
    end
  end
end

#to_sqlObject



36
37
38
# File 'lib/periodic_calculations/query.rb', line 36

def to_sql
  sanitized_sql
end