Created
January 20, 2016 16:27
-
-
Save codesnik/54097d1ede74f819cf33 to your computer and use it in GitHub Desktop.
fetching postgresql data cubes with active record
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def cube(relation, keys) | |
rs = relation.group("cube (#{keys.join(', ')})").pluck(*keys, 'count(*)', "grouping(#{keys.join(', ')})") | |
hs = {} | |
rs.group_by(&:pop).each do |grouping, rows| | |
hs[select_by_bitmask(grouping, keys)] = | |
rows.map do |*indexes, value| | |
[select_by_bitmask(grouping, indexes), value] | |
end.to_h | |
end | |
hs | |
end | |
private | |
def select_by_bitmask(bitmask, array); | |
result = [] | |
array.reverse.each_with_index do |el, i| | |
result.push el if bitmask & 2**i == 0 | |
end | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment