К основному содержанию
скилл CX Codex

postgres-query · civitai — скилл для Claude Code: что делает и как установить

Скилл postgres-query для Claude Code выполняет запросы к PostgreSQL при отладке и профилировании базы данных. Запускает команды через скрипт с обязательным указанием контура --prod или --dev.

Apache-2.0 105 установок ★ 7 327 обновлён 2026-10-25

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add civitai/civitai --skill postgres-query -a claude-code
Открыть на GitHub

Что делает postgres-query

Выполняет SQL-запросы через Node.js-скрипт query.mjs, подключаясь по умолчанию в режиме только для чтения к реплике. Поддерживает явный выбор базы флагами --prod, --dev, --data-packet и --notifications. Два флага окружения одновременно передавать нельзя, а неизвестные параметры отклоняются сразу.

Перед отправкой запроса скрипт выводит в stderr адрес и порт базы, полученные драйвером pg. База для --dev требует поднятого SSH-туннеля к внутренней сети. Конфигурация считывается из файла .claude/skills/postgres-query/.env, при этом все контуры кроме dev отклоняют адреса из корневого .env проекта.

Для анализа планов выполнения доступен флаг --explain с запуском EXPLAIN ANALYZE, поддерживается структурированный вывод через --json и передача SQL из файла с помощью -f. Запись в базу открывается флагом --writable, но на репликах --data-packet и --notifications он запрещён.

Какие задачи решает

  • выполнить EXPLAIN ANALYZE для поиска узких мест в SQL
  • проверить выборку данных на рабочей реплике без риска случайной записи
  • применить DDL или тестовую миграцию на dev-базе через --writable
  • запустить длинный запрос из файла .sql с увеличенным таймаутом

Примеры запросов агенту

  • Выполни профилирование запроса на проде: node .claude/skills/postgres-query/query.mjs --prod --explain "SELECT * FROM \"User\" LIMIT 5"
  • Запусти запрос из файла на dev-базе: node .claude/skills/postgres-query/query.mjs --dev -f my-query.sql
  • Выгрузи список записей в JSON с таймаутом 60 секунд: node .claude/skills/postgres-query/query.mjs --prod --json -t 60 "SELECT id FROM \"Model\" LIMIT 10"

Как установить postgres-query

1Через Skills CLI (Vercel)

npx skills add civitai/civitai --skill postgres-query -a claude-code

2Вручную: положить файлы

~/.claude/skills/postgres-query/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/postgres-query/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о postgres-query

Как установить postgres-query в Claude Code?

Выполните команду npx skills add civitai/civitai --skill postgres-query -a claude-code.

Что делает postgres-query?

Скрипт подключается к нужной базе PostgreSQL, валидирует окружение, выводит параметры соединения в stderr и исполняет переданный SQL-запрос.

Что нужно для работы postgres-query?

Нужны Node.js, локальный файл .claude/skills/postgres-query/.env с переменными строк подключения, а для работы с --dev требуется запущенный SSH-туннель.

Исходный текст

SKILL.md · Apache-2.0
---
name: postgres-query
description: Run PostgreSQL queries for testing, debugging, and performance analysis. Use when you need to query the database directly, run EXPLAIN ANALYZE, compare query results, or test SQL optimizations. Always pass a target — `--prod` or `--dev` — because prod and dev are different databases and the default is prod. Always uses read-only connections unless explicitly directed otherwise.
---

# PostgreSQL Query Testing

Use this skill to run ad-hoc PostgreSQL queries for testing, debugging, and performance analysis.

## Running Queries

Use the included query script, and **name the target**:

```bash
node .claude/skills/postgres-query/query.mjs --prod "SELECT * FROM \"User\" LIMIT 5"
node .claude/skills/postgres-query/query.mjs --dev  "SELECT * FROM \"User\" LIMIT 5"
```

### Targets

Pick exactly one. Two target flags in one call is an error, not a silent precedence rule, and an
unrecognised option (`--devv`, `--data_packet`) is rejected rather than ignored — a swallowed typo
would fall through to the default target, which is production.

