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 912 912: def self.from_value_pairs(pairs, op=:AND, negate=false) 913: pairs = pairs.collect do |l,r| 914: ce = case r 915: when Range 916: new(:AND, new(:>=, l, r.begin), new(r.exclude_end? ? :< : :<=, l, r.end)) 917: when ::Array, ::Sequel::Dataset 918: new(:IN, l, r) 919: when NegativeBooleanConstant 920: new("IS NOT""IS NOT", l, r.constant) 921: when BooleanConstant 922: new(:IS, l, r.constant) 923: when NilClass, TrueClass, FalseClass 924: new(:IS, l, r) 925: when Regexp 926: StringExpression.like(l, r) 927: else 928: new('=''=', l, r) 929: end 930: negate ? invert(ce) : ce 931: end 932: pairs.length == 1 ? pairs.at(0) : new(op, *pairs) 933: 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 941 941: def self.invert(ce) 942: case ce 943: when BooleanExpression 944: case op = ce.op 945: when :AND, :OR 946: BooleanExpression.new(OPERTATOR_INVERSIONS[op], *ce.args.collect{|a| BooleanExpression.invert(a)}) 947: else 948: BooleanExpression.new(OPERTATOR_INVERSIONS[op], *ce.args.dup) 949: end 950: when StringExpression, NumericExpression 951: raise(Sequel::Error, "cannot invert #{ce.inspect}") 952: when Constant 953: CONSTANT_INVERSIONS[ce] || raise(Sequel::Error, "cannot invert #{ce.inspect}") 954: else 955: BooleanExpression.new(:NOT, ce) 956: end 957: end
Always use an AND operator for & on BooleanExpressions
# File lib/sequel/sql.rb, line 960 960: def &(ce) 961: BooleanExpression.new(:AND, self, ce) 962: end