PostgreSQL Wire (pgwire)
Connect psql, psycopg, SQLAlchemy, node-postgres, pgx, COPY, cursors, and LISTEN/NOTIFY over port 5432.
3 min read Protocols & HTTP API
SpydDB exposes a PostgreSQL v3 wire listener (pgwire_bind) so existing SQL tools, BI suites, connection pools, and third-party PostgreSQL drivers connect out of the box with full RBAC, row policies, field masks, TLS/SCRAM authentication, and SSI snapshot isolation.
1. Enable the Listener#
Configure pgwire_bind (and copy_directory if using file-based COPY) in server.json:
json
{
"pgwire_bind": "0.0.0.0:5432",
"copy_directory": "/var/lib/spyd/copy",
"tls": {
"certificate": "/etc/spyd/tls/server.crt",
"private_key": "/etc/spyd/tls/server.key"
}
}- TLS:
SSLRequestupgrades transparently using your server certificate (sslmode=require,verify-ca, orverify-full). Non-loopback plaintext is refused. - Authentication: Supply your SpydDB Bearer token as the PostgreSQL password, or connect with SCRAM-SHA-256 credentials configured in
scram. - Database selection: Pass
databasein the PostgreSQL startup packet (or runCREATE DATABASE analytics/DROP DATABASE IF EXISTS analytics), querycurrent_database(), and verify virtual catalog introspection (pg_class,pg_namespace,pg_attribute,pg_constraint,pg_index,pg_type).
2. Complete PostgreSQL SQL Compatibility Matrix#
| Feature Area | Supported SQL Constructs |
|---|---|
| Queries (DQL) | SELECT with column/table aliases, WHERE, GROUP BY, HAVING, ORDER BY (NULLS FIRST/LAST), LIMIT, OFFSET, DISTINCT, INNER / LEFT / RIGHT / FULL / CROSS joins, subqueries (IN, EXISTS, scalar), CTEs (WITH, WITH RECURSIVE), window functions (OVER (...)) |
| Mutations (DML) | INSERT (VALUES, ON CONFLICT ... DO UPDATE/NOTHING), UPDATE ... SET, DELETE, RETURNING, CALL proc(...) |
| Schema DDL | CREATE / ALTER / DROP TABLE, CREATE / DROP SCHEMA, CREATE / DROP DATABASE, CREATE [UNIQUE] INDEX ... [USING btree | hash | fulltext | hnsw | rtree | graph], CREATE / DROP EXTENSION, DROP PROCEDURE |
| Procedures, Functions & PL/pgSQL | CREATE [OR REPLACE] PROCEDURE (IN/OUT/INOUT, SECURITY DEFINER/INVOKER), CREATE [OR REPLACE] FUNCTION (LANGUAGE sql, LANGUAGE plpgsql, LANGUAGE wasm, RETURNS TABLE(...)), CREATE AGGREGATE ... (SFUNC=..., STYPE=..., INITCOND=...) |
| Transactions & Locking | BEGIN, START TRANSACTION, SET TRANSACTION, COMMIT, ROLLBACK, SAVEPOINT / RELEASE / ROLLBACK TO, FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, OF table, NOWAIT, SKIP LOCKED |
| Extended Protocol & Cursors | Parameterized Parse / Bind / Describe / Execute / Sync / Close / Flush, portal suspension (PortalSuspended row batching), SQL cursors (DECLARE name CURSOR FOR SELECT ..., FETCH [count | NEXT | ALL] FROM name, CLOSE name | ALL), DEALLOCATE |
Bulk I/O (COPY) | COPY table [(cols)] TO STDOUT, COPY (query) TO STDOUT, COPY table [(cols)] FROM STDIN, confined relative-file COPY with FORMAT csv (HEADER) or FORMAT json |
| Session & Pub/Sub | LISTEN channel, UNLISTEN channel | *, transactional NOTIFY channel [, 'payload'], SET, SHOW, DISCARD, and virtual catalog introspection (pg_class, pg_namespace, pg_attribute, pg_constraint, pg_index, pg_type, current_database()) |
| Atomic Ledger Arithmetic | balance_delta(balance, min, max, delta1, ...) |
3. Connecting from CLI, Python, Node.js, and Go#
PostgreSQL CLI (psql)#
sh
PGPASSWORD="$SPYD_TOKEN" psql \
"host=127.0.0.1 port=5432 dbname=default user=admin sslmode=verify-ca sslrootcert=docker/tls/ca.crt"sql
CREATE TABLE invoices (
id BIGINT PRIMARY KEY,
customer TEXT NOT NULL,
amount NUMERIC(12, 2) NOT NULL,
status TEXT NOT NULL
);
INSERT INTO invoices (id, customer, amount, status)
VALUES (1, 'Acme Corp', 250.00, 'paid')
RETURNING id, status;
SELECT customer, SUM(amount) AS total
FROM invoices
WHERE status = 'paid'
GROUP BY customer
ORDER BY total DESC
LIMIT 10;Python (psycopg v3 & SQLAlchemy)#
python
import psycopg
from sqlalchemy import create_engine, text
dsn = (
"postgresql://admin:YOUR_TOKEN@127.0.0.1:5432/default"
"?sslmode=verify-ca&sslrootcert=docker/tls/ca.crt"
)
# Direct psycopg parameterized execution & transaction
with psycopg.connect(dsn) as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO invoices (id, customer, amount, status) VALUES (%s, %s, %s, %s)",
(2, "Globex", "199.95", "open"),
)
cur.execute("SELECT id, customer, amount FROM invoices WHERE status = %s", ("open",))
print(cur.fetchall())
conn.commit()
# SQLAlchemy Engine
engine = create_engine(dsn.replace("postgresql://", "postgresql+psycopg://"))
with engine.connect() as conn:
rows = conn.execute(text("SELECT id, customer FROM invoices ORDER BY id LIMIT 10")).all()
print(rows)Node.js / TypeScript (pg)#
ts
import fs from "node:fs";
import pg from "pg";
const pool = new pg.Pool({
host: "127.0.0.1",
port: 5432,
database: "default",
user: "admin",
password: process.env.SPYD_TOKEN,
ssl: {
ca: fs.readFileSync("docker/tls/ca.crt", "utf8"),
servername: "localhost",
},
});
const { rows } = await pool.query(
"SELECT id, customer, status FROM invoices WHERE status = $1 ORDER BY id LIMIT $2",
["paid", 20],
);
console.log(rows);
await pool.end();Go (pgx/v5)#
go
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"github.com/jackc/pgx/v5"
)
func main() {
caPEM, _ := os.ReadFile("docker/tls/ca.crt")
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caPEM)
cfg, _ := pgx.ParseConfig("postgres://admin:" + os.Getenv("SPYD_TOKEN") + "@127.0.0.1:5432/default")
cfg.TLSConfig = &tls.Config{RootCAs: pool, ServerName: "localhost"}
conn, err := pgx.ConnectConfig(context.Background(), cfg)
if err != nil { panic(err) }
defer conn.Close(context.Background())
var id int64
var customer string
err = conn.QueryRow(context.Background(), "SELECT id, customer FROM invoices WHERE id = $1", 1).Scan(&id, &customer)
if err != nil { panic(err) }
fmt.Println(id, customer)
}4. Real-Time LISTEN / NOTIFY, Cursors & COPY#
sql
-- Session A (Subscriber)
LISTEN order_events;
-- Session B (Publisher inside a transaction)
BEGIN;
INSERT INTO invoices (id, customer, amount, status) VALUES (3, 'Initech', 420.00, 'paid');
NOTIFY order_events, '{"invoice_id":3,"status":"paid"}';
COMMIT; -- Notification delivers only after commit succeedssql
-- Transaction-scoped SQL cursor
BEGIN;
DECLARE inv_cur CURSOR FOR SELECT id, customer FROM invoices ORDER BY id;
FETCH 10 FROM inv_cur;
CLOSE inv_cur;
COMMIT;
-- Server-confined CSV / JSON export (relative to server copy_directory)
COPY (SELECT id, customer, amount FROM invoices WHERE status = 'paid') TO 'paid_invoices.csv' FORMAT csv HEADER;
COPY invoices (id, customer, amount, status) FROM 'new_invoices.json' FORMAT json;