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