Class: Card::Query::ValueClause

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

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(clause, cardclause) ⇒ ValueClause

Returns a new instance of ValueClause.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/card/query/value_clause.rb', line 3

def initialize clause, cardclause
  @cardclause = cardclause

  # bare value shortcut
  @clause = case clause
    when ValueClause; clause.instance_variable_get('@clause')  # FIXME what a hack (what's this for?)
    when Array;     clause
    when String;    ['=', clause]
    when Integer;   ['=', clause]
    else raise("Invalid Condition Clause #{clause.inspect}")
  end

  # operator aliases
  @clause[0] = @clause[0].to_s
  if target = OPERATORS[@clause[0]]
    @clause[0] = target
  end

  # check valid operator
  raise("Invalid Operator #{@clause[0]}") unless OPERATORS.has_key?(@clause[0])

  # handle IN  #FIXME -- shouldn't this handle "not in", too?
  if @clause[0]=='in' and !@clause[1].is_a?(CardClause) and !@clause[1].is_a?(RefClause)
    @clause = [@clause[0], @clause[1..-1]]
  end
end

Instance Method Details

#opObject



30
31
32
# File 'lib/card/query/value_clause.rb', line 30

def op
  @clause[0]
end

#sqlize(v) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/card/query/value_clause.rb', line 34

def sqlize(v)
  case v
    when CardClause, RefClause, SqlCond; v.to_sql
    when Array;    "(" + v.flatten.collect {|x| sqlize(x)}.join(',') + ")"
    else quote(v.to_s)
  end
end

#to_sql(field) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/card/query/value_clause.rb', line 42

def to_sql field
  op,v = @clause
  #warn "to_sql(#{field}), #{op}, #{v}, #{@cardclause.inspect}"
  v=@cardclause.selfname if v=='_self'
  table = @cardclause.table_alias

  #warn "to_sql #{field}, #{v} (#{op})"
  field, v = case field
    when "cond";     return "(#{sqlize(v)})"
    when "name";     ["#{table}.key",      [v].flatten.map(&:to_name).map(&:key)]
    when "content";  ["#{table}.db_content", v]
    else;            ["#{table}.#{safe_sql(field)}", v]
    end

  v = v[0] if Array===v && v.length==1 && op != 'in'
  if op=='~'
    cxn, v = match_prep(v)
    %{#{field} #{cxn.match(sqlize(v))}}
  else
    "#{field} #{op} #{sqlize(v)}"
  end
end