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 132 def self.extended(db) 133 db.instance_exec do 134 extend_datasets(IntervalDatasetMethods) 135 add_conversion_proc(1186, Postgres::IntervalDatabaseMethods::PARSER) 136 if respond_to?(:register_array_type) 137 register_array_type('interval', :oid=>1187, :scalar_oid=>1186) 138 end 139 @schema_type_classes[:interval] = ActiveSupport::Duration 140 end 141 end
Return an unquoted string version of the duration object suitable for use as a bound variable.
# File lib/sequel/extensions/pg_interval.rb 51 def self.literal_duration(duration) 52 h = Hash.new(0) 53 duration.parts.each{|unit, value| h[unit] += value} 54 s = String.new 55 56 DURATION_UNITS.each do |unit| 57 if (v = h[unit]) != 0 58 s << "#{v.is_a?(Integer) ? v : sprintf('%0.6f', v)} #{unit} " 59 end 60 end 61 62 if s.empty? 63 '0' 64 else 65 s 66 end 67 end
Public Instance Methods
Handle ActiveSupport::Duration values in bound variables.
# File lib/sequel/extensions/pg_interval.rb 144 def bound_variable_arg(arg, conn) 145 case arg 146 when ActiveSupport::Duration 147 IntervalDatabaseMethods.literal_duration(arg) 148 else 149 super 150 end 151 end
Private Instance Methods
Handle arrays of interval types in bound variables.
# File lib/sequel/extensions/pg_interval.rb 156 def bound_variable_array(a) 157 case a 158 when ActiveSupport::Duration 159 "\"#{IntervalDatabaseMethods.literal_duration(a)}\"" 160 else 161 super 162 end 163 end
Set the :ruby_default value if the default value is recognized as an interval.
# File lib/sequel/extensions/pg_interval.rb 166 def schema_post_process(_) 167 super.each do |a| 168 h = a[1] 169 if h[:type] == :interval && h[:default] =~ /\A'([\w ]+)'::interval\z/ 170 h[:ruby_default] = PARSER.call($1) 171 end 172 end 173 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 182 def typecast_value_interval(value) 183 case value 184 when ActiveSupport::Duration 185 value 186 when Numeric 187 ActiveSupport::Duration.new(value, [[:seconds, value]]) 188 when String 189 PARSER.call(value) 190 else 191 raise Sequel::InvalidValue, "invalid value for interval type: #{value.inspect}" 192 end 193 end