2022-04-23 23:32:20 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2022-04-26 19:49:26 +00:00
|
|
|
# Implementa rollups recursivos
|
2022-04-23 23:32:20 +00:00
|
|
|
module RecursiveRollup
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
|
|
|
private
|
|
|
|
|
|
|
|
# Genera un rollup recursivo en base al período anterior y aplica una
|
|
|
|
# operación.
|
|
|
|
#
|
|
|
|
# @param :name [String]
|
|
|
|
# @param :interval_previous [String]
|
|
|
|
# @param :interval [String]
|
|
|
|
# @param :operation [Symbol]
|
|
|
|
# @param :dimensions [Hash]
|
2022-04-30 12:56:19 +00:00
|
|
|
# @param :beginning [Time]
|
|
|
|
# @return [Rollup]
|
|
|
|
def recursive_rollup(name:, interval_previous:, interval:, dimensions:, beginning:, operation: :sum)
|
|
|
|
Rollup.where(name: name, interval: interval_previous, dimensions: dimensions)
|
|
|
|
.where('time >= ?', beginning.try(:"beginning_of_#{interval}"))
|
|
|
|
.group(*dimensions_to_jsonb_query(dimensions))
|
|
|
|
.rollup(name, interval: interval, update: true) do |rollup|
|
|
|
|
rollup.try(operation, :value)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# Genera un nuevo rollup a partir de uno anterior.
|
|
|
|
#
|
|
|
|
# @param :name [String]
|
2022-04-23 23:32:20 +00:00
|
|
|
# @param :new_name [String]
|
2022-04-30 12:56:19 +00:00
|
|
|
# @param :interval_previous [String]
|
|
|
|
# @param :interval [String]
|
|
|
|
# @param :operation [Symbol]
|
|
|
|
# @param :dimensions [Hash]
|
2022-04-23 23:32:20 +00:00
|
|
|
# @param :beginning [Time]
|
|
|
|
# @return [Rollup]
|
2022-04-30 12:56:19 +00:00
|
|
|
def square_rollup(name:, new_name:, interval:, dimensions:, beginning:, operation: :sum)
|
|
|
|
Rollup.where(name: name, interval: interval_previous)
|
|
|
|
.where_dimensions(**dimensions)
|
2022-04-23 23:32:20 +00:00
|
|
|
.where('time >= ?', beginning.try(:"beginning_of_#{interval}"))
|
|
|
|
.group(*dimensions_to_jsonb_query(dimensions))
|
2022-04-30 12:56:19 +00:00
|
|
|
.rollup(new_name, interval: interval, update: true) do |rollup|
|
2022-04-23 23:32:20 +00:00
|
|
|
rollup.try(operation, :value)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# @param :dimensions [Hash]
|
|
|
|
# @return [Array]
|
|
|
|
def dimensions_to_jsonb_query(dimensions)
|
|
|
|
dimensions.keys.map do |key|
|
|
|
|
"dimensions->'#{key}'"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|