Harness sql review

From Intense-Visions/harness-engineering · View interactive version

Harness sql review is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Adversarial review of SQL queries for performance anti-patterns, missing indexes, N+1 queries, and unsafe operations. Analyzes raw SQL, ORM-generated queries, and migration scripts to produce optimi

How to use this skill

Skill file

Harness SQL Review

Adversarial review of SQL queries for performance anti-patterns, missing indexes, N+1 queries, and unsafe operations. Analyzes raw SQL, ORM-generated queries, and migration scripts to produce optimization recommendations with estimated impact.

When to Use

Process

Phase 1: SCAN -- Locate SQL Queries

  1. Resolve project root. Use provided path or cwd.
  1. Detect SQL dialect. Determine the database from project configuration:
  1. Extract raw SQL queries. Scan source files for:
  1. Extract ORM queries. Identify ORM usage and extract the implied SQL:
  1. Scope to PR changes. If triggered by a PR, focus on queries in changed files. Also scan unchanged files that import changed models (they may be affected by schema changes).
  1. Build query inventory. For each query, record:

Phase 2: ANALYZE -- Evaluate Query Patterns

  1. Detect N+1 queries. The most common and impactful anti-pattern:
  1. Detect missing indexes. For each WHERE, JOIN, and ORDER BY clause:
  1. Detect full table scans. Flag queries that:
  1. Detect unsafe operations. Flag queries that:
  1. Detect join inefficiencies. Evaluate:
  1. Detect transaction issues. Check for:

Phase 3: OPTIMIZE -- Produce Recommendations

  1. Generate optimized query alternatives. For each finding, provide:
  1. Recommend index additions. For each missing index:

```sql

-- Recommended: speeds up user lookup by email in login flow

-- Estimated impact: O(N) full scan -> O(log N) index seek

CREATE INDEX idx_users_email ON users (email);

```

Include:

  1. Recommend batching strategies for N+1. Provide specific alternatives:
  1. Recommend query rewrites. For complex subqueries and inefficient patterns:
  1. Prioritize by impact. Order recommendations:

Phase 4: VALIDATE -- Verify Optimization Correctness

  1. Verify semantic equivalence. For every rewritten query:
  1. Verify index recommendations. For each proposed index:
  1. Check for regression risks. Flag:
  1. Output structured report. Present findings in review format:

```

SQL Review: [PASS/NEEDS_ATTENTION/FAIL]

Queries analyzed: N

Findings: E errors, W warnings, I info

ERRORS:

[SQL-N1-001] src/repositories/OrderRepository.ts:45

N+1 query in getOrdersWithItems(): queries items per order in loop

Current: 1 + N queries (N = number of orders)

Recommended: Single query with JOIN or Prisma include

Impact: O(N) -> O(1) database round trips

[SQL-UNSAFE-001] src/services/CleanupService.ts:23

DELETE without WHERE clause: db.execute("DELETE FROM temp_records")

Risk: Deletes all records if called outside intended context

Recommended: Add WHERE clause with date filter or use TRUNCATE in migration

WARNINGS:

[SQL-IDX-001] src/repositories/UserRepository.ts:78

Missing index: WHERE email = ? on users table (estimated 500K rows)

Recommended: CREATE INDEX idx_users_email ON users (email);

```

  1. Verify no new anti-patterns introduced. Check that recommended optimizations do not introduce new problems (e.g., a JOIN recommendation that creates a Cartesian product, or an index recommendation on a column already indexed).

Harness Integration

Success Criteria

Examples

Example: Express.js API with Prisma ORM

Phase 1: SCAN
  Dialect: PostgreSQL (detected from DATABASE_URL)
  ORM: Prisma 5.10
  Queries found: 34 (28 Prisma, 4 $queryRaw, 2 $executeRaw)
  Scope: PR diff (3 changed repository files)

Phase 2: ANALYZE
  [SQL-N1-001] src/routes/orders.ts:67
    findMany orders then findUnique for each order's customer
    Pattern: 1 query for orders + N queries for customers
  [SQL-IDX-001] src/routes/products.ts:23
    findMany with where: { category: catId, status: "active" }
    No composite index on (category_id, status)
  [SQL-UNSAFE-001] src/routes/admin.ts:89
    $executeRaw DELETE FROM sessions (no WHERE clause)

