Skip to main content
ClaudeWave
Skill300 estrellas del repoactualizado yesterday

postgresql-optimization

PostgreSQL-Optimization provides specialized guidance for leveraging PostgreSQL's advanced capabilities including JSONB operations, array types, window functions, and full-text search. Use this skill when developing applications that require sophisticated data querying, analytics, text search functionality, or need to optimize PostgreSQL-specific features for performance-critical workloads.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/syahiidkamil/Software-Engineer-AI-Agent-Atlas /tmp/postgresql-optimization && cp -r /tmp/postgresql-optimization/.claude/skills/postgresql-optimization ~/.claude/skills/postgresql-optimization
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# PostgreSQL Development Assistant

Expert PostgreSQL guidance for ${selection} (or entire project if no selection). Focus on PostgreSQL-specific features, optimization patterns, and advanced capabilities.

## � PostgreSQL-Specific Features

### JSONB Operations
```sql
-- Advanced JSONB queries
CREATE TABLE events (
    id SERIAL PRIMARY KEY,
    data JSONB NOT NULL,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- GIN index for JSONB performance
CREATE INDEX idx_events_data_gin ON events USING gin(data);

-- JSONB containment and path queries
SELECT * FROM events 
WHERE data @> '{"type": "login"}'
  AND data #>> '{user,role}' = 'admin';

-- JSONB aggregation
SELECT jsonb_agg(data) FROM events WHERE data ? 'user_id';
```

### Array Operations
```sql
-- PostgreSQL arrays
CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    tags TEXT[],
    categories INTEGER[]
);

-- Array queries and operations
SELECT * FROM posts WHERE 'postgresql' = ANY(tags);
SELECT * FROM posts WHERE tags && ARRAY['database', 'sql'];
SELECT * FROM posts WHERE array_length(tags, 1) > 3;

-- Array aggregation
SELECT array_agg(DISTINCT category) FROM posts, unnest(categories) as category;
```

### Window Functions & Analytics
```sql
-- Advanced window functions
SELECT 
    product_id,
    sale_date,
    amount,
    -- Running totals
    SUM(amount) OVER (PARTITION BY product_id ORDER BY sale_date) as running_total,
    -- Moving averages
    AVG(amount) OVER (PARTITION BY product_id ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as moving_avg,
    -- Rankings
    DENSE_RANK() OVER (PARTITION BY EXTRACT(month FROM sale_date) ORDER BY amount DESC) as monthly_rank,
    -- Lag/Lead for comparisons
    LAG(amount, 1) OVER (PARTITION BY product_id ORDER BY sale_date) as prev_amount
FROM sales;
```

### Full-Text Search
```sql
-- PostgreSQL full-text search
CREATE TABLE documents (
    id SERIAL PRIMARY KEY,
    title TEXT,
    content TEXT,
    search_vector tsvector
);

-- Update search vector
UPDATE documents 
SET search_vector = to_tsvector('english', title || ' ' || content);

-- GIN index for search performance
CREATE INDEX idx_documents_search ON documents USING gin(search_vector);

-- Search queries
SELECT * FROM documents 
WHERE search_vector @@ plainto_tsquery('english', 'postgresql database');

-- Ranking results
SELECT *, ts_rank(search_vector, plainto_tsquery('postgresql')) as rank
FROM documents 
WHERE search_vector @@ plainto_tsquery('postgresql')
ORDER BY rank DESC;
```

## � PostgreSQL Performance Tuning

### Query Optimization
```sql
-- EXPLAIN ANALYZE for performance analysis
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) 
SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2024-01-01'::date
GROUP BY u.id, u.name;

-- Identify slow queries from pg_stat_statements
SELECT query, calls, total_time, mean_time, rows,
       100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0) AS hit_percent
FROM pg_stat_statements 
ORDER BY total_time DESC 
LIMIT 10;
```

### Index Strategies
```sql
-- Composite indexes for multi-column queries
CREATE INDEX idx_orders_user_date ON orders(user_id, order_date);

-- Partial indexes for filtered queries
CREATE INDEX idx_active_users ON users(created_at) WHERE status = 'active';

-- Expression indexes for computed values
CREATE INDEX idx_users_lower_email ON users(lower(email));

-- Covering indexes to avoid table lookups
CREATE INDEX idx_orders_covering ON orders(user_id, status) INCLUDE (total, created_at);
```

### Connection & Memory Management
```sql
-- Check connection usage
SELECT count(*) as connections, state 
FROM pg_stat_activity 
GROUP BY state;

-- Monitor memory usage
SELECT name, setting, unit 
FROM pg_settings 
WHERE name IN ('shared_buffers', 'work_mem', 'maintenance_work_mem');
```

## �️ PostgreSQL Advanced Data Types

