postgresql-rails-analyzer
Comprehensive PostgreSQL configuration and usage analysis for Rails applications. Use when Claude Code needs to analyze a Rails codebase for database performance issues, optimization opportunities, or best practice violations. Detects N+1 queries, missing indexes, suboptimal database configurations, anti-patterns, and provides actionable recommendations. Ideal for performance audits, optimization tasks, or when users ask to "analyze the database", "check for N+1 queries", "optimize PostgreSQL", "review database performance", or "suggest database improvements".
What this skill does
# PostgreSQL Rails Analyzer
Analyze Rails applications for PostgreSQL performance issues and provide actionable optimization recommendations based on "High Performance PostgreSQL for Rails" best practices.
## Analysis Scripts
Run from the Rails application root directory:
### 1. N+1 Query Analysis
```bash
ruby scripts/analyze_n_plus_one.rb
```
Detects potential N+1 query issues by analyzing:
- Controller actions for queries without eager loading
- View files for association access patterns
- Missing `includes`, `preload`, or `eager_load` calls
### 2. Index Analysis
```bash
ruby scripts/analyze_indexes.rb
```
Identifies indexing opportunities:
- Foreign keys without indexes (critical)
- Boolean columns that could benefit from partial indexes
- Columns frequently used in WHERE clauses
- Missing composite indexes
### 3. Configuration Analysis
```bash
ruby scripts/analyze_config.rb
```
Reviews database.yml for:
- Connection pool sizing
- Timeout configurations (statement_timeout, lock_timeout)
- Prepared statements settings
- SSL/TLS configuration
- Connection reaping configuration
- Recommended PostgreSQL extensions
## Workflow
### Step 1: Understand the Request
Clarify what the user wants to analyze: full performance audit, specific issue (slow queries, N+1 problems), configuration review, or schema optimization.
### Step 2: Run Appropriate Analysis Scripts
```bash
# For comprehensive analysis, run all three
ruby scripts/analyze_n_plus_one.rb
ruby scripts/analyze_indexes.rb
ruby scripts/analyze_config.rb
```
### Step 3: Review Results
Script output categorizes issues by severity:
- **WARNING**: High-priority issues that likely impact performance
- **INFO**: Optimization opportunities and best practice recommendations
### Step 4: Provide Recommendations
Create a prioritized list of actionable recommendations:
1. **Critical Issues** (fix immediately) — FK indexes, N+1 in hot paths, missing timeouts
2. **Performance Optimizations** (high impact) — partial indexes, counter caches, eager loading
3. **Best Practices** (preventative) — configuration tuning, pool optimization, monitoring
### Step 5: Generate Migration Code
For index and schema recommendations, provide ready-to-use migration code. Use `algorithm: :concurrently` for production migrations to avoid locking tables.
```ruby
class AddPerformanceIndexes < ActiveRecord::Migration[7.0]
disable_ddl_transaction!
def change
add_index :posts, :user_id, algorithm: :concurrently
add_index :users, :active, where: "active = false", algorithm: :concurrently
add_index :orders, [:status, :created_at], algorithm: :concurrently
end
end
```
### Step 6: Reference Additional Documentation
Load these references when users need deeper understanding:
- `references/performance_guide.md` — comprehensive best practices (indexes, queries, config, schema design, monitoring)
- `references/anti_patterns.md` — 25 common mistakes organized by category (queries, indexes, schema, config, transactions)
## Advanced Analysis
For deeper analysis beyond the scripts, manually review:
- **Schema Design** — data types (bigint for high-volume PKs, jsonb vs json), constraints (NOT NULL, CHECK, FOREIGN KEY)
- **Query Patterns** — use `rails c` to run EXPLAIN ANALYZE on slow queries, check for sequential scans on large tables
- **Model Code** — missing counter caches, batch operation opportunities (`find_each` instead of `each`)
## Limitations
These analysis scripts use static analysis. They may produce false positives (flagging non-issues) or false negatives (missing runtime-only issues). Always recommend testing fixes in staging and using EXPLAIN ANALYZE to verify.
## Complementary Tools
Suggest for ongoing monitoring: **PgHero** (dashboard), **pg_stat_statements** (query stats), **Bullet gem** (runtime N+1 detection), **Rails query logging** (development visibility).
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.