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
186 def initialize(expr, interval, opts=OPTS)
187   @expr = expr
188 
189   h = Hash.new(0)
190   interval = interval.parts unless interval.is_a?(Hash)
191   interval.each do |unit, value|
192     # skip nil values
193     next unless value
194 
195     # Convert weeks to days, as ActiveSupport::Duration can use weeks,
196     # but the database-specific literalizers only support days.
197     if unit == :weeks
198       unit = :days
199       value *= 7
200     end
201 
202     unless DatasetMethods::DURATION_UNITS.include?(unit)
203       raise Sequel::Error, "Invalid key used in DateAdd interval hash: #{unit.inspect}"
204     end
205 
206     # Attempt to prevent SQL injection by users who pass untrusted strings
207     # as interval values. It doesn't make sense to support literal strings,
208     # due to the numeric adding below.
209     if value.is_a?(String)
210       raise Sequel::InvalidValue, "cannot provide String value as interval part: #{value.inspect}"
211     end
212 
213     h[unit] += value
214   end
215 
216   @interval = Hash[h].freeze
217   @cast_type = opts[:cast] if opts[:cast]
218   freeze
219 end