class Sequel::SQL::DateAdd

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

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) click to toggle source

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.

# File lib/sequel/extensions/date_arithmetic.rb, line 213
def initialize(expr, interval, opts=OPTS)
  @expr = expr

  h = Hash.new(0)
  interval = interval.parts unless interval.is_a?(Hash)
  interval.each do |unit, value|
    # skip nil values
    next unless value

    # Convert weeks to days, as ActiveSupport::Duration can use weeks,
    # but the database-specific literalizers only support days.
    if unit == :weeks
      unit = :days
      value *= 7
    end

    unless DatasetMethods::DURATION_UNITS.include?(unit)
      raise Sequel::Error, "Invalid key used in DateAdd interval hash: #{unit.inspect}"
    end

    # Attempt to prevent SQL injection by users who pass untrusted strings
    # as interval values. It doesn't make sense to support literal strings,
    # due to the numeric adding below.
    if value.is_a?(String)
      raise Sequel::InvalidValue, "cannot provide String value as interval part: #{value.inspect}"
    end

    h[unit] += value
  end

  @interval = Hash[h].freeze
  @cast_type = opts[:cast] if opts[:cast]
  freeze
end