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 565 565: def self.from_value_pairs(pairs, op=:AND, negate=false) 566: pairs = pairs.collect do |l,r| 567: ce = case r 568: when Range 569: new(:AND, new(:>=, l, r.begin), new(r.exclude_end? ? :< : :<=, l, r.end)) 570: when ::Array, ::Sequel::Dataset 571: new(:IN, l, r) 572: when NegativeBooleanConstant 573: new("IS NOT""IS NOT", l, r.constant) 574: when BooleanConstant 575: new(:IS, l, r.constant) 576: when NilClass, TrueClass, FalseClass 577: new(:IS, l, r) 578: when Regexp 579: StringExpression.like(l, r) 580: else 581: new('=''=', l, r) 582: end 583: negate ? invert(ce) : ce 584: end 585: pairs.length == 1 ? pairs.at(0) : new(op, *pairs) 586: 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 594 594: def self.invert(ce) 595: case ce 596: when BooleanExpression 597: case op = ce.op 598: when :AND, :OR 599: BooleanExpression.new(OPERTATOR_INVERSIONS[op], *ce.args.collect{|a| BooleanExpression.invert(a)}) 600: else 601: BooleanExpression.new(OPERTATOR_INVERSIONS[op], *ce.args.dup) 602: end 603: when StringExpression, NumericExpression 604: raise(Sequel::Error, "cannot invert #{ce.inspect}") 605: when Constant 606: CONSTANT_INVERSIONS[ce] || raise(Sequel::Error, "cannot invert #{ce.inspect}") 607: else 608: BooleanExpression.new(:NOT, ce) 609: end 610: end
Always use an AND operator for & on BooleanExpressions
# File lib/sequel/sql.rb, line 613 613: def &(ce) 614: BooleanExpression.new(:AND, self, ce) 615: end