Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

postgresql-optimizationPostgreSQL optimization 搜索

Agent Skill

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务。它适合让 Agent 分析 schema、编写 SQL、排查查询问题、整理索引或生成迁移建议。使用时需要明确数据库类型、连接环境和目标表,区分只读分析与写入变更;涉及删除、更新、迁移和批量导入时,应优先 dry-run、备份或事务保护,避免误操作。

总安装

353

周安装

15

GitHub Stars

98

下载量

124
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:postgresql-optimization(PostgreSQL optimization 搜索)
来源仓库:https://github.com/curiositech/some_claude_skills
仓库路径:skills/postgresql-optimization
安装命令:
npx skills add https://github.com/curiositech/some_claude_skills --skill postgresql-optimization
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/curiositech/some_claude_skills --skill postgresql-optimization

简介

postgresql-optimization 专长于 PostgreSQL 数据库性能调优,涵盖查询分析与索引策略优化。

  • 可执行 EXPLAIN 分析、推荐索引类型、设计分区表结构并配置连接池以提升高负载场景表现。
  • 适用于诊断慢查询、优化 schema 设计及实施生产级部署配置,但不处理非关系型数据迁移。
  • 使用前必须确认数据库版本、连接方式与安全凭证范围,防止误操作导致数据丢失或服务中断。
  • 涉及 DDL 变更或批量数据操作时应优先启用事务保护或 dry-run 模式进行预演验证。

SKILL.md

PostgreSQL Optimization

Overview

Expert in PostgreSQL performance tuning, query optimization, and database administration. Specializes in EXPLAIN analysis, indexing strategies, connection pooling, partitioning, and production-grade PostgreSQL operations.

When to Use

  • Diagnosing slow queries with EXPLAIN ANALYZE
  • Creating optimal indexes for query patterns
  • Designing database schemas for performance
  • Configuring PostgreSQL for production workloads
  • Implementing connection pooling (PgBouncer, Supavisor)
  • Setting up partitioning for large tables
  • Analyzing and reducing lock contention
  • Migrating or upgrading PostgreSQL versions

Capabilities

Query Optimization

  • EXPLAIN / EXPLAIN ANALYZE interpretation
  • Query plan analysis and optimization
  • Identifying sequential scans vs index scans
  • Join optimization and query rewriting
  • CTE vs subquery performance trade-offs
  • Window function optimization

Indexing Strategies

  • B-tree, GIN, GiST, BRIN index selection
  • Partial indexes for filtered queries
  • Expression indexes for computed values
  • Covering indexes (INCLUDE clause)
  • Index-only scans optimization
  • Concurrent index creation

Schema Design

  • Normalization vs denormalization trade-offs
  • JSONB column design and indexing
  • Array columns and operations
  • Enum types vs lookup tables
  • Foreign key cascade strategies
  • Table inheritance and partitioning

Configuration Tuning

  • Memory settings (shared_buffers, work_mem, effective_cache_size)
  • Connection limits and pooling
  • WAL and checkpoint tuning
  • Autovacuum configuration
  • Statistics collection settings

Advanced Features

  • Partitioning (range, list, hash)
  • Materialized views with refresh strategies
  • Full-text search with tsvector/tsquery
  • PostGIS geospatial queries
  • Logical replication setup
  • pg_stat_statements analysis

Dependencies

Works well with:

  • database-modeler - Schema design and ERD creation
  • data-pipeline-engineer - ETL and data processing
  • site-reliability-engineer - Database monitoring and alerting
  • nextjs-app-router-expert - Full-stack data fetching

Examples

Reading EXPLAIN ANALYZE Output

EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT u.*, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.created_at > '2024-01-01'
GROUP BY u.id;

-- Key metrics to look for:
-- - "Seq Scan" on large tables → needs index
-- - "Rows Removed by Filter" high → filter before join
-- - "Sort Method: external merge" → increase work_mem
-- - "Buffers: shared hit" vs "shared read" → cache efficiency

Creating Effective Indexes

-- Basic B-tree for equality and range queries
CREATE INDEX CONCURRENTLY idx_orders_user_created
ON orders (user_id, created_at DESC);

-- Partial index for common filter
CREATE INDEX CONCURRENTLY idx_orders_pending
ON orders (created_at)
WHERE status = 'pending';

-- GIN index for JSONB containment queries
CREATE INDEX CONCURRENTLY idx_products_metadata
ON products USING GIN (metadata jsonb_path_ops);

-- Covering index to enable index-only scans
CREATE INDEX CONCURRENTLY idx_users_email_covering
ON users (email) INCLUDE (name, created_at);

-- Expression index for case-insensitive search
CREATE INDEX CONCURRENTLY idx_users_email_lower
ON users (LOWER(email));

Optimizing N+1 Queries

-- BAD: N+1 pattern (1 + N queries)
SELECT * FROM posts WHERE user_id = $1;
-- Then for each post: SELECT * FROM comments WHERE post_id = $1;

