Module: Card::Query::SqlStatement::Joins

Included in:
Card::Query::SqlStatement
Defined in:
lib/card/query/sql_statement/joins.rb

Overview

transform joins from Card::Query::Join objects to SQL string clause

Instance Method Summary collapse

Instance Method Details

#join_clause(join) ⇒ Object



17
18
19
20
21
22
# File 'lib/card/query/sql_statement/joins.rb', line 17

def join_clause join
  subclause = subjoins join
  table = join_table join
  on = on_clause join
  join_clause_parts(join, table, subclause, on).compact.join " "
end

#join_clause_parts(join, table, subclause, on) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/card/query/sql_statement/joins.rb', line 24

def join_clause_parts join, table, subclause, on
  parts = ["\n#{leading_space}", join.side, "JOIN"]
  if join.left? && subclause.present?
    parts + ["(#{table} #{subclause})", on]
  else
    parts + [table, on, subclause]
  end
end

#join_table(join) ⇒ Object



39
40
41
42
43
# File 'lib/card/query/sql_statement/joins.rb', line 39

def join_table join
  to_table = join.to_table
  to_table = "(#{to_table.sql})" if to_table.is_a? CardQuery
  [to_table, join.to_alias].join " "
end

#joins(query = nil) ⇒ Object



6
7
8
9
10
11
# File 'lib/card/query/sql_statement/joins.rb', line 6

def joins query=nil
  query ||= @query
  joins_on_query(query).map do |join|
    join_clause join
  end.flatten.join " "
end

#joins_on_query(query) ⇒ Object



13
14
15
# File 'lib/card/query/sql_statement/joins.rb', line 13

def joins_on_query query
  query.direct_subqueries.unshift(query).map(&:joins).flatten
end

#on_card_conditions(join) ⇒ Object



54
55
56
57
58
# File 'lib/card/query/sql_statement/joins.rb', line 54

def on_card_conditions join
  to = join.to
  explicit = to.conditions_on_join == join ? explicit_conditions(to) : nil
  [explicit, implicit_conditions(to)].compact
end

#on_clause(join) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/card/query/sql_statement/joins.rb', line 45

def on_clause join
  on_conditions = join.conditions
  on_conditions.unshift ["#{join.from_alias}.#{join.from_field}",
                         "#{join.to_alias}.#{join.to_field}"].join(" = ")
  on_conditions += on_card_conditions(join) if join.to.is_a? CardQuery
  on_conditions.reject!(&:blank?)
  "ON #{basic_conditions(on_conditions) * ' AND '}"
end

#subjoins(join) ⇒ Object



33
34
35
36
37
# File 'lib/card/query/sql_statement/joins.rb', line 33

def subjoins join
  return unless join.to.is_a? AbstractQuery

  joins join.to
end