mirror of
https://0xacab.org/sutty/sutty
synced 2024-11-16 10:41:41 +00:00
39 lines
1.1 KiB
Ruby
39 lines
1.1 KiB
Ruby
|
# frozen_string_literal: true
|
||
|
|
||
|
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 :new_name [String]
|
||
|
# @param :beginning [Time]
|
||
|
# @return [Rollup]
|
||
|
def recursive_rollup(name:, interval_previous:, interval:, dimensions:, beginning:, operation: :sum, new_name: nil)
|
||
|
Rollup.where(name: name, interval: interval_previous)
|
||
|
.where('time >= ?', beginning.try(:"beginning_of_#{interval}"))
|
||
|
.where_dimensions(**dimensions)
|
||
|
.group(*dimensions_to_jsonb_query(dimensions))
|
||
|
.rollup(new_name || name, interval: interval, update: true) do |rollup|
|
||
|
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
|