Phase 3: OPTIMIZE
  N+1 fix: Use Prisma include: { customer: true }
  Index: CREATE INDEX idx_products_category_status ON products (category_id, status);
  Safety: Add WHERE expired_at < NOW() to session cleanup

Phase 4: VALIDATE
  All rewrites produce equivalent results: YES
  Index does not duplicate existing: YES (checked schema.prisma)
  Report: FAIL (1 N+1 error, 1 unsafe operation, 1 missing index)

Example: Django REST Framework with Raw SQL

Phase 1: SCAN
  Dialect: PostgreSQL (detected from DATABASES setting)
  ORM: Django ORM + 6 raw SQL queries
  Queries found: 52 (46 ORM, 6 raw)
  Scope: full project audit

Phase 2: ANALYZE
  [SQL-N1-001] views/analytics.py:34
    for report in reports: report.author.name (lazy loading author per report)
  [SQL-SCAN-001] queries/search.sql:12
    WHERE description LIKE '%' || search_term || '%' (leading wildcard, full scan)
  [SQL-JOIN-001] views/dashboard.py:78
    3 sequential queries that could be a single JOIN
  [SQL-TXN-001] views/transfer.py:45
    Debit + credit operations without @transaction.atomic

Phase 3: OPTIMIZE
  N+1: Add select_related('author') to queryset
  Search: Recommend PostgreSQL full-text search with GIN index:
    CREATE INDEX idx_items_description_gin ON items USING GIN (to_tsvector('english', description));
  Join: Combine 3 queries into single query with LEFT JOIN
  Transaction: Wrap debit+credit in @transaction.atomic

Phase 4: VALIDATE
  All optimizations preserve correctness: YES
  Full-text search returns equivalent results: YES (for word-boundary matches)
  Report: FAIL (1 N+1, 1 missing transaction) + 2 warnings

Example: Go Service with sqlx and Raw Queries

Phase 1: SCAN
  Dialect: PostgreSQL (detected from connection string)
  Query library: sqlx
  Queries found: 28 (all raw SQL in repository files)
  SQL files: 12 in queries/ directory

Phase 2: ANALYZE
  [SQL-N1-001] internal/repo/order_repo.go:56
    GetOrdersByUser calls GetItemsByOrderID in loop
  [SQL-IDX-001] queries/search_users.sql:3
    WHERE created_at > $1 AND status = $2 ORDER BY created_at
    Missing composite index on (status, created_at)
  [SQL-PERF-001] queries/report_daily.sql:8
    Correlated subquery for calculating running total
    Recommend: window function SUM() OVER (ORDER BY date)

Phase 3: OPTIMIZE
  N+1: Rewrite with single query using LEFT JOIN and GROUP BY
  Index: CREATE INDEX idx_users_status_created ON users (status, created_at);
  Rewrite: Replace correlated subquery with:
    SELECT date, amount, SUM(amount) OVER (ORDER BY date) as running_total
    FROM daily_revenue;

Phase 4: VALIDATE
  Window function produces identical results: YES
  Index column order matches query pattern: YES (equality on status, range on created_at)
  Report: NEEDS_ATTENTION (1 N+1 error, 1 missing index, 1 query rewrite)

Rationalizations to Reject

| Rationalization | Reality |

| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

| "The ORM handles query optimization automatically" | ORMs generate syntactically correct queries but do not detect N+1 patterns, choose optimal join strategies, or add missing indexes. The ORM executes what the code asks for. A findMany followed by per-item findUnique calls in a loop is an N+1 regardless of which ORM executes it. |

| "That endpoint is only called by admins so performance doesn't matter" | Admin endpoints frequently become user-facing as products grow. An N+1 query on a 10-row table becomes a crisis when the table grows to 100,000 rows. Query correctness should not be conditional on current data volume. |

| "We can add indexes later if performance becomes a problem" | Adding indexes to large production tables requires exclusive locks or online rebuild procedures that carry risk. Identifying and adding the correct index during development, before the table grows, costs minutes instead of hours of planned maintenance. |

| "That DELETE without a WHERE clause is wrapped in application logic that only calls it correctly" | Application logic has bugs. A missing WHERE clause is a single misrouted request away from deleting the entire table. Database safety constraints must not depend on application-layer correctness. |

| "The query is fast in development — the test database only has 100 rows" | Development databases do not represent production query plans. Full table scans, missing indexes, and N+1 patterns only manifest at production data volumes. Static analysis catches these issues regardless of local data size. |

Gates

Escalation

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.