Module: ActiveRecord::Materialized::QueryExpressions

Extended by:
T::Sig
Defined in:
lib/activerecord/materialized/query_expressions.rb

Overview

Portable, aliased Arel aggregate helpers for building a view’s source relation without raw SQL. ‘extend` it into a view (or any object) so the helpers are available where you build the relation.

Examples:

class SalesByCategory < ActiveRecord::Materialized::View
  extend ActiveRecord::Materialized::QueryExpressions
  materialized_from do
    items = Item.arel_table
    Item.group(:category).select(
      items[:category],
      sum_as(items[:amount], as: :revenue),
      count_all_as(as: :order_count)
    )
  end
end

Class Method Summary collapse

Class Method Details

.avg_as(attribute, as:) ⇒ Object



36
37
38
# File 'lib/activerecord/materialized/query_expressions.rb', line 36

def avg_as(attribute, as:)
  attribute.average.as(as.to_s)
end

.count_all_as(as:) ⇒ Object



54
55
56
# File 'lib/activerecord/materialized/query_expressions.rb', line 54

def count_all_as(as:)
  Arel.star.count.as(as.to_s)
end

.count_as(attribute, as:) ⇒ Object



60
61
62
# File 'lib/activerecord/materialized/query_expressions.rb', line 60

def count_as(attribute, as:)
  attribute.count.as(as.to_s)
end

.count_distinct_as(attribute, as:) ⇒ Object



66
67
68
# File 'lib/activerecord/materialized/query_expressions.rb', line 66

def count_distinct_as(attribute, as:)
  attribute.count(true).as(as.to_s)
end

.length(attribute) ⇒ Object



72
73
74
# File 'lib/activerecord/materialized/query_expressions.rb', line 72

def length(attribute)
  Arel::Nodes::NamedFunction.new("LENGTH", [attribute])
end

.max_as(attribute, as:) ⇒ Object



48
49
50
# File 'lib/activerecord/materialized/query_expressions.rb', line 48

def max_as(attribute, as:)
  attribute.maximum.as(as.to_s)
end

.min_as(attribute, as:) ⇒ Object



42
43
44
# File 'lib/activerecord/materialized/query_expressions.rb', line 42

def min_as(attribute, as:)
  attribute.minimum.as(as.to_s)
end

.sum_as(attribute, as:) ⇒ Object



30
31
32
# File 'lib/activerecord/materialized/query_expressions.rb', line 30

def sum_as(attribute, as:)
  attribute.sum.as(as.to_s)
end

.sum_length_as(attribute, as:) ⇒ Object



78
79
80
# File 'lib/activerecord/materialized/query_expressions.rb', line 78

def sum_length_as(attribute, as:)
  length(attribute).sum.as(as.to_s)
end