-- GOOD: Single query with lateral join
SELECT p.*, c.comments
FROM posts p
LEFT JOIN LATERAL (
  SELECT json_agg(c.*) as comments
  FROM comments c
  WHERE c.post_id = p.id
) c ON true
WHERE p.user_id = $1;

-- GOOD: Window function for aggregates
SELECT
  p.*,
  COUNT(*) OVER (PARTITION BY p.user_id) as user_post_count
FROM posts p
WHERE p.user_id = $1;

Table Partitioning

-- Create partitioned table by date range
CREATE TABLE events (
  id BIGSERIAL,
  event_type TEXT NOT NULL,
  payload JSONB,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);

-- Create monthly partitions
CREATE TABLE events_2024_01 PARTITION OF events
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');

CREATE TABLE events_2024_02 PARTITION OF events
FOR VALUES FROM ('2024-02-01') TO ('2024-03-01');

-- Automate partition creation with pg_partman
CREATE EXTENSION pg_partman;
SELECT partman.create_parent('public.events', 'created_at', 'native', 'monthly');

Connection Pooling Config (PgBouncer)

; pgbouncer.ini

[databases]
myapp = host=localhost dbname=myapp

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt

; Pool settings
pool_mode = transaction        ; Recommended for most apps
max_client_conn = 1000
default_pool_size = 20
reserve_pool_size = 5

; Timeouts
server_idle_timeout = 600
client_idle_timeout = 0

Performance Configuration

-- Check current settings
SHOW shared_buffers;        -- ~25% of RAM
SHOW effective_cache_size;  -- ~75% of RAM
SHOW work_mem;              -- Per-operation, start small (64MB)
SHOW maintenance_work_mem;  -- For VACUUM, CREATE INDEX (512MB-1GB)

-- Recommended production settings (for 32GB RAM server)
ALTER SYSTEM SET shared_buffers = '8GB';
ALTER SYSTEM SET effective_cache_size = '24GB';
ALTER SYSTEM SET work_mem = '64MB';
ALTER SYSTEM SET maintenance_work_mem = '1GB';
ALTER SYSTEM SET random_page_cost = 1.1;  -- For SSD storage
ALTER SYSTEM SET effective_io_concurrency = 200;  -- For SSD

-- Reload configuration
SELECT pg_reload_conf();

Finding Slow Queries

-- Enable pg_stat_statements
CREATE EXTENSION pg_stat_statements;

-- Top 10 slowest queries by total time
SELECT
  round(total_exec_time::numeric, 2) as total_ms,
  calls,
  round(mean_exec_time::numeric, 2) as avg_ms,
  round((100 * total_exec_time / sum(total_exec_time) OVER())::numeric, 2) as pct,
  query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

-- Queries with most I/O
SELECT
  round(shared_blks_read::numeric, 2) as disk_reads,
  round(shared_blks_hit::numeric, 2) as cache_hits,
  round(100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0), 2) as cache_hit_ratio,
  query
FROM pg_stat_statements
ORDER BY shared_blks_read DESC
LIMIT 10;

Analyzing Table Bloat

-- Check table bloat
SELECT
  schemaname,
  tablename,
  pg_size_pretty(pg_total_relation_size(schemaname || '.' || tablename)) as total_size,
  pg_size_pretty(pg_relation_size(schemaname || '.' || tablename)) as table_size,
  n_dead_tup,
  n_live_tup,
  round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 2) as dead_pct
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;

-- Manual VACUUM for critical tables
VACUUM (VERBOSE, ANALYZE) orders;

-- Reclaim space (requires exclusive lock)
VACUUM FULL orders;  -- Use during maintenance window

Best Practices

  1. Always use EXPLAIN ANALYZE - Don't guess, measure actual query performance
  2. Create indexes CONCURRENTLY - Avoid blocking writes during index creation
  3. Partial indexes for hot paths - Index only the rows you query frequently
  4. Use connection pooling - PgBouncer or Supavisor for production
  5. Monitor pg_stat_statements - Track query performance over time
  6. Regular ANALYZE - Keep statistics current for query planner
  7. Avoid SELECT * - Only fetch columns you need
  8. Batch large updates - Process in chunks to avoid lock contention
  9. Use prepared statements - Reduce parsing overhead for repeated queries

Common Pitfalls

  • Missing indexes - Check for sequential scans on large tables
  • Over-indexing - Too many indexes slow down writes
  • work_mem too low - Causes disk-based sorts and hash joins
  • Connection exhaustion - Not using connection pooling
  • Stale statistics - Autovacuum not running frequently enough
  • Bloated tables - Not vacuuming after large deletes/updates
  • N+1 queries - Fetching related data in loops instead of joins
  • **SELECT * everywhere** - Fetching unnecessary columns

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.69%
按下载量换算42

Claude

29.41%
按下载量换算36

Cursor

19.11%
按下载量换算24

Gemini CLI

8.85%
按下载量换算11

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills