5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-11-16 10:41:41 +00:00
panel/app/jobs/concerns/recursive_rollup.rb

58 lines
1.9 KiB
Ruby
Raw Normal View History

2022-04-23 23:32:20 +00:00
# frozen_string_literal: true
# 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]
# @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]
# @param :interval_previous [String, Symbol]
# @param :interval [String, Symbol]
# @param :operation [Symbol]
# @param :dimensions [Hash]
2022-04-23 23:32:20 +00:00
# @param :beginning [Time]
# @return [Rollup]
def square_rollup(name:, new_name:, interval:, dimensions:, beginning:, operation: :sum)
Rollup.where(name: name, interval: interval)
.where_dimensions(**dimensions)
2022-04-23 23:32:20 +00:00
.where('time >= ?', beginning.try(:"beginning_of_#{interval}"))
.group(*dimensions_to_jsonb_query(dimensions))
.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