PostgreSQL
suggest changeRuby talks to PostgreSQL through the pg gem. It wraps libpq, the official C client library. Everything else is built on top of it:
pg: the driver. It handles connections, parameterized queries, prepared statements,COPY, streaming results andLISTEN/NOTIFY.- Sequel and Active Record: higher-level libraries that use
pgunderneath. They add query builders, models, migrations and connection pools, and they support PostgreSQL types such as arrays andjsonb.
The examples below were run against PostgreSQL 18 with Ruby 4.0, pg 1.7, Sequel 5.109 and Active Record 8.1. For the general picture (drivers vs. query builders vs. ORMs, migrations) see Relational databases. The same tasks for other databases are covered in MySQL and SQLite.
Installing
$ gem install pg
On Windows, and on common Linux and macOS platforms, RubyGems installs a precompiled gem that already contains libpq, so nothing else is needed. If it has to compile from source, install the client headers first:
# Debian / Ubuntu
$ sudo apt install libpq-dev
# macOS
$ brew install libpq
$ gem install pg -- --with-pg-config=$(brew --prefix libpq)/bin/pg_config
In a Gemfile:
gem "pg", "~> 1.6"
The examples use a database shop owned by a role app:
CREATE USER app PASSWORD 'secret';
CREATE DATABASE shop OWNER app;
Connecting
PG.connect takes a hash of libpq connection parameters, a connection string or a URL:
require 'pg'
conn = PG.connect(
host: '127.0.0.1',
dbname: 'shop',
user: 'app',
password: ENV.fetch('PGPASSWORD', 'secret'),
connect_timeout: 5,
application_name: 'inventory-script'
)
puts conn.server_version
puts conn.exec('SELECT version()').getvalue(0, 0)[0, 18]
puts PG::VERSION
puts PG.library_version
p [conn.host, conn.db, conn.user]
puts conn.parameter_status('server_encoding')
conn.close
url = "postgres://app:secret@127.0.0.1:#{ENV.fetch('PGPORT', 5432)}/shop?sslmode=disable"
PG.connect(url) { |c| puts c.exec('SELECT current_database()').getvalue(0, 0) }
180004
PostgreSQL 18.4 on
1.7.0
180006
["127.0.0.1", "shop", "app"]
UTF8
shop
server_version and library_version are integers: 180004 means 18.4. The second number is the version of the libpq bundled with the gem.
Any parameter you leave out falls back to the standard libpq environment variables (PGHOST, PGPORT, PGDATABASE, PGUSER, PGPASSWORD) and then to defaults (port 5432). That's why the example above doesn't pass a port. Many hosting platforms give you a single DATABASE_URL that you can pass straight to PG.connect.
With a block, PG.connect closes the connection when the block ends. Use sslmode: 'verify-full' (with sslrootcert:) to require TLS and check the server's certificate when you connect over a network.
Creating a table
exec runs one or more SQL statements given as a single string:
conn.exec('DROP TABLE IF EXISTS order_items, orders, products')
conn.exec(<<~SQL)
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price numeric(10,2) NOT NULL CHECK (price >= 0),
stock integer NOT NULL DEFAULT 0,
tags text[] NOT NULL DEFAULT '{}',
attrs jsonb NOT NULL DEFAULT '{}',
created_at timestamptz NOT NULL DEFAULT now()
)
SQL
GENERATED ALWAYS AS IDENTITY is the modern replacement for serial. text[] is an array column and jsonb stores binary JSON that you can index and query.
Server messages such as NOTICE: table "orders" does not exist, skipping are printed to stderr. Use conn.set_notice_processor { |msg| ... } to send them somewhere else or ignore them.
Inserting with parameters
exec_params sends the SQL and the values separately. Placeholders are numbered $1, $2 and so on, and values are never parsed as SQL:
sql = 'INSERT INTO products (sku, name, price, stock) VALUES ($1, $2, $3, $4) RETURNING id, created_at'
res = conn.exec_params(sql, ['KB-001', 'Mechanical keyboard', '129.99', 12])
p res.ntuples, res.cmd_tuples, res.cmd_status
p res[0]
[['MS-002', 'Wireless mouse', 39.5, 40],
['MN-003', '27" monitor', 289, 5],
['CB-004', 'USB-C cable ⚡', 9.99, 0]].each do |row|
conn.exec_params('INSERT INTO products (sku, name, price, stock) VALUES ($1, $2, $3, $4)', row)
end
1
1
"INSERT 0 1"
{"id" => "1", "created_at" => "2026-10-17 22:46:49.585795+02"}
PostgreSQL has no "last insert id" function. Add RETURNING to get generated columns back from an INSERT, UPDATE or DELETE. ntuples is the number of rows returned and cmd_tuples is the number of rows the command changed.
Values are sent as text: pg calls to_s on each one, and the server converts it to the column type. nil becomes NULL.
Querying
exec and exec_params return a PG::Result. It's Enumerable, and each row is a hash with string keys:
res = conn.exec('SELECT id, sku, name, price, stock, created_at FROM products ORDER BY id')
p res.fields
p res.ntuples
res.each { |row| puts format('%s %-7s %-20s %8s %3s', *row.values_at('id', 'sku', 'name', 'price', 'stock')) }
p res.values.first
p res.column_values(1)
p res[0]['price'].class
res.clear
["id", "sku", "name", "price", "stock", "created_at"]
4
1 KB-001 Mechanical keyboard 129.99 12
2 MS-002 Wireless mouse 39.50 40
3 MN-003 27" monitor 289.00 5
4 CB-004 USB-C cable ⚡ 9.99 0
["1", "KB-001", "Mechanical keyboard", "129.99", "12", "2026-10-17 22:46:49.585795+02"]
["KB-001", "MS-002", "MN-003", "CB-004"]
String
By default every value is a String (or nil for NULL), whatever the column type. values returns rows as arrays, column_values(i) returns one column and getvalue(row, col) returns a single value. clear frees the result's memory right away instead of waiting for the garbage collector, which helps with big results.
Type casting with type maps
To get Ruby types back, install type maps on the connection. BasicTypeMapForResults decodes result columns based on their PostgreSQL type, and BasicTypeMapForQueries encodes Ruby parameters:
conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
row = conn.exec_params('SELECT id, price, stock, tags, attrs, created_at FROM products WHERE sku = $1', ['KB-001']).first
row.each { |k, v| puts "#{k.ljust(10)} #{v.class.to_s.ljust(10)} #{v.inspect}" }
p conn.exec_params('SELECT $1::int + 1 AS n, $2::text[] AS a, $3::boolean AS b', [41, %w[a b], true]).first
id Integer 1
price BigDecimal 0.12999e3
stock Integer 12
tags Array []
attrs Hash {}
created_at Time 2026-10-17 22:46:49.585795 +0200
{"n" => 42, "a" => ["a", "b"], "b" => true}
numeric becomes BigDecimal (so money doesn't get floating-point rounding), arrays become Array, jsonb becomes Hash and timestamptz becomes Time. 0.12999e3 is how BigDecimal#inspect writes 129.99.
The type maps read the type catalog when you create them, so create them once per connection. Without BasicTypeMapForQueries, a Ruby array is sent as ["a", "b"], which PostgreSQL rejects as a malformed array literal. You can encode it yourself with PG::TextEncoder::Array.new.encode(%w[a b]), which gives {a,b}.
Prepared statements
exec_params sends the SQL every time. prepare parses and plans a statement once per connection, under a name, and exec_prepared runs it with new values:
conn.prepare('take_stock', 'UPDATE products SET stock = stock - $1 WHERE sku = $2 AND stock >= $1 RETURNING stock')
res = conn.exec_prepared('take_stock', [3, 'KB-001'])
p res.cmd_tuples, res.getvalue(0, 0)
res = conn.exec_prepared('take_stock', [3, 'CB-004'])
p res.cmd_tuples, res.ntuples
p conn.exec("SELECT name, parameter_types FROM pg_prepared_statements").to_a
conn.exec('DEALLOCATE take_stock')
1
"9"
0
0
[{"name" => "take_stock", "parameter_types" => "{integer,text}"}]
The second update matches no row because CB-004 has no stock, so cmd_tuples is 0. That's how you find out a conditional UPDATE didn't apply.
A prepared statement lives until DEALLOCATE or until the connection closes. Preparing the same name twice raises PG::DuplicatePstatement. Only prepare statements you run many times. For one-off queries exec_params is just as safe and simpler.
Handling errors
Every server error raises a subclass of PG::Error named after its SQLSTATE code, so you can rescue exactly the error you expect:
begin
conn.exec_params('INSERT INTO products (sku, name, price) VALUES ($1, $2, $3)', ['KB-001', 'Duplicate', 1])
rescue PG::UniqueViolation => e
puts e.class.ancestors.take(4).inspect
puts e.result.error_field(PG::PG_DIAG_SQLSTATE)
puts e.result.error_field(PG::PG_DIAG_CONSTRAINT_NAME)
puts e.result.error_field(PG::PG_DIAG_MESSAGE_DETAIL)
end
begin
conn.exec_params('INSERT INTO products (sku, name, price) VALUES ($1, $2, $3)', ['XX-999', 'Negative', -5])
rescue PG::CheckViolation => e
puts e.message.lines.first
end
begin
conn.exec('SELECT * FROM no_such_table')
rescue PG::Error => e
puts "#{e.class}: #{e.result.error_field(PG::PG_DIAG_MESSAGE_PRIMARY)}"
end
[PG::UniqueViolation, PG::IntegrityConstraintViolation, PG::ServerError, PG::Error]
23505
products_sku_key
Key (sku)=(KB-001) already exists.
ERROR: new row for relation "products" violates check constraint "products_price_check"
PG::UndefinedTable: relation "no_such_table" does not exist
e.result.error_field gives the structured parts of the error, such as the constraint name, which is more reliable than parsing the message. Classes you'll often rescue: PG::UniqueViolation, PG::ForeignKeyViolation, PG::SerializationFailure and PG::TRDeadlockDetected (retry the transaction), PG::QueryCanceled (statement timeout) and PG::ConnectionBad (can't connect, or the connection was lost).
Transactions
conn.transaction sends BEGIN, runs the block, then sends COMMIT. If the block raises, it sends ROLLBACK and re-raises:
def move_stock(conn, from, to, qty)
conn.transaction do |c|
res = c.exec_params('UPDATE products SET stock = stock - $1 WHERE sku = $2 AND stock >= $1', [qty, from])
raise "not enough stock in #{from}" if res.cmd_tuples.zero?
c.exec_params('UPDATE products SET stock = stock + $1 WHERE sku = $2', [qty, to])
end
end
move_stock(conn, 'MS-002', 'CB-004', 10)
begin
move_stock(conn, 'MN-003', 'CB-004', 100)
rescue => e
puts "rolled back: #{e.message}"
end
conn.exec("SELECT sku, stock FROM products WHERE sku IN ('MS-002', 'MN-003', 'CB-004') ORDER BY sku")
.each { |r| p r }
p conn.transaction_status == PG::PQTRANS_IDLE
rolled back: not enough stock in MN-003
{"sku" => "CB-004", "stock" => "10"}
{"sku" => "MN-003", "stock" => "5"}
{"sku" => "MS-002", "stock" => "30"}
true
An error aborts the whole transaction
PostgreSQL differs from MySQL and SQLite here. After any statement fails inside a transaction, the server rejects every later statement until you roll back. Rescuing the Ruby exception doesn't change that:
begin
conn.transaction do
conn.exec("UPDATE products SET stock = stock + 1 WHERE sku = 'KB-001'")
begin
conn.exec_params('INSERT INTO products (sku, name, price) VALUES ($1, $2, $3)', ['KB-001', 'dup', 1])
rescue PG::UniqueViolation
puts 'duplicate, carrying on'
end
conn.exec("SELECT stock FROM products WHERE sku = 'KB-001'")
end
rescue PG::InFailedSqlTransaction => e
puts e.message.lines.first
end
duplicate, carrying on
ERROR: current transaction is aborted, commands ignored until end of transaction block
To recover from an expected error and keep going, wrap the risky statement in a savepoint and roll back to it:
conn.transaction do
conn.exec("UPDATE products SET stock = stock + 1 WHERE sku = 'KB-001'")
begin
conn.exec('SAVEPOINT before_insert')
conn.exec_params('INSERT INTO products (sku, name, price) VALUES ($1, $2, $3)', ['KB-001', 'dup', 1])
conn.exec('RELEASE SAVEPOINT before_insert')
rescue PG::UniqueViolation
conn.exec('ROLLBACK TO SAVEPOINT before_insert')
puts 'duplicate, carrying on'
end
puts conn.exec("SELECT stock FROM products WHERE sku = 'KB-001'").getvalue(0, 0)
end
duplicate, carrying on
10
Sequel (DB.transaction(savepoint: true)) and Active Record (transaction(requires_new: true)) create savepoints for you. Often you don't need one at all: ON CONFLICT, shown next, avoids the error in the first place.
The default isolation level is READ COMMITTED. For stricter guarantees run SET TRANSACTION ISOLATION LEVEL SERIALIZABLE as the first statement in the transaction, and retry the whole transaction when it raises PG::SerializationFailure.
Upserts with ON CONFLICT
INSERT ... ON CONFLICT inserts a row, or updates (or skips) it when a unique constraint would be violated. EXCLUDED refers to the row you tried to insert:
upsert = <<~SQL
INSERT INTO products (sku, name, price, stock) VALUES ($1, $2, $3, $4)
ON CONFLICT (sku) DO UPDATE
SET price = EXCLUDED.price, stock = products.stock + EXCLUDED.stock
RETURNING id, stock, (xmax = 0) AS inserted
SQL
p conn.exec_params(upsert, ['KB-001', 'Mechanical keyboard', 119.99, 5]).first
p conn.exec_params(upsert, ['WC-006', 'Webcam', 79, 8]).first
res = conn.exec_params(<<~SQL, ['KB-001', 'dup', 1])
INSERT INTO products (sku, name, price) VALUES ($1, $2, $3)
ON CONFLICT (sku) DO NOTHING
SQL
p res.cmd_tuples
{"id" => "1", "stock" => "15", "inserted" => "f"}
{"id" => "10", "stock" => "8", "inserted" => "t"}
0
(xmax = 0) is a common trick to tell whether the row was inserted (t) or updated (f). The new webcam got id 10, not 5, because each failed insert earlier still used up a value from the identity sequence. Gaps in ids are normal; don't rely on ids being consecutive.
Arrays and JSONB
With the type maps installed, Ruby arrays and hashes go straight into text[] and jsonb columns. To match a value against a list, pass an array with = ANY($1) instead of building an IN (...) list by hand:
conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
conn.exec_params('UPDATE products SET tags = $1, attrs = $2 WHERE sku = $3',
[%w[input wireless], { color: 'black', dpi: 4000 }, 'MS-002'])
conn.exec_params('UPDATE products SET tags = $1, attrs = $2 WHERE sku = $3',
[%w[input mechanical], { color: 'white', layout: 'ISO' }, 'KB-001'])
p conn.exec_params('SELECT sku FROM products WHERE sku = ANY($1) ORDER BY sku', [%w[KB-001 MN-003 XX-000]]).column_values(0)
p conn.exec_params('SELECT sku FROM products WHERE $1 = ANY(tags) ORDER BY sku', ['input']).column_values(0)
p conn.exec_params('SELECT sku, attrs FROM products WHERE attrs @> $1', [{ color: 'white' }]).to_a
p conn.exec("SELECT sku, attrs->>'color' AS color, (attrs->>'dpi')::int AS dpi FROM products WHERE attrs ? 'color' ORDER BY sku").to_a
["KB-001", "MN-003"]
["KB-001", "MS-002"]
[{"sku" => "KB-001", "attrs" => {"color" => "white", "layout" => "ISO"}}]
[{"sku" => "KB-001", "color" => "white", "dpi" => nil}, {"sku" => "MS-002", "color" => "black", "dpi" => 4000}]
= ANY($1) takes one parameter however long the list is, so the SQL text stays the same and can be prepared. @> means "contains", ->> extracts a field as text and ? tests whether a key exists. A GIN index (CREATE INDEX ON products USING gin (attrs)) makes @> and ? fast on large tables.
Bulk loading with COPY
Running INSERT once per row costs a network round trip each time. COPY streams rows in a single command and is the fastest way to load data:
conn.exec('CREATE TEMP TABLE events (id bigint, kind text, payload jsonb)')
enc = PG::TextEncoder::CopyRow.new
t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
conn.copy_data('COPY events (id, kind, payload) FROM STDIN', enc) do
100_000.times do |i|
conn.put_copy_data([i, i.even? ? 'view' : 'click', %({"n": #{i}})])
end
end
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - t
puts conn.exec('SELECT count(*) FROM events').getvalue(0, 0)
puts format("copied in %.2fs", elapsed)
dec = PG::TextDecoder::CopyRow.new
rows = []
conn.copy_data("COPY (SELECT id, kind FROM events WHERE id < 3 ORDER BY id) TO STDOUT", dec) do
while (row = conn.get_copy_data)
rows << row
end
end
p rows
csv = +''
conn.copy_data("COPY (SELECT sku, price FROM products ORDER BY id LIMIT 2) TO STDOUT WITH (FORMAT csv, HEADER)") do
while (line = conn.get_copy_data)
csv << line
end
end
puts csv
100000
copied in 0.06s
[["0", "view"], ["1", "click"], ["2", "view"]]
sku,price
KB-001,119.99
MS-002,39.50
PG::TextEncoder::CopyRow turns a Ruby array into one line of COPY text format, escaping tabs, newlines and nil for you. copy_data ends the COPY when the block finishes, or aborts it if the block raises. COPY ... TO STDOUT WITH (FORMAT csv) is an easy way to export a query as CSV.
Streaming large results
exec loads the whole result into memory before it returns. To process millions of rows, use single-row mode: send the query asynchronously, switch the mode on, then iterate with stream_each:
conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
conn.send_query_params('SELECT g AS n, md5(g::text) AS h FROM generate_series(1, $1::int) AS g', [1_000_000])
conn.set_single_row_mode
count = 0
sum = 0
conn.get_result.stream_each do |row|
count += 1
sum += row['n']
end
conn.get_last_result
puts "#{count} rows, sum=#{sum}"
1000000 rows, sum=500000500000
Memory use stays flat because only one row is held at a time. set_chunked_rows_mode(1000) (libpq 17 and later) works the same way but fetches rows in batches, which has less overhead per row. Read the stream to the end (get_last_result drains anything left) before you run another query on the connection. Another option is a server-side cursor (DECLARE c CURSOR FOR ... inside a transaction, then FETCH 1000 FROM c in a loop). Sequel's paged_each does that for you.
LISTEN and NOTIFY
PostgreSQL has a built-in publish/subscribe channel. One connection runs LISTEN, and any session can send a message with NOTIFY or pg_notify():
listener = Thread.new do
PG.connect(host: '127.0.0.1', dbname: 'shop', user: 'app', password: 'secret') do |c|
c.exec('LISTEN stock_changed')
received = 0
while received < 3
c.wait_for_notify(5) do |channel, pid, payload|
puts "#{channel}: #{payload}"
received += 1
end || break
end
c.exec('UNLISTEN *')
end
end
sleep 0.2 # give the listener time to run LISTEN
conn.exec_params('SELECT pg_notify($1, $2)', ['stock_changed', 'KB-001'])
conn.transaction do
conn.exec_params('SELECT pg_notify($1, $2)', ['stock_changed', 'MS-002'])
conn.exec_params('SELECT pg_notify($1, $2)', ['stock_changed', 'MN-003'])
puts 'committing'
end
listener.join
stock_changed: KB-001
committing
stock_changed: MS-002
stock_changed: MN-003
Notifications are sent when the transaction commits, which is why the last two arrive after committing. wait_for_notify(timeout) returns nil on timeout. The listener needs its own long-lived connection, so it doesn't work through PgBouncer in transaction mode. Payloads are limited to 8000 bytes, so send an id and look the record up rather than sending the whole record.
SQL injection and escaping
Never interpolate input into SQL:
# DON'T: name = "x' OR '1'='1" returns every row
conn.exec("SELECT * FROM products WHERE name = '#{name}'")
Use $1 parameters. When you have to build SQL text, for example for a dynamic ORDER BY column, use escape_literal for values and escape_identifier for names, and check identifiers against an allow-list:
name = "O'Reilly; DROP TABLE products; --"
puts conn.escape_literal(name)
puts conn.escape_identifier('weird "column"')
sort_column = 'price'
allowed = %w[sku name price stock]
raise ArgumentError, 'bad column' unless allowed.include?(sort_column)
sql = "SELECT sku FROM products WHERE name <> #{conn.escape_literal(name)} ORDER BY #{conn.escape_identifier(sort_column)} DESC LIMIT 2"
puts sql
p conn.exec(sql).column_values(0)
'O''Reilly; DROP TABLE products; --'
"weird ""column"""
SELECT sku FROM products WHERE name <> 'O''Reilly; DROP TABLE products; --' ORDER BY "price" DESC LIMIT 2
["MN-003", "KB-001"]
escape_literal adds the surrounding quotes itself, so don't wrap its result in another pair.
Timeouts and broken connections
A slow query can hold a connection, and its locks, for a long time. Set statement_timeout so the server cancels it:
conn.exec('SET statement_timeout = 200')
begin
conn.exec('SELECT pg_sleep(1)')
rescue PG::QueryCanceled => e
puts e.message.lines.first
end
conn.exec('RESET statement_timeout')
begin
PG.connect(host: '127.0.0.1', port: 1, dbname: 'shop', user: 'app', password: 'secret', connect_timeout: 2)
rescue PG::ConnectionBad => e
puts e.class
end
p conn.status == PG::CONNECTION_OK
ERROR: canceling statement due to statement timeout
PG::ConnectionBad
true
The value is in milliseconds. You can also set it for every session with options: '-c statement_timeout=5000' in PG.connect, or for a role with ALTER ROLE app SET statement_timeout = '5s'. After a network failure, conn.status is PG::CONNECTION_BAD. Call conn.reset to reconnect with the same parameters, or let a pool replace the connection.
Threads and connection pools
A PG::Connection runs one query at a time, so don't share one between threads. Sequel and Active Record have their own pools. With the raw driver, use the connection_pool gem:
require 'pg'
require 'connection_pool'
POOL = ConnectionPool.new(size: 5, timeout: 3) do
PG.connect(host: '127.0.0.1', dbname: 'shop', user: 'app', password: 'secret')
end
threads = 10.times.map do
Thread.new do
POOL.with { |c| c.exec('SELECT pg_backend_pid(), pg_sleep(0.1)').getvalue(0, 0) }
end
end
pids = threads.map(&:value)
puts "#{pids.size} queries on #{pids.uniq.size} connections"
POOL.shutdown(&:close)
10 queries on 5 connections
pg releases the GVL while it waits for the server, so other threads keep running during a query. It also works with a Fiber scheduler (see Fibers and Async). Each PostgreSQL connection is a separate server process, so keep the total number of connections small. Database connection pooling covers pool sizing, PgBouncer and forking servers.
Sequel
Sequel's postgres adapter uses pg and supports PostgreSQL types through extensions:
require 'sequel'
DB = Sequel.connect(adapter: 'postgres', host: '127.0.0.1', database: 'shop',
user: 'app', password: 'secret', max_connections: 5)
DB.extension :pg_array, :pg_json
Sequel.extension :pg_array_ops, :pg_json_ops
DB.create_table!(:orders) do
primary_key :id, type: :Bignum, identity: true
foreign_key :product_id, :products, type: :Bignum, null: false
Integer :quantity, null: false
jsonb :details
timestamptz :created_at, null: false, default: Sequel::CURRENT_TIMESTAMP
end
products = DB[:products]
orders = DB[:orders]
p products.where(Sequel.pg_array_op(:tags).contains(Sequel.pg_array(['input']))).order(:sku).select_map(:sku)
p products.where(Sequel.pg_jsonb_op(:attrs).get_text('color') => 'black').get(:name)
kb = products.first(sku: 'KB-001')
DB.transaction do
id = orders.insert(product_id: kb[:id], quantity: 2, details: Sequel.pg_jsonb(gift: true, note: 'Happy birthday'))
products.where(id: kb[:id]).update(stock: Sequel[:stock] - 2)
puts "order #{id}"
end
p products.returning(:sku, :stock).where { stock > 20 }.update(stock: Sequel[:stock] - 1)
p products.insert_conflict(target: :sku, update: { price: Sequel[:excluded][:price] })
.insert_sql(sku: 'KB-001', name: 'Mechanical keyboard', price: 109.99)
d = orders.first[:details]
p d.class, d['note']
n = 0
DB[:products].order(:id).paged_each(rows_per_fetch: 2) { n += 1 }
puts n
begin
products.insert(sku: 'KB-001', name: 'dup', price: 1)
rescue Sequel::UniqueConstraintViolation => e
puts e.class
end
["KB-001", "MS-002"]
"Wireless mouse"
order 1
[{sku: "MS-002", stock: 29}]
"INSERT INTO \"products\" (\"sku\", \"name\", \"price\") VALUES ('KB-001', 'Mechanical keyboard', 109.99) ON CONFLICT (\"sku\") DO UPDATE SET \"price\" = \"excluded\".\"price\""
Sequel::Postgres::JSONBHash
"Happy birthday"
5
Sequel::UniqueConstraintViolation
returning maps to RETURNING, and insert_conflict maps to ON CONFLICT. With the pg_json extension, jsonb values come back as JSONBHash, which behaves like a Hash. On PostgreSQL, paged_each uses a cursor inside a transaction, so it streams any number of rows with constant memory. Installing the optional sequel_pg gem makes fetching rows faster.
Active Record without Rails
Use adapter: 'postgresql'. Active Record reads the table schema, so array and jsonb columns become Ruby arrays and hashes automatically:
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: '127.0.0.1',
database: 'shop',
username: 'app',
password: 'secret',
pool: 5
)
class Product < ActiveRecord::Base
has_many :orders
validates :sku, presence: true, uniqueness: true
end
class Order < ActiveRecord::Base
belongs_to :product
end
p Product.where('price > ?', 100).order(:price).pluck(:sku, :price)
p Product.where('? = ANY(tags)', 'wireless').pluck(:sku)
p Product.where("attrs->>'color' = ?", 'white').pick(:sku)
mouse = Product.find_by!(sku: 'MS-002')
p mouse.tags, mouse.attrs
Product.transaction do
mouse.orders.create!(quantity: 3, details: { gift: false })
mouse.decrement!(:stock, 3)
end
p mouse.reload.stock
p Order.last.details
p Product.joins(:orders).group(:sku).order(:sku).sum(:quantity)
res = Product.upsert_all([{ sku: 'KB-001', name: 'Mechanical keyboard', price: 99.99 },
{ sku: 'HS-007', name: 'Headset', price: 59 }],
unique_by: :sku, update_only: [:price], returning: %w[sku price])
p res.rows
[["KB-001", 0.11999e3], ["MN-003", 0.289e3]]
["MS-002"]
"KB-001"
["input", "wireless"]
{"dpi" => 4000, "color" => "black"}
26
{"gift" => false}
{"KB-001" => 2, "MS-002" => 3}
[["KB-001", 0.9999e2], ["HS-007", 0.59e2]]
upsert_all generates INSERT ... ON CONFLICT (sku) DO UPDATE, and on PostgreSQL it can return columns with returning:. jsonb stores keys in its own order (shorter keys first), which is why dpi comes before color. In migrations, declare these columns with t.string :tags, array: true, default: [] and t.jsonb :attrs, default: {}. In a Rails app the connection settings go in config/database.yml, or in DATABASE_URL.
Which one to use
| Library | Good for | Notes |
|---|---|---|
pg |
scripts, bulk loads, full control | COPY, streaming, LISTEN/NOTIFY; returns strings unless you set type maps |
| Sequel | apps without Rails, complex SQL | very good PostgreSQL support (arrays, JSONB, RETURNING, cursors), built-in pool |
| Active Record | Rails, or reusing Rails models | models, validations, associations, upsert_all |
Whichever you pick, you can still get to the raw PG::Connection for COPY or LISTEN: DB.synchronize { |c| ... } in Sequel and ActiveRecord::Base.connection.raw_connection in Active Record. To store user passwords in a users table, see Password hashing.