Class | Sequel::SQL::BooleanExpression |
In: |
lib/sequel/sql.rb
|
Parent: | ComplexExpression |
Subclass of ComplexExpression where the expression results in a boolean value in SQL.
Take pairs of values (e.g. a hash or array of two element arrays) and converts it to a BooleanExpression. The operator and args used depends on the case of the right (2nd) argument:
If multiple arguments are given, they are joined with the op given (AND by default, OR possible). If negate is set to true, all subexpressions are inverted before used. Therefore, the following expressions are equivalent:
~from_value_pairs(hash) from_value_pairs(hash, :OR, true)
# File lib/sequel/sql.rb, line 890 890: def self.from_value_pairs(pairs, op=:AND, negate=false) 891: pairs = pairs.collect do |l,r| 892: ce = case r 893: when Range 894: new(:AND, new(:>=, l, r.begin), new(r.exclude_end? ? :< : :<=, l, r.end)) 895: when ::Array, ::Sequel::Dataset 896: new(:IN, l, r) 897: when NegativeBooleanConstant 898: new("IS NOT""IS NOT", l, r.constant) 899: when BooleanConstant 900: new(:IS, l, r.constant) 901: when NilClass, TrueClass, FalseClass 902: new(:IS, l, r) 903: when Regexp 904: StringExpression.like(l, r) 905: else 906: new('=''=', l, r) 907: end 908: negate ? invert(ce) : ce 909: end 910: pairs.length == 1 ? pairs.at(0) : new(op, *pairs) 911: end
Invert the expression, if possible. If the expression cannot be inverted, raise an error. An inverted expression should match everything that the uninverted expression did not match, and vice-versa, except for possible issues with SQL NULL (i.e. 1 == NULL is NULL and 1 != NULL is also NULL).
BooleanExpression.invert(:a) # NOT "a"
# File lib/sequel/sql.rb, line 919 919: def self.invert(ce) 920: case ce 921: when BooleanExpression 922: case op = ce.op 923: when :AND, :OR 924: BooleanExpression.new(OPERTATOR_INVERSIONS[op], *ce.args.collect{|a| BooleanExpression.invert(a)}) 925: else 926: BooleanExpression.new(OPERTATOR_INVERSIONS[op], *ce.args.dup) 927: end 928: when StringExpression, NumericExpression 929: raise(Sequel::Error, "cannot invert #{ce.inspect}") 930: when Constant 931: CONSTANT_INVERSIONS[ce] || raise(Sequel::Error, "cannot invert #{ce.inspect}") 932: else 933: BooleanExpression.new(:NOT, ce) 934: end 935: end
Always use an AND operator for & on BooleanExpressions
# File lib/sequel/sql.rb, line 938 938: def &(ce) 939: BooleanExpression.new(:AND, self, ce) 940: end