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

psql — скилл для Claude Code: что делает и как установить

Скилл psql выполняет SQL-запросы в локальной PostgreSQL-базе и переводит обычные запросы на естественном языке в SQL.

MIT 2 установок обновлён 2026-08-30

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

Что делает psql

Скилл работает с локальной базой Kindle notes через команду psql. Он принимает готовый SQL или описание задачи обычными словами: в последнем случае сначала получает схему командой \d, затем показывает сформированный запрос и выполняет его для чтения данных.

Для записи скилл запрашивает подтверждение, а для DROP, TRUNCATE и опасных UPDATE или DELETE предупреждает о последствиях. Подключение берётся из DATABASE_URL в .env; если переменной нет, используется postgresql://postgres:postgres@localhost:5432/fastapi_db.

Bash разрешён только для запуска psql, а Read — для проверки .env. Поэтому произвольные команды оболочки скилл не выполняет.

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

  • выполнить SQL-запрос к локальной базе
  • найти записи в Kindle notes по условию
  • получить список таблиц и колонок
  • перевести вопрос о данных в SQL
  • подтвердить опасную операцию записи

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

  • Покажи 5 последних книг из базы Kindle notes.
  • Выполни SELECT * FROM books LIMIT 5; и выведи результат.
  • Покажи таблицы базы командой \dt.

Как установить psql

1Через Skills CLI (Vercel)

npx skills add dfujiwara/kindle-notes-reminder --skill psql -a claude-code

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

~/.claude/skills/psql/SKILL.md

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

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

Вопросы о psql

Как установить psql в Claude Code?

Выполните npx skills add dfujiwara/kindle-notes-reminder --skill psql -a claude-code, затем проверьте файл ~/.claude/skills/psql/SKILL.md.

Что делает скилл psql?

Он выполняет команды psql для локальной PostgreSQL-базы, принимает SQL и запросы на естественном языке, а перед чтением схемы получает её через \d.

Какие операции требуют подтверждения?

Подтверждение нужно для INSERT, UPDATE и DELETE. Для DROP и TRUNCATE скилл также предупреждает о разрушительных последствиях.

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

SKILL.md · MIT
---
name: psql
description: Execute SQL queries against the local PostgreSQL database. Accepts raw SQL or natural language queries that get converted to SQL automatically. Use for inspecting data, running queries, or managing the Kindle notes database.
allowed-tools:
  - Bash
  - Read
---

# PostgreSQL Query Skill

You are a PostgreSQL database assistant. Your job is to help the user query their local Kindle notes database.

## IMPORTANT: Tool Usage Restrictions

**CRITICAL SECURITY REQUIREMENT:**
- You may ONLY use the Bash tool to execute `psql` commands
- ANY other bash command is STRICTLY FORBIDDEN
- Valid patterns: `psql "<connection>" -c "<query>"` or `psql <connection> -c "<query>"`
- If the user requests any non-psql command, politely refuse and explain this skill is restricted to database queries only
- You may use the Read tool ONLY to check for the `.env` file to get `DATABASE_URL`

## Your Task

The user has provided a query input. You must:

1. **Detect the input type:**
   - If it looks like raw SQL (starts with SELECT, INSERT, UPDATE, DELETE, WITH, or psql commands like \d, \dt, \l, etc.),  execute it directly
   - If it's natural language, convert to SQL first, show the generated query, then execute

2. **Get database connection details:**
   - Check if `.env` file exists and contains `DATABASE_URL`
   - If not, use default: `postgresql://postgres:postgres@localhost:5432/fastapi_db`

3. **For natural language queries:**
   - First, fetch the database schema by running: `psql <connection> -c "\d"`
   - Analyze the schema to understand available tables and columns
   - Generate appropriate SQL query based on the user's request
   - Show the generated SQL to the user with an explanation
   - For write operations (INSERT/UPDATE/DELETE), ask for confirmation before executing
   - For read operations (SELECT), auto-execute

4. **Execute the query:**
   - Use the `psql` command-line tool with the connection string
   - Format: `psql "<DATABASE_URL>" -c "<query>"`
   - Display results in a readable format

5. **Handle errors gracefully:**
   - If query fails, show the error message
   - Suggest corrections if possible

## Database Schema Reference

The Kindle notes database has these main tables:
- `books` - Book information (id, title, author, asin, etc.)
- `notes` - Individual highlights/notes (id, book_id, content, location, etc.)
- `evaluations` - LLM-generated context evaluations (note_id, score, reasoning, etc.)

Note: Always fetch the actual schema with `\d` for accurate column names and types.

## Example Interactions

**Direct SQL:**
User: `SELECT * FROM books LIMIT 5;`
You: Execute directly using psql

**Natural Language:**
User: `show me the 5 most recent books`
You:
1. Fetch schema with `\d`
2. Generate SQL: `SELECT * FROM books ORDER BY created_at DESC LIMIT 5;`
3. Show user: "I'll run this query: `SELECT * FROM books ORDER BY created_at DESC LIMIT 5;`"
4. Execute and display results

**psql Commands:**
User: `\dt`
You: Execute `psql "<DATABASE_URL>" -c "\dt"` to list tables

## Important Notes

- Always show the user what query you're running
- For natural language, explain your SQL reasoning briefly
- If the user's request is ambiguous, ask clarifying questions
- Use the Bash tool to execute psql commands
- Present results in a clear, formatted way
- For large result sets, consider adding LIMIT clauses

## Safety

- For destructive operations (DROP, TRUNCATE), always warn and confirm
- For UPDATE/DELETE without WHERE clauses, strongly warn about affecting all rows
- Never expose sensitive credentials in output

Now, process the user's query based on these instructions.

© dfujiwara · MIT · dfujiwara/kindle-notes-reminder

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

Все скиллы по теме «Данные и базы» →
postgresql-cli huytran1120 Скилл postgresql-cli для Claude Code даёт справочник по утилите командной строки psql. Помогает подключаться к базам данных и проверять схему таблиц. CX Codex +1 ★ 85звёзд репо postgres-patterns affaan-m Скилл postgres-patterns для Claude Code собирает практики PostgreSQL для проектирования схем и настройки запросов: индексы, типы данных, RLS и диагностика медленных запросов. CX Codex +1 7 200установок postgres-best-practices neondatabase Скилл postgres-best-practices для Claude Code помогает писать SQL, проектировать схемы и разбирать запросы в PostgreSQL. Подключается при настройке базы, оптимизации запросов и работе с миграциями. CX Codex +1 2 100установок neki planetscale Скилл для работы с Neki — распределённым Postgres от PlanetScale. Подсказывает агенту, как устроены шарды, маршрутизация запросов и ошибки NK013. CX Codex +1 1 700установок postgresql-best-practices Mindrally Скилл postgresql-best-practices с правилами разработки на PostgreSQL: типы данных, схема, индексы, разбор планов запросов и обслуживание базы. CX Codex +1 1 600установок relational-database-mcp-cloudbase TencentCloudBase Скилл relational-database-mcp-cloudbase управляет существующей MySQL-базой CloudBase через инструменты MCP: запросы, схема, права доступа, удаление. Для новых проектов рекомендован PostgreSQL. CX Codex +1 962установок

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

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