| Flag | Connection string | Use when |
|------|-------------------|----------|
| `--prod` (default) | `DATABASE_REPLICA_URL`, or `DATABASE_URL` with `--writable` | The production main database |
| `--dev` | `DEV_DATABASE_URL` | The dev cnpg database; requires SSH tunnel |
| `--data-packet` | `DATABASE_DATA_PACKET_URL` | The DataPacket replica (read-only) |
| `--notifications` | `NOTIFICATION_DB_REPLICA_URL` | notifications-db (read-only); requires SSH tunnel |

Omitting the target still runs against prod, so old commands keep working — but the run prints
`No target flag given, defaulted to --prod`. Pass the flag.

### Every run prints which database answered

Before connecting, the script writes a line to **stderr** naming the target, the access mode, the
`user@host:port/database` **pg itself resolved**, and the env var it came from:

```
Target: PROD (read-only) -> <user>@<host>:25061/civitai [DATABASE_REPLICA_URL, timeout 30s]
```

It prints under `--quiet` and `--json` too, and before every exit path that reaches a database —
including a blocked write, so you can always see which database you just aimed a `DELETE` at. It is
on stderr, so `--json` piped to a file is still clean JSON.

The host and port come from the client's own resolved connection parameters rather than a re-parse
of the string, so the line cannot disagree with where the query actually went.

🔴 **Read that line before you trust a result.** This skill's `.env` and the app's root `.env` both
define `DATABASE_URL`, and **they name different databases** — the skill's is production, the root
one is the dev snapshot the dev server uses. The skill's `.env` wins: it is loaded first, and
`loadEnv` only fills in keys that are not already **present** (an empty value counts as present, so
a bare `DATABASE_REPLICA_URL=` left in this file does not hand that key to the root `.env` — the
target falls back to this file's `DATABASE_URL` instead, and the banner says
`read-only, but pointed at the primary`). So a bare `query.mjs` answers from production while your
dev server answers from dev. Comparing a value
read here against one read by the running app is comparing two different databases unless both lines
say the same host and port. That cost an hour and produced a confidently wrong root cause on
2026-08-16: `limit: 8` from the app's DB and `limit: 40` from this skill's, reported as a config bug
that did not exist.

Two checks make the wrong database fail loudly instead of answering:

- **Every target except `--dev` refuses a URL that came from the root `.env`.** A checkout with no
  skill `.env` exits 1 and names the file it would have read. A URL set in the process environment
  is still accepted: that is a deliberate choice.
- **`--prod` (read-only) checks that it reached a hot standby.** After connecting it prints
  `Server: <addr>, in recovery: <bool>` and exits 1 if the server is not in recovery, since a primary
  or a local copy is not the replica.

### Options

| Flag | Description |
|------|-------------|
| `--explain` | Run EXPLAIN ANALYZE on the query |
| `--writable` | Use the primary connection instead of the read replica (requires user permission) |
| `--timeout <s>`, `-t` | Query timeout in seconds (default: 30) |
| `--file`, `-f` | Read query from a file |
| `--json` | Output results as JSON |
| `--quiet`, `-q` | Minimal output, only results |

`--writable` combined with `--data-packet` or `--notifications` is an error — both are read-only
replicas, so the combination can only mean a mistake.

### Examples

```bash
# Simple query
node .claude/skills/postgres-query/query.mjs --prod "SELECT id, username FROM \"User\" LIMIT 5"

# Same query against the dev database
node .claude/skills/postgres-query/query.mjs --dev "SELECT id, username FROM \"User\" LIMIT 5"

# Check query performance
node .claude/skills/postgres-query/query.mjs --prod --explain "SELECT * FROM \"Model\" WHERE id = 1"

# Override default 30s timeout for longer queries
node .claude/skills/postgres-query/query.mjs --prod --timeout 60 "SELECT ... (complex query)"

# Query the notifications-db
node .claude/skills/postgres-query/query.mjs --notifications "SELECT count(*) FROM \"Notification\""

# Query from file
node .claude/skills/postgres-query/query.mjs --dev -f my-query.sql

# JSON output for processing (banner goes to stderr, stdout stays valid JSON)
node .claude/skills/postgres-query/query.mjs --prod --json "SELECT id, username FROM \"User\" LIMIT 3"
```

## Querying the dev database (cnpg)

The dev database is not reachable directly — it needs an SSH tunnel to an internal
host. **Ask an infra owner for the connection recipe**; the specifics are not
documented here because this repository is public (see the Security section of
`CLAUDE.md`).

