Module: ActiveRecordExtended::QueryMethods::WithCTE

Defined in:
lib/active_record_extended/query_methods/with_cte.rb

Defined Under Namespace

Classes: WithChain

Instance Method Summary collapse

Instance Method Details

#build_with(arel) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/active_record_extended/query_methods/with_cte.rb', line 66

def build_with(arel)
  with_statements = with_values.flat_map do |with_value|
    case with_value
    when String, Arel::Nodes::As
      with_value
    when Hash
      build_with_hashed_value(with_value)
    end
  end.compact

  return if with_statements.empty?
  recursive_value? ? arel.with(:recursive, with_statements) : arel.with(with_statements)
end

#build_with_hashed_value(with_value) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/active_record_extended/query_methods/with_cte.rb', line 52

def build_with_hashed_value(with_value)
  with_value.map do |name, expression|
    select =
      case expression
      when String
        Arel.sql("(#{expression})")
      when ActiveRecord::Relation, Arel::SelectManager
        Arel.sql("(#{expression.to_sql})")
      end
    next if select.nil?
    Arel::Nodes::As.new(Arel.sql(PG::Connection.quote_ident(name.to_s)), select)
  end
end

#recursive_valueObject Also known as: recursive_value?



36
37
38
# File 'lib/active_record_extended/query_methods/with_cte.rb', line 36

def recursive_value
  @values[:recursive]
end

#recursive_value=(value) ⇒ Object

Raises:

  • (ImmutableRelation)


31
32
33
34
# File 'lib/active_record_extended/query_methods/with_cte.rb', line 31

def recursive_value=(value)
  raise ImmutableRelation if @loaded
  @values[:recursive] = value
end

#with(opts = :chain, *rest) ⇒ Object



41
42
43
44
# File 'lib/active_record_extended/query_methods/with_cte.rb', line 41

def with(opts = :chain, *rest)
  return WithChain.new(spawn) if opts == :chain
  opts.blank? ? self : spawn.with!(opts, *rest)
end

#with!(opts = :chain, *rest) ⇒ Object



46
47
48
49
50
# File 'lib/active_record_extended/query_methods/with_cte.rb', line 46

def with!(opts = :chain, *rest)
  return WithChain.new(self) if opts == :chain
  self.with_values += [opts] + rest
  self
end

#with_valuesObject



19
20
21
# File 'lib/active_record_extended/query_methods/with_cte.rb', line 19

def with_values
  @values[:with] || []
end

#with_values=(values) ⇒ Object



27
28
29
# File 'lib/active_record_extended/query_methods/with_cte.rb', line 27

def with_values=(values)
  @values[:with] = values
end

#with_values?Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/active_record_extended/query_methods/with_cte.rb', line 23

def with_values?
  !(@values[:with].nil? || @values[:with].empty?)
end