---
name: postgres-patterns
description: |
  PostgreSQL database patterns for query optimization, schema design, indexing, and security.
  Use this skill when working on Arbiter's database (arbiter_db), writing migrations,
  troubleshooting slow queries, or implementing security policies.
source: skill.fish (affaan-m/everything-claude-code)
---

# PostgreSQL Patterns

Quick reference for PostgreSQL best practices.

---

## WHEN TO ACTIVATE

- Writing SQL queries or migrations
- Designing database schemas
- Troubleshooting slow queries
- Implementing Row Level Security
- Setting up connection pooling
- Working on Arbiter's arbiter_db

---

## INDEX CHEAT SHEET

| Query Pattern | Index Type | Example |
|---------------|------------|---------|
| `WHERE col = value` | B-tree (default) | `CREATE INDEX idx ON t (col)` |
| `WHERE col > value` | B-tree | `CREATE INDEX idx ON t (col)` |
| `WHERE a = x AND b > y` | Composite | `CREATE INDEX idx ON t (a, b)` |
| `WHERE jsonb @> '{}'` | GIN | `CREATE INDEX idx ON t USING gin (col)` |
| `WHERE tsv @@ query` | GIN | `CREATE INDEX idx ON t USING gin (col)` |
| Time-series ranges | BRIN | `CREATE INDEX idx ON t USING brin (col)` |

---

## DATA TYPE QUICK REFERENCE

| Use Case | Correct Type | Avoid |
|----------|--------------|-------|
| IDs | `bigint` | `int`, random UUID |
| Strings | `text` | `varchar(255)` |
| Timestamps | `timestamptz` | `timestamp` |
| Money | `numeric(10,2)` | `float` |
| Flags | `boolean` | `varchar`, `int` |

---

## COMMON PATTERNS

### Composite Index Order

```sql
-- Equality columns first, then range columns
CREATE INDEX idx ON orders (status, created_at);
-- Works for: WHERE status = 'pending' AND created_at > '2024-01-01'
```

### Covering Index

```sql
CREATE INDEX idx ON users (email) INCLUDE (name, created_at);
-- Avoids table lookup for SELECT email, name, created_at
```

### Partial Index

```sql
CREATE INDEX idx ON users (email) WHERE deleted_at IS NULL;
-- Smaller index, only includes active users
```

### RLS Policy (Optimized)

```sql
CREATE POLICY policy ON orders
  USING ((SELECT auth.uid()) = user_id);  -- Wrap in SELECT!
```

### UPSERT

```sql
INSERT INTO settings (user_id, key, value)
VALUES (123, 'theme', 'dark')
ON CONFLICT (user_id, key)
DO UPDATE SET value = EXCLUDED.value;
```

### Cursor Pagination

```sql
SELECT * FROM products WHERE id > $last_id ORDER BY id LIMIT 20;
-- O(1) vs OFFSET which is O(n)
```

### Queue Processing

```sql
UPDATE jobs SET status = 'processing'
WHERE id = (
  SELECT id FROM jobs WHERE status = 'pending'
  ORDER BY created_at LIMIT 1
  FOR UPDATE SKIP LOCKED
) RETURNING *;
```

---

## ANTI-PATTERN DETECTION

### Find Unindexed Foreign Keys

```sql
SELECT conrelid::regclass, a.attname
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey)
WHERE c.contype = 'f'
  AND NOT EXISTS (
    SELECT 1 FROM pg_index i
    WHERE i.indrelid = c.conrelid AND a.attnum = ANY(i.indkey)
  );
```

### Find Slow Queries

```sql
SELECT query, mean_exec_time, calls
FROM pg_stat_statements
WHERE mean_exec_time > 100
ORDER BY mean_exec_time DESC;
```

### Check Table Bloat

```sql
SELECT relname, n_dead_tup, last_vacuum
FROM pg_stat_user_tables
WHERE n_dead_tup > 1000
ORDER BY n_dead_tup DESC;
```

---

## CONFIGURATION TEMPLATE

```sql
-- Connection limits (adjust for RAM)
ALTER SYSTEM SET max_connections = 100;
ALTER SYSTEM SET work_mem = '8MB';

-- Timeouts
ALTER SYSTEM SET idle_in_transaction_session_timeout = '30s';
ALTER SYSTEM SET statement_timeout = '30s';

-- Monitoring
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- Security defaults
REVOKE ALL ON SCHEMA public FROM public;

SELECT pg_reload_conf();
```

---

## FIREFROST CONTEXT

### Arbiter Database (arbiter_db)

**Location:** Command Center (63.143.34.217)
**User:** arbiter
**Password:** (see .env on Command Center)

**Current Tables:**
- `subscriptions` — Stripe subscription tracking
- `users` — Discord user data
- `servers` — Pterodactyl server allocations
- `whitelist_entries` — Server whitelist management

**When optimizing Arbiter:**
- Check for missing indexes on foreign keys
- Use `timestamptz` for all time columns
- Consider partial indexes for active subscriptions
- Use cursor pagination for listing endpoints

---

## USEFUL QUERIES FOR ARBITER

### Check Index Usage

```sql
SELECT relname, indexrelname, idx_scan, idx_tup_read
FROM pg_stat_user_indexes
ORDER BY idx_scan DESC;
```

### Check Table Sizes

```sql
SELECT relname, pg_size_pretty(pg_total_relation_size(relid))
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC;
```

### Active Connections

```sql
SELECT count(*), state
FROM pg_stat_activity
WHERE datname = 'arbiter_db'
GROUP BY state;
```

---

**Source:** skill.fish — affaan-m/everything-claude-code (Based on Supabase Agent Skills, MIT License)
**Added:** 2026-04-09 by Chronicler #73

**Fire + Frost + Foundation = Where Love Builds Legacy** 💙🔥❄️