Once the tunnel is up, set `DEV_DATABASE_URL` in
`.claude/skills/postgres-query/.env` to point at your local forwarded port.

### Running dev queries

```bash
# Read-only (default — writes are blocked client-side)
node .claude/skills/postgres-query/query.mjs --dev "SELECT count(*) FROM \"User\""

# Writable DML (needs user permission)
node .claude/skills/postgres-query/query.mjs --dev --writable "UPDATE ..."
```

`--dev` uses `DEV_DATABASE_URL` either way — unlike `--prod`, there is no separate replica
credential, so `--writable` only lifts the client-side guard. Whether a write lands is decided by
the role in that URL.

**DDL does work through this credential** — verified 2026-08-17 on both dev and the prod primary as
role `civitai`: `ALTER TABLE ... ADD COLUMN`, `ADD CONSTRAINT`, `CREATE INDEX` and a
`CREATE TABLE`/`DROP TABLE` round trip all succeeded. Migrations can be applied with `--writable`.

This section previously said the opposite — that a `ddl_command_end` event trigger reassigning object
ownership made any `CREATE TABLE` roll back with `must be able to SET ROLE "<schema owner>"`. Nobody
has observed that, and it is contradicted by the run above. It cost an escalation to an infra owner
that was not needed. If you do hit an ownership error, record what you ran and correct this section
again rather than restoring the blanket claim.

⚠️ **A multi-statement script needs `--writable` even when its first statement is harmless.** The
client-side write guard checks every statement's leading keyword, so a migration opening with
`SET lock_timeout` / `BEGIN` is still refused on account of the `ALTER`s underneath. That is
deliberate.

## Querying the notifications-db

The notifications database is not reachable directly — it needs an SSH tunnel to an
internal host, and access has to be granted first.

**Ask an infra owner for access and the connection recipe.** The bastion host, the
forward target, and where the credentials live are deliberately not documented here,
because this repository is public — see the Security section of `CLAUDE.md`.

Once you have the tunnel open, set `NOTIFICATION_DB_REPLICA_URL` in
`.claude/skills/postgres-query/.env` to point at your local forwarded port.

### Running queries

```bash
# With the tunnel open in another terminal:
node .claude/skills/postgres-query/query.mjs --notifications \
  "SELECT count(*) FROM \"Notification\""

node .claude/skills/postgres-query/query.mjs --notifications --explain \
  "SELECT * FROM \"UserNotification\" WHERE \"userId\" = 12345 ORDER BY \"createdAt\" DESC LIMIT 50"
```

### Available tables (read-only)

- `Notification` — canonical notifications
- `UserNotification` — per-user fanout (largest table)
- `PendingNotification` — processing queue (often empty)

The role `notifications_readonly` only has `SELECT`. Writes are also rejected at the pooler level (replica routing).

## Safety Features

1. **Read-only by default**: `--prod` uses `DATABASE_REPLICA_URL` to prevent accidental writes
2. **Write protection**: Blocks INSERT/UPDATE/DELETE/DROP unless `--writable` flag is used
3. **Replica targets refuse `--writable`**: `--notifications` and `--data-packet` error on the flag, and their roles/poolers reject writes anyway
4. **Explicit permission required**: Before using `--writable`, you MUST ask the user for permission
5. **The target is printed on every run**: no result can be attributed to the wrong database by accident

⚠️ **The write guard is a typo-catcher, not a sandbox.** It matches the query's leading keyword
(after stripping leading comments) and the `(INSERT|UPDATE|DELETE|…` inside a leading `WITH`. A write
buried deeper than that gets through the client. What actually stops writes is the **role** you
connect as — which is why `--prod` defaults to the read-only replica credential. Do not treat a
missing `--writable` as proof a query cannot write.

## When to Use --writable

Only use the `--writable` flag when:
- The user explicitly requests write access
- You need to test write operations
- You're verifying transaction behavior

**IMPORTANT**: Always ask the user for permission before running with `--writable`.

## Comparing Query Performance

To compare two query approaches — same target on both runs, or the comparison is meaningless:

