Class: Card::Query::RefClause

Inherits:
Clause show all
Defined in:
lib/card/query/ref_clause.rb

Constant Summary collapse

REFERENCE_DEFINITIONS =
{
  # syntax:
  # wql query key => [ direction, {reference_type} ]
      # direction      = :out | :in
      # reference_type =  'L' | 'I' | 'P' 

  :refer_to => [ :out, 'L','I' ], :referred_to_by => [ :in, 'L','I' ],
  :link_to  => [ :out, 'L' ],     :linked_to_by   => [ :in, 'L' ],
  :include  => [ :out, 'I' ],     :included_by    => [ :in, 'I' ]
}
REFERENCE_FIELDS =
{
  :out => [ :referer_id, :referee_id ],
  :in  => [ :referee_id, :referer_id ]
}

Instance Attribute Summary

Attributes inherited from Clause

#clause

Instance Method Summary collapse

Methods inherited from Clause

#cast_type, #match_prep, #quote, #safe_sql

Constructor Details

#initialize(key, val, parent) ⇒ RefClause

Returns a new instance of RefClause.



19
20
21
# File 'lib/card/query/ref_clause.rb', line 19

def initialize key, val, parent
  @key, @val, @parent = key, val, parent
end

Instance Method Details

#to_sql(*args) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/card/query/ref_clause.rb', line 23

def to_sql *args
  dir, *type = REFERENCE_DEFINITIONS[ @key.to_sym ]
  field1, field2 = REFERENCE_FIELDS[ dir ]
  cond = []
  if type.present?
    operator = (type.size==1 ? '=' : 'IN')
    quoted_letters = type.map { |letter| "'#{letter}'" } * ', '
    cond << "ref_type #{operator} (#{quoted_letters})"
  end

  sql =  %[select distinct #{field1} as ref_id from card_references]
  if @val == '_none'
    cond << "present = 0"
  else
    cardclause = CardClause.build(:return=>'id', :_parent=>@parent).merge(@val)
    sql << %[ join #{ cardclause.to_sql } as c on #{field2} = c.id]
  end
  sql << %[ where #{ cond * ' and ' }] if cond.any?
  
  "(#{sql})"
end