Method: Sequel::SQL::BooleanExpression.invert

Defined in:
lib/sequel/sql.rb

.invert(ce) ⇒ Object

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"

1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/sequel/sql.rb', line 1149

def self.invert(ce)
  case ce
  when BooleanExpression
    case op = ce.op
    when :AND, :OR
      BooleanExpression.new(OPERATOR_INVERSIONS[op], *ce.args.map{|a| BooleanExpression.invert(a)})
    when :IN, :"NOT IN"
      BooleanExpression.new(OPERATOR_INVERSIONS[op], *ce.args.dup)
    else
      if ce.args.length == 2
        case ce.args[1]
        when Function, LiteralString, PlaceholderLiteralString
          # Special behavior to not push down inversion in this case because doing so
          # can result in incorrect behavior for ANY/SOME/ALL operators.
          BooleanExpression.new(:NOT, ce)
        else
          BooleanExpression.new(OPERATOR_INVERSIONS[op], *ce.args.dup)
        end
      else
        BooleanExpression.new(OPERATOR_INVERSIONS[op], *ce.args.dup)
      end
    end
  when StringExpression, NumericExpression
    raise(Sequel::Error, "cannot invert #{ce.inspect}")
  when Constant
    CONSTANT_INVERSIONS[ce] || raise(Sequel::Error, "cannot invert #{ce.inspect}")
  else
    BooleanExpression.new(:NOT, ce)
  end
end