Using PostgreMQ through SQL
PostgreMQ's public SQL functions implement the same publication, claim, and settlement contract used by its SDKs. This gives SQL applications and other languages direct access without another network protocol.
The SDKs also manage polling, notifications, automatic extension, subscription lifetime, cancellation, and shutdown. A custom SQL client must supply those lifecycle responsibilities itself.
Publish, claim, and acknowledge
Connect psql to an installed database with runtime permissions. The walkthrough uses a distinct topic and queue and assumes no earlier pending work in that queue. psql autocommit is enabled, so each function call below commits before the next begins.
SQL
\set ON_ERROR_STOP on
SELECT postgremq.create_topic('sql-events');
SELECT postgremq.create_queue('sql-jobs', 'sql-events', 5, false);
SELECT postgremq.publish_message('sql-events', '{"number":1}'::jsonb);
SELECT * FROM postgremq.consume_message('sql-jobs', 30, 1) \gset claim_
\echo Received message :claim_message_id
SELECT postgremq.ack_message(
'sql-jobs', :claim_message_id, :'claim_consumer_token');
The claim returns a message ID, JSON payload, ownership token, attempt count, deadline, and optional group information. Keep the token with that attempt. A new claim uses a different token; the message ID alone does not grant settlement rights.
In this small example, printing receipt stands in for processing. Acknowledge only after the actual work succeeds. If another consumer wins the claim, the receive call can return no rows; a real worker must handle an empty result rather than assuming the psql variable assignment always succeeds.
The equivalent SDK flow keeps those lifecycle services available. These excerpts use the existing connections from Connecting and import the standard packages used by the Quick start.
- Go
- Rust
- TypeScript
if err := conn.CreateTopic(ctx, "sql-events"); err != nil { return err }
if err := conn.CreateQueue(ctx, "sql-jobs", "sql-events", false,
postgremq.WithMaxDeliveryAttempts(5)); err != nil { return err }
if _, err := conn.Publish(ctx, "sql-events", json.RawMessage(`{"number":1}`)); err != nil {
return err
}
consumer, err := conn.Consume("sql-jobs", postgremq.WithBatchSize(1), postgremq.WithVT(30))
if err != nil { return err }
select {
case message, ok := <-consumer.Messages():
if !ok { return fmt.Errorf("consumer ended before receiving") }
fmt.Println("Received", message.ID)
if err := message.Ack(ctx); err != nil { return err }
case <-ctx.Done():
return ctx.Err()
}
conn.create_topic("sql-events").await?;
conn.create_queue("sql-jobs", "sql-events",
postgremq::QueueOptions::default().max_delivery_attempts(5)).await?;
conn.publish("sql-events", &postgremq::serde_json::json!({"number": 1}),
postgremq::PublishOptions::default()).await?;
let mut consumer = conn.consume("sql-jobs",
postgremq::ConsumeOptions::default().batch_size(std::num::NonZeroU32::MIN)).await?;
let message = tokio::time::timeout(std::time::Duration::from_secs(10), consumer.next())
.await?.ok_or("consumer ended before receiving")??;
println!("Received {}", message.message_id());
message.ack().await?;
await client.createTopic('sql-events');
await client.createQueue('sql-jobs', 'sql-events', false, { maxDeliveryAttempts: 5 });
await client.publish('sql-events', { number: 1 });
const consumer = client.consume('sql-jobs', { batchSize: 1, visibilityTimeoutSec: 30 });
let received = false;
for await (const message of consumer.messages()) {
console.log('Received', message.id);
await message.ack();
received = true;
break;
}
if (!received) throw new Error('Consumer ended before receiving');
Finish through the surrounding program's bounded connection-close path. In a service, observe consumer termination and use an application lifetime rather than waiting indefinitely for an assumed message.
Commit claims before external work
If you use an explicit transaction to claim messages, commit the claim promptly before performing arbitrary external work. An open claim transaction holds locks; its uncommitted lease is not a substitute for the normal visibility contract. Keeping a transaction open throughout an HTTP request can block recovery and consume a connection for the whole request.
For database-only processing, a later transaction can commit application changes and acknowledgement together. Idempotent consumers demonstrates that boundary and rollback behavior in all supported languages.
Build the missing lifecycle deliberately
A custom worker must poll when claims return no rows and after missed notifications. LISTEN is a wake-up optimization, not durable delivery state. A correct listener subscribes, then queries database state, and keeps periodic polling. See Notifications and polling.
Renew long-running claims before their confirmed deadline and stop unsafe work if ownership cannot be maintained. Negative-acknowledge attempted failures; release only work never attempted. Choose finite attempt limits and arrange maintenance for abandoned final attempts.
For Exclusive queues, the client must extend subscription lifetime separately from message leases. Consumption alone does not maintain that lifetime. Track queue generations so a deleted and recreated name does not silently become a different subscription underneath a running worker.
Use SQL conventions for argument units, transaction rules, and the complete function reference. Unsupported languages can implement this contract directly, but a single consume_message loop is only the beginning of a complete client.