Module: Sequel::SQL::NumericMethods

Included in:
Dataset, LiteralString, GenericExpression, NumericExpression, Symbol
Defined in:
lib/sequel/sql.rb

Overview

This module includes the standard mathematical methods (+, -, *, and /) that are defined on objects that can be used in a numeric context in SQL (Symbol, LiteralString, and SQL::GenericExpression).

Sequel[:a] + :b # "a" + "b"
Sequel[:a] - :b # "a" - "b"
Sequel[:a] * :b # "a" * "b"
Sequel[:a] / :b # "a" / "b"

One exception to this is if + is called with a String or StringExpression, in which case the || operator is used instead of the + operator:

Sequel[:a] + 'b' # "a" || 'b'

Instance Method Summary collapse

Instance Method Details

#+(ce) ⇒ Object

Use || as the operator when called with StringExpression and String instances, and the + operator for LiteralStrings and all other types.



800
801
802
803
804
805
806
807
808
809
# File 'lib/sequel/sql.rb', line 800

def +(ce)
  case ce
  when LiteralString
    NumericExpression.new(:+, self, ce)
  when StringExpression, String
    StringExpression.new(:'||', self, ce)
  else
    NumericExpression.new(:+, self, ce)
  end
end

#coerce(other) ⇒ Object

If the argument given is Numeric, treat it as a NumericExpression, allowing code such as:

1 + Sequel[:x] # SQL: (1 + x)
Sequel.expr{1 - x(y)} # SQL: (1 - x(y))


788
789
790
791
792
793
794
795
796
# File 'lib/sequel/sql.rb', line 788

def coerce(other)
  if other.is_a?(Numeric)
    [SQL::NumericExpression.new(:NOOP, other), self]
  elsif defined?(super)
    super 
  else
    [self, other]
  end
end