# pg_range.rb

Path: | lib/sequel/extensions/pg_range.rb
Last Update: | Sun May 19 07:59:58 +0000 2013

The pg_range extension adds support for the PostgreSQL 9.2+ range types to Sequel. PostgreSQL range types are similar to ruby‘s Range class, representating an array of values. However, they are more flexible than ruby‘s ranges, allowing exclusive beginnings and endings (ruby‘s range only allows exclusive endings), and unbounded beginnings and endings (which ruby‘s range does not support).

This extension integrates with Sequel‘s native postgres adapter, so that when range type values are retrieved, they are parsed and returned as instances of Sequel::Postgres::PGRange. PGRange mostly acts like a Range, but it‘s not a Range as not all PostgreSQL range type values would be valid ruby ranges. If the range type value you are using is a valid ruby range, you can call PGRange#to_range to get a Range. However, if you call PGRange#to_range on a range type value uses features that ruby‘s Range does not support, an exception will be raised.

In addition to the parser, this extension comes with literalizers for both PGRange and Range that use the standard Sequel literalization callbacks, so they work on all adapters.

To turn an existing Range into a PGRange, use Sequel.pg_range:

      Sequel.pg_range(range)

If you have loaded the core_extensions extension), you can also use Range#pg_range:

      range.pg_range

You may want to specify a specific range type:

      Sequel.pg_range(range, :daterange)
      range.pg_range(:daterange)

If you specify the range database type, Sequel will automatically cast the value to that type when literalizing.

If you would like to use range columns in your model objects, you probably want to modify the schema parsing/typecasting so that it recognizes and correctly handles the range type columns, which you can do by:

      DB.extension :pg_range

If you are not using the native postgres adapter, you probably also want to use the typecast_on_load plugin in the model, and set it to typecast the range type column(s) on load.

This extension integrates with the pg_array extension. If you plan to use arrays of range types, load the pg_array extension before the pg_range extension:

      DB.extension :pg_array, :pg_range

### Required files

adapters/utils/pg_types

[Validate]