```bash
# Run first approach
node .claude/skills/postgres-query/query.mjs --prod --explain "SELECT ... (approach 1)"

# Run second approach
node .claude/skills/postgres-query/query.mjs --prod --explain "SELECT ... (approach 2)"

# Compare actual results
node .claude/skills/postgres-query/query.mjs --prod --json "SELECT ... (approach 1)" > /tmp/q1.json
node .claude/skills/postgres-query/query.mjs --prod --json "SELECT ... (approach 2)" > /tmp/q2.json
```

## Verifying Index Usage

Run with `--explain` and look for:
- **Good**: "Index Scan", "Bitmap Index Scan", "Index Only Scan"
- **Bad**: "Seq Scan" on large tables (indicates missing or unused index)

```bash
node .claude/skills/postgres-query/query.mjs --prod --explain "SELECT * FROM \"Account\" WHERE provider = 'discord'"
```

© civitai · Apache-2.0 · civitai/civitai

Похожие скиллы

Все скиллы по теме «Данные и базы» →

Сначала — postgres-query от других авторов.

postgres-query civitai Скилл postgres-query выполняет SQL-запросы к PostgreSQL, запускает EXPLAIN ANALYZE и проверяет индексы через агент в безопасном режиме чтения. CX Codex +1 ★ 7 327звёзд репо neon-postgres neondatabase Скилл neon-postgres для Claude Code помогает работать с базой Neon: подключениями, схемой и ветками. Агент подключает его при запросах к существующей базе, SQL или поиску. CX Codex +1 315 000установок postgres-patterns affaan-m Скилл postgres-patterns для Claude Code собирает практики PostgreSQL для проектирования схем и настройки запросов: индексы, типы данных, RLS и диагностика медленных запросов. CX Codex +1 7 200установок design-postgres-tables tigerdata Скилл design-postgres-tables для Claude Code проектирует таблицы PostgreSQL: типы данных, индексы, ограничения, JSONB и партиционирование. Включается при создании или изменении схемы. CX Codex +1 680установок supabase-postgres-best-practices supabase Скилл supabase-postgres-best-practices помогает агенту проектировать схемы и писать SQL с учётом правил Supabase для Postgres. Подключайте его до изменений базы и при разборе проблем с запросами, подключениями или RLS. CX Codex +1 146установок postgres-tuning oakoss Скилл postgres-tuning для Claude Code, Codex, Cursor и других агентов, который даёт инструкции по настройке производительности PostgreSQL 17/18+. Охватывает async I/O, анализ планов запросов, индексы, autovacuum, pgvector и PgBouncer. CX Codex +1 136установок

Из того же набора11

Весь набор →
clickup Скилл clickup для Claude Code работает с задачами и документами ClickUp: показывает детали и комментарии, создаёт и меняет записи по URL или ID. CX Codex +1 1 800установок clickup Подключает ClickUp API прямо в агент. Читает задачи по URL или ID, создаёт, переназначает, обновляет статус и добавляет комментарии. CX Codex +1 1 800установок quick-mockups Скилл quick-mockups для Claude Code: генерирует от 3 до 5 параллельных вариантов интерфейса в HTML для сравнения разных сеток и подачи новой фичи. CX Codex +1 1 700установок meilisearch-admin Скилл meilisearch-admin для мониторинга Meilisearch: проверяет индексы, задачи, здоровье сервера и настройки поиска. Помогает отловить ошибки в индексировании и понять, что происходит с поиском. CX Codex +1 132установок agent-review Скилл agent-review для Claude Code отправляет код на проверку внешнему AI-агенту. Выполняет ревью, помогает оценить архитектурные решения и получить второе мнение. CX Codex +1 3установок discord Отправляет сообщения, анонсы и эмбеды в каналы Discord через REST API. Передаёт уведомления о релизах и командную переписку из консоли. CX Codex +1 ★ 7 327звёзд репо clickhouse-query Скилл clickhouse-query гоняет ad-hoc запросы к ClickHouse прямо из чата с агентом: метрики, события, план выполнения. По умолчанию только чтение. CX Codex +1 ★ 7 327звёзд репо redis-inspect Скилл redis-inspect для Claude Code проверяет ключи, значения и TTL в основном и системном инстансах Redis. Показывает, что сейчас хранится в кэше. CX Codex +1 ★ 7 327звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой