pg_array_ops.rb

lib/sequel/extensions/pg_array_ops.rb
Last Update: 2022-09-02 09:11:30 -0700

The pg_array_ops extension adds support to Sequel’s DSL to make it easier to call PostgreSQL array functions and operators.

To load the extension:

Sequel.extension :pg_array_ops

The most common usage is passing an expression to Sequel.pg_array_op:

ia = Sequel.pg_array_op(:int_array_column)

If you have also loaded the pg_array extension, you can use Sequel.pg_array as well:

ia = Sequel.pg_array(:int_array_column)

Also, on most Sequel expression objects, you can call the pg_array method:

ia = Sequel[:int_array_column].pg_array

If you have loaded the core_extensions extension, or you have loaded the core_refinements extension and have activated refinements for the file, you can also use Symbol#pg_array:

ia = :int_array_column.pg_array

This creates a Sequel::Postgres::ArrayOp object that can be used for easier querying:

ia[1]     # int_array_column[1]
ia[1][2]  # int_array_column[1][2]

ia.contains(:other_int_array_column)     # @>
ia.contained_by(:other_int_array_column) # <@
ia.overlaps(:other_int_array_column)     # &&
ia.concat(:other_int_array_column)       # ||

ia.push(1)         # int_array_column || 1
ia.unshift(1)      # 1 || int_array_column

ia.any             # ANY(int_array_column)
ia.all             # ALL(int_array_column)
ia.cardinality     # cardinality(int_array_column)
ia.dims            # array_dims(int_array_column)
ia.hstore          # hstore(int_array_column)
ia.hstore(:a)      # hstore(int_array_column, a)
ia.length          # array_length(int_array_column, 1)
ia.length(2)       # array_length(int_array_column, 2)
ia.lower           # array_lower(int_array_column, 1)
ia.lower(2)        # array_lower(int_array_column, 2)
ia.join            # array_to_string(int_array_column, '')
ia.join(':')       # array_to_string(int_array_column, ':')
ia.join(':', ' ')  # array_to_string(int_array_column, ':', ' ')
ia.unnest          # unnest(int_array_column)
ia.unnest(:b)      # unnest(int_array_column, b)

See the PostgreSQL array function and operator documentation for more details on what these functions and operators do.

If you are also using the pg_array extension, you should load it before loading this extension. Doing so will allow you to use PGArray#op to get an ArrayOp, allowing you to perform array operations on array literals.

In order for hstore to automatically wrap the returned value correctly in an HStoreOp, you need to load the pg_hstore_ops extension.

Related module: Sequel::Postgres::ArrayOp