| name | postgres-ops |
| description | Set up and manage local PostgreSQL via Docker and psql for development and testing. Trigger: when setting up postgres, connecting to PostgreSQL, creating databases, running psql, using Docker postgres |
| version | 1 |
| argument-hint | [database-url or action] |
| allowed-tools | ["bash","read","write","grep","glob"] |
PostgreSQL Operations
You are now operating in PostgreSQL management mode.
Start Local PostgreSQL with Docker
docker run -d \
--name postgres \
-p 5432:5432 \
-e POSTGRES_PASSWORD=dev \
postgres:16
docker ps --filter name=postgres
Connect with psql
psql postgresql://postgres:dev@localhost:5432/postgres
psql -h localhost -p 5432 -U postgres -d postgres
psql postgresql://postgres:dev@localhost:5432/postgres -c "SELECT version();"
Database Management
docker exec postgres psql -U postgres -c "CREATE DATABASE myapp;"
psql postgresql://postgres:dev@localhost:5432/postgres -c "\l"
psql postgresql://postgres:dev@localhost:5432/postgres -c "DROP DATABASE IF EXISTS myapp;"
psql postgresql://postgres:dev@localhost:5432/postgres -c \
"CREATE USER appuser WITH PASSWORD 'secret';"
psql postgresql://postgres:dev@localhost:5432/postgres -c \
"GRANT ALL PRIVILEGES ON DATABASE myapp TO appuser;"
Schema Inspection
psql $DATABASE_URL -c "\dt"
psql $DATABASE_URL -c "\d+ users"
psql $DATABASE_URL -c "\dn"
psql $DATABASE_URL -c "SELECT schemaname, tablename, n_live_tup FROM pg_stat_user_tables ORDER BY n_live_tup DESC;"
Query Analysis
psql $DATABASE_URL -c "EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'test@example.com';"
psql $DATABASE_URL -c "SELECT query, calls, total_time, mean_time FROM pg_stat_statements ORDER BY mean_time DESC LIMIT 10;"
psql $DATABASE_URL -c "SELECT pid, usename, application_name, state, query FROM pg_stat_activity WHERE state != 'idle';"
psql $DATABASE_URL -c "SELECT indexname, idx_scan, idx_tup_read FROM pg_stat_user_indexes ORDER BY idx_scan ASC;"
Backup and Restore
pg_dump -Fc $DATABASE_URL > backup.dump
pg_dump $DATABASE_URL > backup.sql
pg_dump --schema-only $DATABASE_URL > schema.sql
pg_restore -d $DATABASE_URL backup.dump
psql $DATABASE_URL < backup.sql
Cleanup
docker stop postgres && docker rm postgres
docker stop postgres && docker rm -v postgres
Connection String Format
postgresql://[user]:[password]@[host]:[port]/[database]?sslmode=disable
# Examples:
# Local dev (no SSL):
postgresql://postgres:dev@localhost:5432/myapp?sslmode=disable
# Production (with SSL):
postgresql://appuser:secret@db.example.com:5432/myapp?sslmode=require
Safety Rules
- Never run
DROP DATABASE or DROP TABLE in production without a backup.
- Use transactions for multi-statement schema changes:
BEGIN; ...; COMMIT;
- Always test migrations on a copy of production data first.
- Store connection strings in environment variables, never in source code.