class Sequel::SQL::DateAdd

  1. lib/sequel/extensions/date_arithmetic.rb
Superclass: GenericExpression

The DateAdd class represents the addition of an interval to a date/timestamp expression.

Methods

Public Class

  1. new

Public Instance

  1. cast_type
  2. expr
  3. interval

Attributes

cast_type [R]

The type to cast the expression to. nil if not overridden, in which cast the generic timestamp type for the database will be used.

expr [R]

The expression that the interval is being added to.

interval [R]

The interval added to the expression, as a hash with symbol keys.

Public Class methods

new(expr, interval, opts=OPTS)

Supports two types of intervals:

Hash

Used directly, but values cannot be plain strings.

ActiveSupport::Duration

Converted to a hash using the interval’s parts.

[show source]
    # File lib/sequel/extensions/date_arithmetic.rb
214 def initialize(expr, interval, opts=OPTS)
215   @expr = expr
216 
217   h = Hash.new(0)
218   interval = interval.parts unless interval.is_a?(Hash)
219   interval.each do |unit, value|
220     # skip nil values
221     next unless value
222 
223     # Convert weeks to days, as ActiveSupport::Duration can use weeks,
224     # but the database-specific literalizers only support days.
225     if unit == :weeks
226       unit = :days
227       value *= 7
228     end
229 
230     unless DatasetMethods::DURATION_UNITS.include?(unit)
231       raise Sequel::Error, "Invalid key used in DateAdd interval hash: #{unit.inspect}"
232     end
233 
234     # Attempt to prevent SQL injection by users who pass untrusted strings
235     # as interval values. It doesn't make sense to support literal strings,
236     # due to the numeric adding below.
237     if value.is_a?(String)
238       raise Sequel::InvalidValue, "cannot provide String value as interval part: #{value.inspect}"
239     end
240 
241     h[unit] += value
242   end
243 
244   @interval = Hash[h].freeze
245   @cast_type = opts[:cast] if opts[:cast]
246   freeze
247 end