module Sequel::Postgres::IntervalDatabaseMethods
Constants
- DURATION_UNITS
- PARSER
Single instance of Parser used for parsing, to save on memory (since the parser has no state).
Public Class Methods
Reset the conversion procs if using the native postgres adapter, and extend the datasets to correctly literalize ActiveSupport::Duration values.
# File lib/sequel/extensions/pg_interval.rb, line 115 def self.extended(db) db.instance_exec do extend_datasets(IntervalDatasetMethods) add_conversion_proc(1186, Postgres::IntervalDatabaseMethods::PARSER) if respond_to?(:register_array_type) register_array_type('interval', :oid=>1187, :scalar_oid=>1186) end @schema_type_classes[:interval] = ActiveSupport::Duration end end
Return an unquoted string version of the duration object suitable for use as a bound variable.
# File lib/sequel/extensions/pg_interval.rb, line 43 def self.literal_duration(duration) h = Hash.new(0) duration.parts.each{|unit, value| h[unit] += value} s = String.new DURATION_UNITS.each do |unit| if (v = h[unit]) != 0 s << "#{v.is_a?(Integer) ? v : sprintf('%0.6f', v)} #{unit} " end end if s.empty? '0' else s end end
Public Instance Methods
Handle ActiveSupport::Duration values in bound variables.
# File lib/sequel/extensions/pg_interval.rb, line 127 def bound_variable_arg(arg, conn) case arg when ActiveSupport::Duration IntervalDatabaseMethods.literal_duration(arg) else super end end
Private Instance Methods
Handle arrays of interval types in bound variables.
# File lib/sequel/extensions/pg_interval.rb, line 139 def bound_variable_array(a) case a when ActiveSupport::Duration "\"#{IntervalDatabaseMethods.literal_duration(a)}\"" else super end end
Set the :ruby_default value if the default value is recognized as an interval.
# File lib/sequel/extensions/pg_interval.rb, line 149 def schema_post_process(_) super.each do |a| h = a[1] if h[:type] == :interval && h[:default] =~ /\A'([\w ]+)'::interval\z/ h[:ruby_default] = PARSER.call($1) end end end
Typecast value correctly to an ActiveSupport::Duration instance. If already an ActiveSupport::Duration, return it. If a numeric argument is given, assume it represents a number of seconds, and create a new ActiveSupport::Duration instance representing that number of seconds. If a String, assume it is in PostgreSQL interval output format and attempt to parse it.
# File lib/sequel/extensions/pg_interval.rb, line 165 def typecast_value_interval(value) case value when ActiveSupport::Duration value when Numeric ActiveSupport::Duration.new(value, [[:seconds, value]]) when String PARSER.call(value) else raise Sequel::InvalidValue, "invalid value for interval type: #{value.inspect}" end end