Join the chat at


Pg is the Ruby interface to the PostgreSQL RDBMS.

It works with PostgreSQL 9.3 and later.

A small example usage:

#!/usr/bin/env ruby

require 'pg'

# Output a table of current connections to the DB
conn = PG.connect( dbname: 'sales' )
conn.exec( "SELECT * FROM pg_stat_activity" ) do |result|
  puts "     PID | User             | Query"
  result.each do |row|
    puts " %7d | %-16s | %s " %
      row.values_at('pid', 'usename', 'query')

Build Status

Build Status Github Actions Build Status Appveyor Build Status


  • Ruby 2.4 or newer

  • PostgreSQL 9.3.x or later (with headers, -dev packages, etc).

It usually works with earlier versions of Ruby/PostgreSQL as well, but those are not regularly tested.


We tag and release gems according to the Semantic Versioning principle.

As a result of this policy, you can (and should) specify a dependency on this gem using the Pessimistic Version Constraint with two digits of precision.

For example:

spec.add_dependency 'pg', '~> 1.0'

How To Install

Install via RubyGems:

gem install pg

You may need to specify the path to the 'pg_config' program installed with Postgres:

gem install pg -- --with-pg-config=<path to pg_config>

If you're installing via Bundler, you can provide compile hints like so:

bundle config --with-pg-config=<path to pg_config>

See README-OS_X.rdoc for more information about installing under MacOS X, and README-Windows.rdoc for Windows build/installation instructions.

There's also a Google+ group and a mailing list if you get stuck, or just want to chat about something.

If you want to install as a signed gem, the public certs of the gem signers can be found in the `certs` directory of the repository.

Type Casts

Pg can optionally type cast result values and query parameters in Ruby or native C code. This can speed up data transfers to and from the database, because String allocations are reduced and conversions in (slower) Ruby code can be omitted.

Very basic type casting can be enabled by:

conn.type_map_for_results = conn
# ... this works for result value mapping:
conn.exec("select 1, now(), '{2,3}'::int[]").values
    # => [[1, 2014-09-21 20:51:56 +0200, [2, 3]]]

conn.type_map_for_queries = conn
# ... and this for param value mapping:
conn.exec_params("SELECT $1::text, $2::text, $3::text", [1, 1.23, [2,3]]).values
    # => [["1", "1.2300000000000000E+00", "{2,3}"]]

But Pg's type casting is highly customizable. That's why it's divided into 2 layers:

Encoders / Decoders (ext/pg_*coder.c, lib/pg/*coder.rb)

This is the lower layer, containing encoding classes that convert Ruby objects for transmission to the DBMS and decoding classes to convert received data back to Ruby objects. The classes are namespaced according to their format and direction in PG::TextEncoder, PG::TextDecoder, PG::BinaryEncoder and PG::BinaryDecoder.

It is possible to assign a type OID, format code (text or binary) and optionally a name to an encoder or decoder object. It's also possible to build composite types by assigning an element encoder/decoder. PG::Coder objects can be used to set up a PG::TypeMap or alternatively to convert single values to/from their string representation.

The following PostgreSQL column types are supported by ruby-pg (TE = Text Encoder, TD = Text Decoder, BE = Binary Encoder, BD = Binary Decoder):

The following text formats can also be encoded although they are not used as column type:

  • COPY input and output data: TE, TD

  • Literal for insertion into SQL string: TE

  • SQL-Identifier: TE, TD

PG::TypeMap and derivations (ext/pg_type_map*.c, lib/pg/type_map*.rb)

A TypeMap defines which value will be converted by which encoder/decoder. There are different type map strategies, implemented by several derivations of this class. They can be chosen and configured according to the particular needs for type casting. The default type map is PG::TypeMapAllStrings.

A type map can be assigned per connection or per query respectively per result set. Type maps can also be used for COPY in and out data streaming. See PG::Connection#copy_data .

The following base type maps are available:

  • PG::TypeMapAllStrings - encodes and decodes all values to and from strings (default)

  • PG::TypeMapByClass - selects encoder based on the class of the value to be sent

  • PG::TypeMapByColumn - selects encoder and decoder by column order

  • PG::TypeMapByOid - selects decoder by PostgreSQL type OID

  • PG::TypeMapInRuby - define a custom type map in ruby

The following type maps are prefilled with type mappings from the PG::BasicTypeRegistry :

  • PG::BasicTypeMapForResults - a PG::TypeMapByOid prefilled with decoders for common PostgreSQL column types

  • PG::BasicTypeMapBasedOnResult - a PG::TypeMapByOid prefilled with encoders for common PostgreSQL column types

  • PG::BasicTypeMapForQueries - a PG::TypeMapByClass prefilled with encoders for common Ruby value classes


To report bugs, suggest features, or check out the source with Git, check out the project page.

After checking out the source, run:

$ rake newb

This task will install any missing dependencies, run the tests/specs, and generate the API documentation.

The current maintainers are Michael Granger <[email protected]> and Lars Kanis <[email protected]>.


Copyright © 1997-2019 by the authors.

You may redistribute this software under the same terms as Ruby itself; see or the BSDL file in the source for details.

Portions of the code are from the PostgreSQL project, and are distributed under the terms of the PostgreSQL license, included in the file POSTGRES.

Portions copyright LAIKA, Inc.


See Contributors.rdoc for the many additional fine people that have contributed to this library over the years.

We are thankful to the people at the ruby-list and ruby-dev mailing lists. And to the people who developed PostgreSQL.