BasicTypeMapForQueries class

Simple set of rules for type casting common Ruby types to PostgreSQL.

OIDs of supported type casts are not hard-coded in the sources, but are retrieved from the PostgreSQL’s pg_type table in .

Query params are type casted based on the class of the given value.

Higher level libraries will most likely not make use of this class, but use their own derivation of PG::TypeMapByClass or another set of rules to choose suitable encoders and decoders for the values to be sent.


conn =
# Assign a default ruleset for type casts of input and output values.
conn.type_map_for_queries =
# Execute a query. The Integer param value is typecasted internally by PG::BinaryEncoder::Int8.
# The format of the parameter is set to 0 (text) and the OID of this parameter is set to 20 (int8).
res = conn.exec_params( "SELECT $1", [5] )


encode_array_as R

Public Class Methods

new(connection_or_coder_maps, registry: nil, if_undefined: nil)

Create a new type map for query submission


  • registry: Custom type registry, nil for default global registry

  • if_undefined: Optional Proc object which is called, if no type for an parameter class is not defined in the registry. The Proc object is called with the name and format of the missing type. Its return value is not used.

# File lib/pg/basic_type_map_for_queries.rb, line 51
def initialize(connection_or_coder_maps, registry: nil, if_undefined: nil)
        @coder_maps = build_coder_maps(connection_or_coder_maps, registry: registry)
        @array_encoders_by_klass = array_encoders_by_klass
        @encode_array_as = :array
        @if_undefined = if_undefined || method(:raise_undefined_type).to_proc

Public Instance Methods


Change the mechanism that is used to encode ruby array values

Possible values:

  • :array : Encode the ruby array as a PostgreSQL array. The array element type is inferred from the class of the first array element. This is the default.

  • :json : Encode the ruby array as a JSON document.

  • :record : Encode the ruby array as a composite type row.

  • "_type" : Encode the ruby array as a particular PostgreSQL type. All PostgreSQL array types are supported. If there’s an encoder registered for the elements type, it will be used. Otherwise a string conversion (by value.to_s) is done.

# File lib/pg/basic_type_map_for_queries.rb, line 74
def encode_array_as=(pg_type)
        case pg_type
                when :array
                when :json
                when :record
                when /\A_/
                        raise ArgumentError, "invalid pg_type #{pg_type.inspect}"

        @encode_array_as = pg_type