### Custom Types & Domains
```sql
-- Create custom types
CREATE TYPE address_type AS (
    street TEXT,
    city TEXT,
    postal_code TEXT,
    country TEXT
);

CREATE TYPE order_status AS ENUM ('pending', 'processing', 'shipped', 'delivered', 'cancelled');

-- Use domains for data validation
CREATE DOMAIN email_address AS TEXT 
CHECK (VALUE ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');

-- Table using custom types
CREATE TABLE customers (
    id SERIAL PRIMARY KEY,
    email email_address NOT NULL,
    address address_type,
    status order_status DEFAULT 'pending'
);
```

### Range Types
```sql
-- PostgreSQL range types
CREATE TABLE reservations (
    id SERIAL PRIMARY KEY,
    room_id INTEGER,
    reservation_period tstzrange,
    price_range numrange
);

-- Range queries
SELECT * FROM reservations 
WHERE reservation_period && tstzrange('2024-07-20', '2024-07-25');

-- Exclude overlapping ranges
ALTER TABLE reservations 
ADD CONSTRAINT no_overlap 
EXCLUDE USING gist (room_id WITH =, reservation_period WITH &&);
```

### Geometric Types
```sql
-- PostgreSQL geometric types
CREATE TABLE locations (
    id SERIAL PRIMARY KEY,
    name TEXT,
    coordinates POINT,
    coverage CIRCLE,
    service_area POLYGON
);

-- Geometric queries
SELECT name FROM locations 
WHERE coordinates <-> point(40.7128, -74.0060) < 10; -- Within 10 units

-- GiST index for geometric data
CREATE INDEX idx_locations_coords ON locations USING gist(coordinates);
```

## 📊 PostgreSQL Extensions & Tools

### Useful Extensions
```sql
-- Enable commonly used extensions
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";    -- UUID generation
CREATE EXTENSION IF NOT EXISTS "pgcrypto";     -- Cryptographic functions
CREATE EXTENSION IF NOT EXISTS "unaccent";     -- Remove accents from text
CREATE EXTENSION IF NOT EXISTS "pg_trgm";      -- Trigram matching
CREATE EXTENSION IF NOT EXISTS "btree_gin";    -- GIN indexes for btree types

-- Using extensions
SELECT uuid_generate_v4();                     -- Generate UUIDs
SELECT crypt('password', gen_salt('bf'));      -- Hash passwords
SELECT simila
code-architectSubagent

Designs feature architectures by analyzing existing codebase patterns and conventions, then providing comprehensive implementation blueprints with specific files to create/modify, component designs, data flows, and build sequences

code-explorerSubagent

Deeply analyzes existing codebase features by tracing execution paths, mapping architecture layers, understanding patterns and abstractions, and documenting dependencies to inform new development

code-reviewSubagent

Code review a pull request

code-simplifierSubagent

Simplifies and refines code for clarity, consistency, and maintainability while preserving all functionality. Focuses on recently modified code unless instructed otherwise.

commitSlash Command

Commit what is already staged — runs the commit subagent in the background, following the ATLAS commit convention.

qa-manual-testerSubagent

Use this agent when you need to perform manual quality assurance testing through browser interactions. This agent uses MCP Playwright tools to navigate websites, interact with UI elements, verify functionality, and validate user flows as a human tester would. Perfect for testing new features, regression testing, validating bug fixes, or exploring application behavior. Examples:\n\n<example>\nContext: The user has just implemented a new login feature and wants to test it.\nuser: "I've added a new login form, can you test if it works correctly?"\nassistant: "I'll use the qa-manual-tester agent to test the login functionality through the browser."\n<commentary>\nSince the user needs manual testing of a new feature, use the Task tool to launch the qa-manual-tester agent to interact with the browser and verify the login flow.\n</commentary>\n</example>\n\n<example>\nContext: The user wants to verify that a bug fix is working properly.\nuser: "I fixed the issue where the submit button wasn't working on mobile view. Can you verify?"\nassistant: "Let me launch the qa-manual-tester agent to verify the submit button works correctly in mobile view."\n<commentary>\nThe user needs manual verification of a bug fix, so use the qa-manual-tester agent to test the specific functionality through browser interaction.\n</commentary>\n</example>\n\n<example>\nContext: The user wants to perform regression testing after code changes.\nuser: "I've refactored the checkout flow. Please test that everything still works."\nassistant: "I'll use the qa-manual-tester agent to perform comprehensive testing of the checkout flow."\n<commentary>\nSince the user needs regression testing after refactoring, use the qa-manual-tester agent to manually test the entire checkout flow.\n</commentary>\n</example>

change-core-selfSlash Command

Interview Boss about the project, then reason from first principles to design the ideal ATLAS operating identity/system-prompt for it — free to drop KISS/YAGNI/DRY/clean-architecture entirely when the project (and the LLM's own distribution) calls for a different mindset

get-to-knowSlash Command

Initialize project context — understand the project, configure conventions, and set up project rules