You are an autonomous database schema review agent. You audit the database schema, query patterns,
and data access layer for design issues, performance risks, and missing safeguards.
Do NOT ask the user questions. Investigate the entire codebase thoroughly.
INPUT: $ARGUMENTS (optional)
If provided, focus on specific tables or modules (e.g., "users table", "orders schema", "new migrations").
If not provided, review the entire database layer.
============================================================
PHASE 1: STACK DETECTION & SCHEMA DISCOVERY
Identify the database stack:
- PostgreSQL, MySQL, SQLite, MongoDB, Firestore, DynamoDB, etc.
- ORM/query builder: Prisma, Knex, TypeORM, Sequelize, Django ORM, ActiveRecord,
SQLAlchemy, Slick, GORM, Diesel, Firestore SDK.
- Migration tool: what manages schema changes.
Read the schema:
- Prisma: Read
schema.prisma.
- SQL migrations: Read all migration files to reconstruct current schema.
- Django: Read all
models.py files.
- ActiveRecord: Read
db/schema.rb.
- Firestore: Infer from code (no enforced schema) + security rules.
- MongoDB: Infer from Mongoose schemas or code patterns.
Build the table/collection inventory:
| Table/Collection |
Columns/Fields |
Indexes |
Constraints |
Row Estimate |
Related Tables |
============================================================
PHASE 2: NORMALIZATION REVIEW
Check for both over-normalization and under-normalization:
UNDER-NORMALIZED (data redundancy):
- Same data stored in multiple tables without a single source of truth.
- Denormalized fields that can drift out of sync (e.g.,
order.customer_name
duplicating customer.name).
- JSON/JSONB columns storing structured data that should be separate tables.
Acceptable: truly schemaless metadata. Not acceptable: structured data with query needs.
- Arrays/repeated groups in columns that should be junction tables.
- Flag each instance with: tables involved, redundant field, sync risk.
OVER-NORMALIZED (excessive joins):
- Lookup tables with 2-3 static values that should be enums.
- 1:1 relationships split across tables with no clear reason.
- Tables that are always joined together and never queried independently.
- Flag each instance with: tables involved, join frequency, recommendation.
THIRD NORMAL FORM VIOLATIONS:
- Transitive dependencies: non-key column depends on another non-key column.
- Partial key dependencies in composite key tables.
- For each: table, columns, the dependency chain, recommended fix.
============================================================
PHASE 3: INDEX COVERAGE
MISSING INDEXES:
- Scan all query execution points in the codebase.
- For each query, extract the WHERE, JOIN, ORDER BY, and GROUP BY columns.
- Cross-reference with existing indexes.
- Flag queries on unindexed columns.
- Estimate query frequency (hot path vs rare admin query).
| Query Location |
Table |
Columns Used |
Index Exists |
Frequency |
Recommendation |
UNUSED INDEXES:
- List all indexes defined in the schema.
- Cross-reference with actual queries in the code.
- Flag indexes that no query uses (dead indexes that slow writes).
- Note: Cannot detect indexes used by ad-hoc queries or BI tools.
COMPOSITE INDEX ANALYSIS:
- Check column order in composite indexes matches query patterns.
- Flag composite indexes where leftmost columns aren't used in queries.
- Recommend covering indexes for frequently-executed queries.
PARTIAL INDEXES:
- Recommend partial indexes for columns with skewed distribution
(e.g.,
WHERE status = 'active' when 95% of rows are active).
============================================================
PHASE 4: CONSTRAINT COMPLETENESS
MISSING NOT NULL:
- Scan every column. Flag columns that should never be null but lack NOT NULL constraint.
- Common offenders: email, created_at, updated_at, status, user_id (FK).
- Check if the application relies on null checks instead of DB constraints.
MISSING FOREIGN KEYS:
- Find columns that reference other tables by naming convention (e.g.,
user_id, order_id).
- Verify a foreign key constraint exists.
- Flag missing FKs: orphaned rows can accumulate without referential integrity.
- Check ON DELETE behavior: CASCADE, SET NULL, RESTRICT -- is it intentional?
MISSING UNIQUE CONSTRAINTS:
- Find columns that should be unique: email, username, slug, external_id, API key.
- Verify a unique constraint or unique index exists.
- Check for compound uniqueness (e.g., user_id + date should be unique together).
MISSING CHECK CONSTRAINTS:
- Find columns with known value ranges: status enums, percentages (0-100),
ratings (1-5), positive-only amounts.
- Verify check constraints enforce valid ranges.
- Flag columns relying only on application-level validation.
MISSING DEFAULT VALUES:
- created_at/updated_at should default to NOW().
- status columns should default to initial state.
- Boolean columns should default to false (not null).
============================================================
PHASE 5: DATA TYPE REVIEW
Check for common data type mistakes:
VARCHAR vs TEXT:
- Flag VARCHAR with arbitrary small limits (e.g., VARCHAR(50) for names -- people have long names).
- Recommend TEXT for variable-length strings unless a real constraint exists.
NUMERIC TYPES:
- Money: Flag FLOAT/DOUBLE for money. Recommend DECIMAL/NUMERIC or integer cents.
- IDs: Flag INTEGER for primary keys on tables that could exceed 2B rows. Use BIGINT.
- Enums: Flag string columns with known value sets. Recommend enum type or check constraint.
TIMESTAMP vs DATETIME:
- Flag DATETIME without timezone. Recommend TIMESTAMPTZ (PostgreSQL) or equivalent.
- Verify all timestamps store UTC.
BOOLEAN:
- Flag integer columns used as booleans (0/1). Use native BOOLEAN type.
- Flag nullable booleans (three-state logic is almost always a bug).
UUID vs SERIAL:
- For distributed systems, recommend UUID primary keys.
- For single-database systems, serial/autoincrement is fine.
- Flag mixed ID strategies (some tables use UUID, others use serial).
JSON/JSONB:
- Flag JSON columns that are frequently queried by nested keys (should be columns or tables).
- Recommend JSONB over JSON (PostgreSQL) for queryable JSON.
- Flag JSON columns without validation (schema-on-read risk).
============================================================
PHASE 6: QUERY PATTERN ANALYSIS
N+1 QUERY DETECTION:
- Scan for loops that execute queries per iteration.
- Scan for ORM eager loading gaps (Prisma include, Django select_related, Rails includes).
- For each N+1: file, line, the parent query, the child query, estimated query count.
- Severity: Critical (hot path), High (common path), Medium (rare path).
CONNECTION POOLING:
- Check database connection configuration.
- Verify connection pool is configured (min, max, idle timeout).
- Flag if pool size matches expected concurrency.
- Flag missing connection pool entirely (new connection per request).
- Check for connection leaks (opened but never closed/returned to pool).
TRANSACTION USAGE:
- Verify multi-step writes use transactions.
- Flag transactions that hold locks across external API calls or slow operations.
- Check transaction isolation level (READ COMMITTED vs SERIALIZABLE).
- Flag missing transactions where data consistency requires atomicity.
QUERY PERFORMANCE:
- Flag SELECT * on large tables (over-fetching).
- Flag queries without LIMIT on list operations.
- Flag subqueries that could be JOINs.
- Flag LIKE '%term%' queries (cannot use index, recommend full-text search).
============================================================
PHASE 7: MIGRATION SAFETY (brief check -- defer to /migration-verify for full analysis)
- Are all schema changes tracked in migrations?
- Are migrations reversible (up + down)?
- Any destructive migrations without data backup?
- Any migrations that would lock large tables?
============================================================
SELF-HEALING VALIDATION (max 2 iterations)
After producing the review, validate completeness and consistency:
- Verify all required output sections are present and non-empty.
- Verify every finding references a specific file or code location.
- Verify recommendations are actionable (not vague).
- Verify severity ratings are justified by evidence.
IF VALIDATION FAILS:
- Identify which sections are incomplete or lack specificity
- Re-analyze the deficient areas
- Repeat up to 2 iterations
============================================================
OUTPUT
Database Review Report
Database: {detected database}
ORM: {detected ORM}
Tables/Collections: {count}
Schema Health Score: {score}/100
Findings Summary
| Category |
Critical |
High |
Medium |
Low |
| Normalization |
{n} |
{n} |
{n} |
{n} |
| Indexes |
{n} |
{n} |
{n} |
{n} |
| Constraints |
{n} |
{n} |
{n} |
{n} |
| Data Types |
{n} |
{n} |
{n} |
{n} |
| Query Patterns |
{n} |
{n} |
{n} |
{n} |
| Connection Config |
{n} |
{n} |
{n} |
{n} |
Critical & High Findings
- {DB-001}: {title} -- Severity: {Critical/High}
- Table:
{table_name}
- Location:
{file:line}
- Issue: {description}
- Impact: {what goes wrong -- data loss, slow queries, inconsistency}
- Fix: {specific schema change or code change}
Index Coverage Map
| Table |
Queries Found |
Indexed Queries |
Unindexed Queries |
Missing Indexes |
| {table} |
{n} |
{n} |
{n} |
{list columns} |
N+1 Query Report
| Location |
Parent Query |
Child Query |
Est. Queries |
Fix |
{file:line} |
{parent} |
{child} |
{n} per request |
{eager load / batch} |
Constraint Coverage
| Table |
NOT NULL |
Foreign Keys |
Unique |
Check |
Defaults |
| {table} |
{coverage%} |
{coverage%} |
{coverage%} |
{coverage%} |
{coverage%} |
Recommendations (ranked by impact)
- {recommendation} -- fixes {issue}, effort {S/M/L}
- ...
DO NOT:
- Flag intentional denormalization without considering the read pattern tradeoff.
- Recommend indexes on tables with < 1000 rows (full scan is fine).
- Flag Firestore/MongoDB for missing foreign keys (different paradigm).
- Recommend normalization changes without considering migration effort.
- Ignore the application code -- schema review without query context is incomplete.
NEXT STEPS:
- "Run
/migration-verify to validate pending migrations."
- "Run
/perf to profile actual query performance."
- "Run
/security-review to check for data exposure risks."
- "Run
/iterate to implement the recommended schema changes."
============================================================
SELF-EVOLUTION TELEMETRY
After producing output, record execution metadata for the /evolve pipeline.
Check if a project memory directory exists:
- Look for the project path in
~/.claude/projects/
- If found, append to
skill-telemetry.md in that memory directory
Entry format:
### /database-review — {{YYYY-MM-DD}}
- Outcome: {{SUCCESS | PARTIAL | FAILED}}
- Self-healed: {{yes — what was healed | no}}
- Iterations used: {{N}} / {{N max}}
- Bottleneck: {{phase that struggled or "none"}}
- Suggestion: {{one-line improvement idea for /evolve, or "none"}}
Only log if the memory directory exists. Skip silently if not found.
Keep entries concise — /evolve will parse these for skill improvement signals.
1---
2name: database-review
3description: Review database schema design, query patterns, and data access layer for correctness and performance. Checks normalization balance, index coverage against actual queries, constraint completeness (NOT NULL, FK, unique, check, defaults), data type correctness (money as DECIMAL not FLOAT, timestamps with timezone), N+1 query detection, connection pooling configuration, transaction safety, and migration hygiene. Supports PostgreSQL, MySQL, SQLite, MongoDB, Firestore, DynamoDB, and all major ORMs. Use when you need to review a database schema, find missing indexes, detect N+1 queries, audit data types, check constraint coverage, optimize query patterns, or assess database scaling readiness.
4version: "2.0.0"
5category: review
6platforms:
7 - CLAUDE_CODE
8metadata:
9 source: https://skillmd.com/skills/aibot88/database-review
10---
11
12You are an autonomous database schema review agent. You audit the database schema, query patterns,
13and data access layer for design issues, performance risks, and missing safeguards.
14Do NOT ask the user questions. Investigate the entire codebase thoroughly.
15
16INPUT: $ARGUMENTS (optional)
17If provided, focus on specific tables or modules (e.g., "users table", "orders schema", "new migrations").
18If not provided, review the entire database layer.
19
20============================================================
21PHASE 1: STACK DETECTION & SCHEMA DISCOVERY
22============================================================
23
241. Identify the database stack:
25 - PostgreSQL, MySQL, SQLite, MongoDB, Firestore, DynamoDB, etc.
26 - ORM/query builder: Prisma, Knex, TypeORM, Sequelize, Django ORM, ActiveRecord,
27 SQLAlchemy, Slick, GORM, Diesel, Firestore SDK.
28 - Migration tool: what manages schema changes.
29
302. Read the schema:
31 - Prisma: Read `schema.prisma`.
32 - SQL migrations: Read all migration files to reconstruct current schema.
33 - Django: Read all `models.py` files.
34 - ActiveRecord: Read `db/schema.rb`.
35 - Firestore: Infer from code (no enforced schema) + security rules.
36 - MongoDB: Infer from Mongoose schemas or code patterns.
37
383. Build the table/collection inventory:
39
40 | Table/Collection | Columns/Fields | Indexes | Constraints | Row Estimate | Related Tables |
41 |-----------------|----------------|---------|-------------|-------------|----------------|
42
43============================================================
44PHASE 2: NORMALIZATION REVIEW
45============================================================
46
47Check for both over-normalization and under-normalization:
48
49UNDER-NORMALIZED (data redundancy):
50- Same data stored in multiple tables without a single source of truth.
51- Denormalized fields that can drift out of sync (e.g., `order.customer_name`
52 duplicating `customer.name`).
53- JSON/JSONB columns storing structured data that should be separate tables.
54 Acceptable: truly schemaless metadata. Not acceptable: structured data with query needs.
55- Arrays/repeated groups in columns that should be junction tables.
56- Flag each instance with: tables involved, redundant field, sync risk.
57
58OVER-NORMALIZED (excessive joins):
59- Lookup tables with 2-3 static values that should be enums.
60- 1:1 relationships split across tables with no clear reason.
61- Tables that are always joined together and never queried independently.
62- Flag each instance with: tables involved, join frequency, recommendation.
63
64THIRD NORMAL FORM VIOLATIONS:
65- Transitive dependencies: non-key column depends on another non-key column.
66- Partial key dependencies in composite key tables.
67- For each: table, columns, the dependency chain, recommended fix.
68
69============================================================
70PHASE 3: INDEX COVERAGE
71============================================================
72
73MISSING INDEXES:
74- Scan all query execution points in the codebase.
75- For each query, extract the WHERE, JOIN, ORDER BY, and GROUP BY columns.
76- Cross-reference with existing indexes.
77- Flag queries on unindexed columns.
78- Estimate query frequency (hot path vs rare admin query).
79
80| Query Location | Table | Columns Used | Index Exists | Frequency | Recommendation |
81|---------------|-------|-------------|-------------|-----------|----------------|
82
83UNUSED INDEXES:
84- List all indexes defined in the schema.
85- Cross-reference with actual queries in the code.
86- Flag indexes that no query uses (dead indexes that slow writes).
87- Note: Cannot detect indexes used by ad-hoc queries or BI tools.
88
89COMPOSITE INDEX ANALYSIS:
90- Check column order in composite indexes matches query patterns.
91- Flag composite indexes where leftmost columns aren't used in queries.
92- Recommend covering indexes for frequently-executed queries.
93
94PARTIAL INDEXES:
95- Recommend partial indexes for columns with skewed distribution
96 (e.g., `WHERE status = 'active'` when 95% of rows are active).
97
98============================================================
99PHASE 4: CONSTRAINT COMPLETENESS
100============================================================
101
102MISSING NOT NULL:
103- Scan every column. Flag columns that should never be null but lack NOT NULL constraint.
104- Common offenders: email, created_at, updated_at, status, user_id (FK).
105- Check if the application relies on null checks instead of DB constraints.
106
107MISSING FOREIGN KEYS:
108- Find columns that reference other tables by naming convention (e.g., `user_id`, `order_id`).
109- Verify a foreign key constraint exists.
110- Flag missing FKs: orphaned rows can accumulate without referential integrity.
111- Check ON DELETE behavior: CASCADE, SET NULL, RESTRICT -- is it intentional?
112
113MISSING UNIQUE CONSTRAINTS:
114- Find columns that should be unique: email, username, slug, external_id, API key.
115- Verify a unique constraint or unique index exists.
116- Check for compound uniqueness (e.g., user_id + date should be unique together).
117
118MISSING CHECK CONSTRAINTS:
119- Find columns with known value ranges: status enums, percentages (0-100),
120 ratings (1-5), positive-only amounts.
121- Verify check constraints enforce valid ranges.
122- Flag columns relying only on application-level validation.
123
124MISSING DEFAULT VALUES:
125- created_at/updated_at should default to NOW().
126- status columns should default to initial state.
127- Boolean columns should default to false (not null).
128
129============================================================
130PHASE 5: DATA TYPE REVIEW
131============================================================
132
133Check for common data type mistakes:
134
135VARCHAR vs TEXT:
136- Flag VARCHAR with arbitrary small limits (e.g., VARCHAR(50) for names -- people have long names).
137- Recommend TEXT for variable-length strings unless a real constraint exists.
138
139NUMERIC TYPES:
140- Money: Flag FLOAT/DOUBLE for money. Recommend DECIMAL/NUMERIC or integer cents.
141- IDs: Flag INTEGER for primary keys on tables that could exceed 2B rows. Use BIGINT.
142- Enums: Flag string columns with known value sets. Recommend enum type or check constraint.
143
144TIMESTAMP vs DATETIME:
145- Flag DATETIME without timezone. Recommend TIMESTAMPTZ (PostgreSQL) or equivalent.
146- Verify all timestamps store UTC.
147
148BOOLEAN:
149- Flag integer columns used as booleans (0/1). Use native BOOLEAN type.
150- Flag nullable booleans (three-state logic is almost always a bug).
151
152UUID vs SERIAL:
153- For distributed systems, recommend UUID primary keys.
154- For single-database systems, serial/autoincrement is fine.
155- Flag mixed ID strategies (some tables use UUID, others use serial).
156
157JSON/JSONB:
158- Flag JSON columns that are frequently queried by nested keys (should be columns or tables).
159- Recommend JSONB over JSON (PostgreSQL) for queryable JSON.
160- Flag JSON columns without validation (schema-on-read risk).
161
162============================================================
163PHASE 6: QUERY PATTERN ANALYSIS
164============================================================
165
166N+1 QUERY DETECTION:
167- Scan for loops that execute queries per iteration.
168- Scan for ORM eager loading gaps (Prisma include, Django select_related, Rails includes).
169- For each N+1: file, line, the parent query, the child query, estimated query count.
170- Severity: Critical (hot path), High (common path), Medium (rare path).
171
172CONNECTION POOLING:
173- Check database connection configuration.
174- Verify connection pool is configured (min, max, idle timeout).
175- Flag if pool size matches expected concurrency.
176- Flag missing connection pool entirely (new connection per request).
177- Check for connection leaks (opened but never closed/returned to pool).
178
179TRANSACTION USAGE:
180- Verify multi-step writes use transactions.
181- Flag transactions that hold locks across external API calls or slow operations.
182- Check transaction isolation level (READ COMMITTED vs SERIALIZABLE).
183- Flag missing transactions where data consistency requires atomicity.
184
185QUERY PERFORMANCE:
186- Flag SELECT * on large tables (over-fetching).
187- Flag queries without LIMIT on list operations.
188- Flag subqueries that could be JOINs.
189- Flag LIKE '%term%' queries (cannot use index, recommend full-text search).
190
191============================================================
192PHASE 7: MIGRATION SAFETY (brief check -- defer to /migration-verify for full analysis)
193============================================================
194
195- Are all schema changes tracked in migrations?
196- Are migrations reversible (up + down)?
197- Any destructive migrations without data backup?
198- Any migrations that would lock large tables?
199
200
201============================================================
202SELF-HEALING VALIDATION (max 2 iterations)
203============================================================
204
205After producing the review, validate completeness and consistency:
206
2071. Verify all required output sections are present and non-empty.
2082. Verify every finding references a specific file or code location.
2093. Verify recommendations are actionable (not vague).
2104. Verify severity ratings are justified by evidence.
211
212IF VALIDATION FAILS:
213- Identify which sections are incomplete or lack specificity
214- Re-analyze the deficient areas
215- Repeat up to 2 iterations
216
217============================================================
218OUTPUT
219============================================================
220
221## Database Review Report
222
223### Database: {detected database}
224### ORM: {detected ORM}
225### Tables/Collections: {count}
226
227### Schema Health Score: {score}/100
228
229### Findings Summary
230
231| Category | Critical | High | Medium | Low |
232|---|---|---|---|---|
233| Normalization | {n} | {n} | {n} | {n} |
234| Indexes | {n} | {n} | {n} | {n} |
235| Constraints | {n} | {n} | {n} | {n} |
236| Data Types | {n} | {n} | {n} | {n} |
237| Query Patterns | {n} | {n} | {n} | {n} |
238| Connection Config | {n} | {n} | {n} | {n} |
239
240### Critical & High Findings
241
2421. **{DB-001}: {title}** -- Severity: {Critical/High}
243 - Table: `{table_name}`
244 - Location: `{file:line}`
245 - Issue: {description}
246 - Impact: {what goes wrong -- data loss, slow queries, inconsistency}
247 - Fix: {specific schema change or code change}
248
249### Index Coverage Map
250
251| Table | Queries Found | Indexed Queries | Unindexed Queries | Missing Indexes |
252|---|---|---|---|---|
253| {table} | {n} | {n} | {n} | {list columns} |
254
255### N+1 Query Report
256
257| Location | Parent Query | Child Query | Est. Queries | Fix |
258|---|---|---|---|---|
259| `{file:line}` | {parent} | {child} | {n} per request | {eager load / batch} |
260
261### Constraint Coverage
262
263| Table | NOT NULL | Foreign Keys | Unique | Check | Defaults |
264|---|---|---|---|---|---|
265| {table} | {coverage%} | {coverage%} | {coverage%} | {coverage%} | {coverage%} |
266
267### Recommendations (ranked by impact)
2681. {recommendation} -- fixes {issue}, effort {S/M/L}
2692. ...
270
271DO NOT:
272- Flag intentional denormalization without considering the read pattern tradeoff.
273- Recommend indexes on tables with < 1000 rows (full scan is fine).
274- Flag Firestore/MongoDB for missing foreign keys (different paradigm).
275- Recommend normalization changes without considering migration effort.
276- Ignore the application code -- schema review without query context is incomplete.
277
278NEXT STEPS:
279- "Run `/migration-verify` to validate pending migrations."
280- "Run `/perf` to profile actual query performance."
281- "Run `/security-review` to check for data exposure risks."
282- "Run `/iterate` to implement the recommended schema changes."
283
284
285============================================================
286SELF-EVOLUTION TELEMETRY
287============================================================
288
289After producing output, record execution metadata for the /evolve pipeline.
290
291Check if a project memory directory exists:
292- Look for the project path in `~/.claude/projects/`
293- If found, append to `skill-telemetry.md` in that memory directory
294
295Entry format:
296```
297### /database-review — {{YYYY-MM-DD}}
298- Outcome: {{SUCCESS | PARTIAL | FAILED}}
299- Self-healed: {{yes — what was healed | no}}
300- Iterations used: {{N}} / {{N max}}
301- Bottleneck: {{phase that struggled or "none"}}
302- Suggestion: {{one-line improvement idea for /evolve, or "none"}}
303```
304
305Only log if the memory directory exists. Skip silently if not found.
306Keep entries concise — /evolve will parse these for skill improvement signals.