module Sequel::Postgres::InetDatabaseMethods

Methods enabling Database object integration with the inet/cidr types.

Public Class Methods

extended(db) click to toggle source

Reset the conversion procs when extending the Database object, so it will pick up the inet/cidr converter. Also, extend the datasets with support for literalizing the IPAddr types.

# File lib/sequel/extensions/pg_inet.rb, line 39
def self.extended(db)
  db.instance_exec do
    extend_datasets(InetDatasetMethods)

    # :nocov:
    if !defined?(SEQUEL_PG_VERSION_INTEGER) || SEQUEL_PG_VERSION_INTEGER >= 11300
    # :nocov:
      # sequel_pg 1.13.0+ will use inet/cidr conversion procs, but doing so is
      # slower, so don't add the conversion procs if using sequel_pg 1.13.0+.
      meth = IPAddr.method(:new)
      add_conversion_proc(869, meth)
      add_conversion_proc(650, meth)
      if respond_to?(:register_array_type)
        register_array_type('inet', :oid=>1041, :scalar_oid=>869)
        register_array_type('cidr', :oid=>651, :scalar_oid=>650)
      end
    end

    if respond_to?(:register_array_type)
      register_array_type('macaddr', :oid=>1040, :scalar_oid=>829)
    end
    @schema_type_classes[:ipaddr] = IPAddr
  end
end

Public Instance Methods

bound_variable_arg(arg, conn) click to toggle source

Convert an IPAddr arg to a string. Probably not necessary, but done for safety.

Calls superclass method
# File lib/sequel/extensions/pg_inet.rb, line 66
def bound_variable_arg(arg, conn)
  case arg
  when IPAddr
    "#{arg.to_s}/#{arg.instance_variable_get(:@mask_addr).to_s(2).count('1')}"
  else
    super
  end
end

Private Instance Methods

schema_column_type(db_type) click to toggle source

Make the column type detection recognize the inet and cidr types.

Calls superclass method
# File lib/sequel/extensions/pg_inet.rb, line 78
def schema_column_type(db_type)
  case db_type
  when 'inet', 'cidr'
    :ipaddr
  else
    super
  end
end
schema_post_process(_) click to toggle source

Set the :ruby_default value if the default value is recognized as an ip address.

Calls superclass method
# File lib/sequel/extensions/pg_inet.rb, line 88
def schema_post_process(_)
  super.each do |a|
    h = a[1]
    if h[:type] == :ipaddr && h[:default] =~ /\A'([:a-fA-F0-9\.\/]+)'::(?:inet|cidr)\z/
      h[:ruby_default] = IPAddr.new($1)
    end
  end
end
typecast_value_ipaddr(value) click to toggle source

Typecast the given value to an IPAddr object.

# File lib/sequel/extensions/pg_inet.rb, line 98
def typecast_value_ipaddr(value)
  case value
  when IPAddr
    value
  when String
    IPAddr.new(typecast_check_string_length(value, 100))
  else
    raise Sequel::InvalidValue, "invalid value for inet/cidr: #{value.inspect}"
  end
end