postgres-js
БесплатноБез исполняемых скриптовНе проверенPostgres.js is a PostgreSQL client for Node.js, Bun and Deno that builds safe parameterized queries from tagged template literals. Use it when asked to…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Postgres.js — PostgreSQL client with tagged template queries
Overview
Postgres.js (npm package postgres, current major 4) is a dependency-free, ES-module PostgreSQL client. Every value written as ${value} inside a template literal is sent as a bound parameter, so queries are not built by string concatenation and cannot be injected through values. It pools connections, pipelines queries, prepares statements automatically, and supports transactions, cursors, COPY streams, LISTEN/NOTIFY and logical-replication subscriptions.
This skill is the Node client. For the database itself (schemas, indexes, tuning) use the postgresql skill.
Instructions
Installation
npm install postgres
It is ESM. In an ES module use import postgres from 'postgres'. From CommonJS use const postgres = require('postgres').default, which works on Node.js 20.19, 22.12 and later. Types ship with the package.
Connect
Create one sql instance per process and share it. Pass a URL, options, or both (options win over the URL). With no arguments it reads the same environment variables as psql (PGHOST, PGPORT, PGDATABASE, PGUSER, PGPASSWORD).
// db.ts
import postgres from 'postgres'
export const sql = postgres(process.env.DATABASE_URL!, {
max: 10, // pool size (default 10)
idle_timeout: 30, // close idle connections after 30 s (default 0 = never)
connect_timeout: 10, // seconds (default 30)
queue_timeout: 5, // fail a query that waits more than 5 s for a free connection
})
Connections open lazily on the first query. Call await sql.end({ timeout: 5 }) before the process exits so it does not hang.
Queries
A query returns an array of row objects, and the array also carries count (rows affected) and command (SELECT, INSERT...).
const minTotal = 2000
const orders = await sql`
select id, customer, total_cents
from orders
where total_cents > ${minTotal}
order by id
`
const result = await sql`select count(*)::int as n from orders`
console.log(result[0].n, result.count, result.command) // 2 1 SELECT
Never put quotes around ${...}. Postgres returns bigint and numeric columns as strings; cast in SQL (::int) or convert in code when the value is small enough.
Typed rows with TypeScript: await sql<{ id: number; customer: string }[]>\select id, customer from orders``.
Dynamic inserts, updates, lists and identifiers
const rows = [
{ customer: 'Marta Ilves', total_cents: 4200 },
{ customer: 'Joel Brandt', total_cents: 1999 },
]
// one multi-row insert; the listed keys pick the columns
const inserted = await sql`insert into orders ${sql(rows, 'customer', 'total_cents')} returning id, customer`
// update from an object
await sql`update orders set ${sql({ status: 'paid' }, 'status')} where id = ${inserted[0].id}`
// IN lists: either form works
const ids = inserted.map(r => r.id)
await sql`select * from orders where id in ${sql(ids)}`
await sql`select * from orders where id = any(${ids})`
// identifiers (column or table names) are quoted by sql(name)
const sortColumn = 'total_cents' // validate against an allow-list first
await sql`select * from orders order by ${sql(sortColumn)} desc`
JSON values: ${sql.json({ source: 'web' })} writes a json/jsonb parameter.
Conditional filters
Nest sql\`` fragments; an empty fragment adds nothing.
async function findOrders(filter: { minTotal?: number; customer?: string }) {
const conditions = sql`and`.join([
filter.minTotal !== undefined && sql`total_cents > ${filter.minTotal}`,
filter.customer && sql`customer = ${filter.customer}`,
])
return sql`select * from orders ${conditions.length ? sql`where ${conditions}` : sql``}`
}
join drops false, null and undefined entries.
Transactions
sql.begin runs the callback on one connection, commits when it resolves and rolls back when it throws. Use the callback's own tx, never the outer sql, inside it.
const [order] = await sql.begin(async tx => {
const [order] = await tx`insert into orders (customer, total_cents) values (${'Marta Ilves'}, ${4200}) returning *`
await tx`update stock set qty = qty - 1 where sku = ${'KB-104'}`
return [order]
})
A savepoint inside a transaction: await tx.savepoint(async sp => { ... }). Throwing inside it rolls back only the savepoint.
Cursors and large result sets
// batches of 500 rows
await sql`select * from events order by id`.cursor(500, async rows => {
await processBatch(rows)
})
// one row at a time
for await (const [row] of sql`select * from events`.cursor()) {
console.log(row.id)
}
LISTEN / NOTIFY
await sql.listen('orders_changed', payload => console.log('changed:', payload))
await sql.notify('orders_changed', JSON.stringify({ id: 42 }))
Use a direct connection or a session-mode pooler for listen. sql.listen reconnects and re-subscribes after a dropped connection.
Установить postgres-js в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл postgres-js?
Postgres.js is a PostgreSQL client for Node.js, Bun and Deno that builds safe parameterized queries from tagged template literals. Use it when asked to "connect Node to Postgres", "run a SQL query from TypeScript", "insert rows with postgres.js", "use a transaction", "listen for Postgres notifications", "stream a big result set with a cursor", or "cancel a slow query". Covers v4 connection options, dynamic inserts and filters, transactions, cursors, LISTEN/NOTIFY, timeouts, TLS and PgBouncer settings.
Как установить скилл postgres-js?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл postgres-js запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic