Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
JavaScript PostgreSQL libraries connect Node.js and serverless code to a PostgreSQL database and run SQL queries. A client keeps a pool of open connections and sends each query's values as parameters separate from the SQL text. These libraries let apps and backend services read and write relational data without opening a new database connection for every request.
Popularity
node-postgres has the most monthly downloads in this comparison, at 372.0M.
export const migrateStaleBlockers = async () => {
const body = (event.body as any) || {};
const phase: string = body.phase;
const auditId: string | undefined = body.auditId;
const dryRun: boolean = !!body.dryRun;
if (!phase) {
return {
statusCode: 400,
body: JSON.stringify({ error: "phase is required: 'ignored_hashes' | 'scan_counts' | 'move_stale'" }),
};
}
await db.connect();
const t0 = Date.now();
try {
if (phase === "ignored_hashes") {
// Backfill content_hash_id on existing ignored_blockers rows by joining // back to blockers. Safe to re-run (NULL-only update). const auditFilter = auditId ? `AND ib.audit_id = $1` : "";
const values = auditId ? [auditId] : [];
const result = await db.query({
text: `
${dryRun ? "SELECT COUNT(*) AS updated FROM" : "UPDATE"} ignored_blockers ib
${dryRun ? "JOIN" : "SET content_hash_id = b.content_hash_id FROM"} blockers b
${dryRun ? "ON" : "WHERE"} ib.blocker_id = b.id
AND ib.content_hash_id IS NULL
${auditFilter}
`,
values,
});
const updated = dryRun ? result.rows[0]?.updated : result.rowCount;
await db.clean();
return {
statusCode: 200,
body: JSON.stringify({ phase, dryRun, updated, ms: Date.now() - t0 }),
};
}
if (phase === "scan_counts") {
// Backfill blocker_count + equalified_count on every scan row from the // active blockers table. MUST run BEFORE any blockers are moved to stale. const auditFilter = auditId ? `WHERE s.audit_id = $1` : "";
const values = auditId ? [auditId] : [];
if (dryRun) {
const result = await db.query({
text: `SELECT COUNT(*) AS scan_count FROM scans s ${auditFilter}`,
values,
});
await db.clean();
return {
statusCode: 200,
body: JSON.stringify({ phase, dryRun, scansToUpdate: result.rows[0]?.scan_count, ms: Date.now() - t0 }),
};
}
const result = await db.query({
text: `
UPDATE scans s SET
blocker_count = COALESCE((SELECT COUNT(*) FROM blockers WHERE scan_id = s.id), 0),
equalified_count = COALESCE((SELECT COUNT(*) FROM blockers WHERE scan_id = s.id AND equalified = true), 0)
${auditFilter}
`,
values,
});
await db.clean();
return {
statusCode: 200,
body: JSON.stringify({ phase, scansUpdated: result.rowCount, ms: Date.now() - t0 }),
};
}
if (phase === "move_stale") {
// Move blockers for non-latest scans (per audit) from blockers → stale_blockers. // Batched: process N stale scans per Lambda invocation. Caller re-invokes until done. const scansPerBatch: number = body.scansPerBatch ?? 5;
const maxBatches: number = body.maxBatches ?? 20;
// Stop starting new batches with this much headroom left in the Lambda budget. // Default 100s (fits 2-min Lambda). Bump for longer Lambdas via body.softDeadlineMs. const softDeadlineMs: number = body.softDeadlineMs ?? 100000;
// Pre-check: how many stale scans remain to migrate (have blockers still in active table) const remainingResult = await db.query({
text: `
WITH latest AS (
SELECT DISTINCT ON (audit_id) id
FROM scans
${auditId ? "WHERE audit_id = $1" : ""}
ORDER BY audit_id, created_at DESC
)
SELECT COUNT(DISTINCT b.scan_id) AS remaining
FROM blockers b
WHERE b.scan_id IS NOT NULL
AND b.scan_id NOT IN (SELECT id FROM latest)
${auditId ? "AND b.audit_id = $1" : ""}
`,
values: auditId ? [auditId] : [],
});
const remainingStaleScans = parseInt(remainingResult.rows[0]?.remaining ?? "0", 10);
if (dryRun) {
await db.clean();
return {
statusCode: 200,
body: JSON.stringify({ phase, dryRun, remainingStaleScans, ms: Date.now() - t0 }),
};
}
let batchesRun = 0;
let totalRowsMoved = 0;
const batchResults: any[] = [];
while (batchesRun < maxBatches && Date.now() - t0 < softDeadlineMs) {
const moveResult = await db.query({
text: `
WITH latest AS (
SELECT DISTINCT ON (audit_id) id
FROM scans
${auditId ? "WHERE audit_id = $1" : ""}
ORDER BY audit_id, created_at DESC
),
target_scans AS (
SELECT DISTINCT b.scan_id
FROM blockers b
WHERE b.scan_id IS NOT NULL
AND b.scan_id NOT IN (SELECT id FROM latest)
${auditId ? "AND b.audit_id = $1" : ""}
LIMIT ${scansPerBatch}
),
moved AS (
DELETE FROM blockers
WHERE scan_id IN (SELECT scan_id FROM target_scans)
RETURNING id, created_at, updated_at, audit_id, content, content_normalized,
content_hash_id, targets, equalified, url_id, scan_id, short_id
)
INSERT INTO stale_blockers
(id, created_at, updated_at, audit_id, content, content_normalized,
content_hash_id, targets, equalified, url_id, scan_id, short_id)
SELECT id, created_at, updated_at, audit_id, content, content_normalized,
content_hash_id, targets, equalified, url_id, scan_id, short_id
FROM moved
`,
values: auditId ? [auditId] : [],
});
const rowsMoved = moveResult.rowCount ?? 0;
batchesRun++;
totalRowsMoved += rowsMoved;
batchResults.push({ batch: batchesRun, rowsMoved });
if (rowsMoved === 0) break; // nothing left
}
await db.clean();
return {
statusCode: 200,
body: JSON.stringify({
phase,
batchesRun,
totalRowsMoved,
remainingStaleScansBefore: remainingStaleScans,
ms: Date.now() - t0,
stoppedReason: batchesRun >= maxBatches
? "max_batches_reached"
: Date.now() - t0 >= softDeadlineMs
? "soft_deadline"
: "no_more_work",
batches: batchResults,
}),
};
}
if (phase === "move_orphan_blocker_messages") {
// After move_stale, blocker_messages rows still reference the moved blockers. // Move those orphans to stale_blocker_messages so the link table shrinks too. // Batched: process rowsPerBatch rows per round. const rowsPerBatch: number = body.rowsPerBatch ?? 200000;
const maxBatches: number = body.maxBatches ?? 50;
const softDeadlineMs: number = body.softDeadlineMs ?? 100000;
let totalRowsMoved = 0;
let batchesRun = 0;
const batchResults: any[] = [];
while (batchesRun < maxBatches && Date.now() - t0 < softDeadlineMs) {
const moveResult = await db.query({
text: `
WITH targets AS (
SELECT bm.id
FROM blocker_messages bm
WHERE NOT EXISTS (
SELECT 1 FROM blockers b WHERE b.id = bm.blocker_id
)
LIMIT ${rowsPerBatch}
),
moved AS (
DELETE FROM blocker_messages
WHERE id IN (SELECT id FROM targets)
RETURNING id, created_at, updated_at, message_id, blocker_id
)
INSERT INTO stale_blocker_messages
(id, created_at, updated_at, message_id, blocker_id)
SELECT id, created_at, updated_at, message_id, blocker_id FROM moved
`,
});
const rowsMoved = moveResult.rowCount ?? 0;
batchesRun++;
totalRowsMoved += rowsMoved;
batchResults.push({ batch: batchesRun, rowsMoved });
if (rowsMoved === 0) break;
}
await db.clean();
return {
statusCode: 200,
body: JSON.stringify({
phase,
batchesRun,
totalRowsMoved,
ms: Date.now() - t0,
stoppedReason: batchesRun >= maxBatches
? "max_batches_reached"
: Date.now() - t0 >= softDeadlineMs
? "soft_deadline"
: "no_more_work",
batches: batchResults,
}),
};
}
if (phase === "vacuum_full") {
// VACUUM FULL rewrites the heap to reclaim space from dead tuples. // Takes an ACCESS EXCLUSIVE lock for the duration — table is unavailable. // Hasura SQL console won't let you run this (TX wrapper); this route works // because serverless-postgres runs each query non-transactionally. const tableName: string = body.tableName;
if (!tableName || !/^[a-z_]+$/.test(tableName)) {
await db.clean();
return { statusCode: 400, body: JSON.stringify({ error: "tableName required, lowercase letters/underscores only" }) };
}
await db.query({ text: `VACUUM FULL public.${tableName}` });
await db.clean();
return {
statusCode: 200,
body: JSON.stringify({ phase, tableName, ms: Date.now() - t0 }),
};
}
await db.clean();
return {
statusCode: 400,
body: JSON.stringify({ error: `unknown phase '${phase}'` }),
};
} catch (err: any) {
try { await db.clean(); } catch {}
console.error("migrateStaleBlockers error:", err);
return {
statusCode: 500,
body: JSON.stringify({ error: err?.message || String(err), phase, ms: Date.now() - t0 }),
};
}
};
FAQ
node-postgres suits general Node.js apps that want explicit pool and client control. Postgres.js suits code that writes queries as tagged template literals. Neon serverless driver suits serverless and edge functions that query over HTTP or WebSockets.
The Neon serverless driver runs PostgreSQL queries over HTTPS or WebSockets from JavaScript runtimes. Its WebSocket mode offers a Pool and Client compatible with node-postgres.
Pool is the connection pool class in node-postgres. It keeps connections open and hands one to each query instead of connecting per request.
Slonik is a PostgreSQL client that builds queries from SQL tokens. It adds result assertions, transaction scoping, and schema validation of rows.
node-postgres uses parameterized query configs with an explicit pool and client lifecycle. Postgres.js writes queries as tagged templates with an automatically managed pool.
For coding agents
Found your PostgreSQL library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.