postgres-query

civitai/civitai

Выполнение запросов PostgreSQL для тестирования, отладки и анализа производительности. По умолчанию только чтение.

Звёзды7 324
Авторcivitai
Установок105

Установка

SKILL.md

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:

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

Options

FlagDescription
--explainRun EXPLAIN ANALYZE on the query
--writableUse primary database instead of read replica (requires user permission)
--data-packetUse the DataPacket replica (DATABASE_DATA_PACKET_URL) — read-only
--notificationsQuery the notifications-db (DataPacket) — read-only via SSH bastion (see setup below)
--devQuery the dev cnpg database (DEV_DATABASE_URL) via SSH bastion (see setup below)
--timeout <s>, -tQuery timeout in seconds (default: 30)
--file, -fRead query from a file
--jsonOutput results as JSON
--quiet, -qMinimal output, only results

Examples

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

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

# Override default 30s timeout for longer queries
node .claude/skills/postgres-query/query.mjs --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 -f my-query.sql

# JSON output for processing
node .claude/skills/postgres-query/query.mjs --json "SELECT id, username FROM \"User\" LIMIT 3"

Connection Targets

FlagConnection stringUse when
(default)DATABASE_REPLICA_URL (falls back to DATABASE_URL)Most queries — read-only main replica
--writableDATABASE_URLWrites against primary; needs user permission
--data-packetDATABASE_DATA_PACKET_URLQuerying the DataPacket replica (read-only)
--notificationsNOTIFICATION_DB_REPLICA_URLQuerying notifications-db (read-only); requires SSH tunnel
--devDEV_DATABASE_URLQuerying the dev cnpg database; requires SSH tunnel

Querying the dev database (cnpg)

The dev database lives in the cnpg-database-dev namespace and is reached through the civitai SSH bastion, which forwards local port 15432 to the in-cluster pgbouncer pooler.

Setup

  1. Make sure your ~/.ssh/config has the civitai host with this forward (already configured):

    # dev db (cnpg pgbouncer pooler)
    LocalForward 15432 pgbouncer-pooler-dev.cnpg-database-dev.svc.cluster.local:5432
    
  2. Open the tunnel in a terminal (stays open):

    ssh civitai -N
    
  3. Make sure DEV_DATABASE_URL is set in .claude/skills/postgres-query/.env:

    DEV_DATABASE_URL=postgresql://postgres:<password>@localhost:15432/civitai?sslmode=no-verify&schema=public
    

    Use sslmode=no-verify (not require) — the cnpg pooler presents a self-signed cert, and the connection is already encrypted inside the SSH tunnel.

Running dev queries

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

# Writable (the dev postgres role is a superuser; needs user permission)
node .claude/skills/postgres-query/query.mjs --dev --writable "UPDATE ..."

Querying the notifications-db (DataPacket)

The notifications-db lives on the DataPacket cluster. Direct network access from your laptop isn't allowed — connect via the SSH bastion.

One-time setup

  1. Make sure your SSH public key has been added to the bastion. If you don't have access yet, ask zach to add your ~/.ssh/id_ed25519.pub to:

    clusters/production/apps/notifications-db/secrets/bastion-ssh-keys.enc.yaml

  2. Get the bastion host, port, and forward target from zach (or read them out of the datapacket-talos repo: bastion deployment is at clusters/production/apps/notifications-db/bastion.yaml, public host/port are in clusters/production/apps/minio/nginx-reverse-proxy.yaml).

  3. Add an SSH config entry (~/.ssh/config) so the tunnel is one command:

    Host notif-bastion
      HostName <bastion-host>
      Port <bastion-port>
      User bastion
      IdentityFile ~/.ssh/id_ed25519
      # Tunnel local 5433 → in-cluster ro pgbouncer pooler
      LocalForward 5433 <ro-pooler-host>:5432
      ServerAliveInterval 60
    
  4. Add the connection string to your project .env (or .claude/skills/postgres-query/.env):

    NOTIFICATION_DB_REPLICA_URL=postgresql://notifications_readonly:<password>@127.0.0.1:5433/notification_prod?sslmode=disable
    

    Get the password from zach (stored in the bastion-pg-creds.enc.yaml secret in the datapacket-talos repo). The same password is also preloaded inside the bastion's .pgpass for in-pod use.

Running queries

# 1. Open the SSH tunnel in one terminal (stays open)
ssh notif-bastion

#    The bastion's MOTD shows the available tables and tools.
#    You can run ad-hoc psql in this terminal too — `psql` is preloaded
#    with .pgpass and PGHOST/PGUSER env vars.

# 2. In another terminal, run queries via the skill
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: Uses DATABASE_REPLICA_URL to prevent accidental writes
  2. Write protection: Blocks INSERT/UPDATE/DELETE/DROP unless --writable flag is used
  3. Notifications is always read-only: --notifications blocks writes client-side AND the database role/pooler reject them
  4. Explicit permission required: Before using --writable, you MUST ask the user for permission

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:

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

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

# Compare actual results
node .claude/skills/postgres-query/query.mjs --json "SELECT ... (approach 1)" > /tmp/q1.json
node .claude/skills/postgres-query/query.mjs --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)
node .claude/skills/postgres-query/query.mjs --explain "SELECT * FROM \"Account\" WHERE provider = 'discord'"

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: postgres-query](https://darkplay.ru/ai/skills/civitai-civitai-postgres-query)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Database Revieweraffaan-m · Специалист PostgreSQL: оптимизация запросов, схемы, безопасность, Supabase.
225 587 ★
alloydbanthropics · Создание, подключение и работа с базой данных и данными AlloyDB для PostgreSQL.
100 комп.
apolloanthropics · Поиск клиентов, обогащение лидов, загрузка цепочек аутрича и аналитика продаж с Apollo.io…
100 комп.
apollo-skillsanthropics · Навыки агентов Apollo GraphQL для Claude Code — Apollo Client, Server, Federation…
100 комп.
azure-cosmos-db-assistantanthropics · Экспертный помощник по Azure Cosmos DB — моделирование данных, оптимизация запросов…
100 комп.
bigquery-data-analyticsanthropics · Подключение, запросы и генерация аналитики по наборам данных и данным BigQuery.
100 комп.
carta-cap-tableanthropics · Плагин Carta Cap Table — навыки и хуки для запросов к cap table, грантам, SAFE, оценкам…
100 комп.
carta-investorsanthropics · Плагин Carta Investors — навыки для запросов данных об инвесторах, бенчмарков…
100 комп.
clickhouse-best-practicesanthropics · 28 правил лучших практик для проектирования схем ClickHouse, оптимизации запросов и…
100 комп.
cloud-sql-postgresqlanthropics · Создание, подключение и работа с базой данных Cloud SQL for PostgreSQL и её данными.
100 комп.

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8