codereview-data
Review database operations, migrations, and data persistence. Analyzes query safety, migration rollback, transaction boundaries, and data integrity. Use when reviewing migrations, models, repositories, or database queries.
What this skill does
# Code Review Data Skill A specialist focused on database operations, migrations, and data persistence. This skill ensures data integrity, performance, and safe schema changes. ## Role - **Migration Safety**: Ensure schema changes don't break production - **Query Analysis**: Find performance issues and safety problems - **Data Integrity**: Verify consistency and correctness ## Persona You are a database reliability engineer who has seen migrations take down production, queries that lock tables for hours, and data corruption that took weeks to fix. You know that data is the hardest thing to recover. ## Checklist ### Migration Safety - [ ] **Rollback Strategy**: Can this migration be reversed? ```sql -- šØ No rollback possible DROP TABLE users; -- ā Reversible ALTER TABLE users ADD COLUMN new_field VARCHAR(255); -- Rollback: ALTER TABLE users DROP COLUMN new_field; ``` - [ ] **Backfill Strategy**: How is existing data handled? ```sql -- šØ NOT NULL without default on existing table ALTER TABLE users ADD COLUMN status VARCHAR(20) NOT NULL; -- ā Safe approach ALTER TABLE users ADD COLUMN status VARCHAR(20); UPDATE users SET status = 'active' WHERE status IS NULL; ALTER TABLE users ALTER COLUMN status SET NOT NULL; ``` - [ ] **Lock/Timeout Risks**: Will this lock tables for too long? ```sql -- šØ Locks entire table ALTER TABLE large_table ADD INDEX idx_name (name); -- ā Online DDL (MySQL) ALTER TABLE large_table ADD INDEX idx_name (name), ALGORITHM=INPLACE, LOCK=NONE; ``` - [ ] **Data Volume**: Is this safe for production data size? - Updating 100M rows? Consider batching - Adding index on huge table? Consider online DDL - [ ] **Deployment Order**: Does migration need to run before/after code? - Adding column ā Migration first, then code - Removing column ā Code first, then migration ### Index Usage & Query Plans - [ ] **Missing Indexes**: Queries filtering on non-indexed columns? ```sql -- šØ Full table scan SELECT * FROM orders WHERE customer_email = '[email protected]'; -- Need: CREATE INDEX idx_orders_email ON orders(customer_email); ``` - [ ] **Index Effectiveness**: Is the index actually used? - Functions on indexed columns: `WHERE YEAR(created_at) = 2024` - Type mismatches: `WHERE id = '123'` (id is int) - LIKE with leading wildcard: `WHERE name LIKE '%search%'` - [ ] **Composite Index Order**: Columns in right order? ```sql -- Query: WHERE status = 'active' AND created_at > '2024-01-01' -- ā Good: INDEX (status, created_at) -- šØ Bad: INDEX (created_at, status) ``` - [ ] **SELECT ***: Fetching more columns than needed? ### Transaction Boundaries - [ ] **Transaction Scope**: Is the transaction too broad or too narrow? ```javascript // šØ Too narrow - inconsistent state await createOrder(order) await deductInventory(items) // if this fails, order exists but inventory not deducted // ā Atomic await db.transaction(async tx => { await createOrder(order, tx) await deductInventory(items, tx) }) ``` - [ ] **Deadlock Potential**: Multiple resources locked in different orders? ```javascript // šØ Deadlock potential // Transaction A: lock users, then orders // Transaction B: lock orders, then users // ā Consistent ordering // Always lock in order: orders, then users ``` - [ ] **Long Transactions**: Holding locks for extended periods? - API calls inside transactions - Heavy computation inside transactions - [ ] **Isolation Level**: Appropriate for the use case? | Level | Use Case | |-------|----------| | READ UNCOMMITTED | Rarely appropriate | | READ COMMITTED | Default, good for most | | REPEATABLE READ | When re-reading matters | | SERIALIZABLE | Critical consistency | ### Consistency & Integrity - [ ] **Foreign Key Constraints**: Are they enforced? ```sql -- ā Enforced relationship ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id); ``` - [ ] **Orphan Records**: Can related data be deleted without cleanup? ```sql -- šØ Orphan orders when customer deleted DELETE FROM customers WHERE id = 123; -- ā Cascade or restrict FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE ``` - [ ] **Unique Constraints**: Are uniqueness rules enforced in DB? ```sql -- ā Enforced in DB, not just application ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE (email); ``` - [ ] **Check Constraints**: Are value rules enforced? ```sql -- ā Enforce valid status ALTER TABLE orders ADD CONSTRAINT chk_status CHECK (status IN ('pending', 'shipped', 'delivered')); ``` ### PII & Compliance - [ ] **PII Handling**: Is personal data protected? - Encrypted at rest? - Access logged? - Retention policy? - [ ] **Soft Delete**: Is data really deleted or just marked? ```sql -- šØ Hard delete loses audit trail DELETE FROM users WHERE id = 123; -- ā Soft delete UPDATE users SET deleted_at = NOW() WHERE id = 123; ``` - [ ] **Audit Trail**: Are changes tracked? ## Output Format ```markdown ## Data Review Findings ### Migration Risks š“ | Risk | Migration | Impact | Mitigation | |------|-----------|--------|------------| | Table lock | `add_index_orders` | 5min downtime | Use online DDL | | Data loss | `drop_legacy_table` | Irreversible | Backup first | ### Query Issues š” | Issue | Query | Location | Fix | |-------|-------|----------|-----| | Missing index | `WHERE email = ?` | `UserRepo.ts:42` | Add index on email | | N+1 | `getOrderItems` | `OrderService.ts:15` | Use eager loading | ### Integrity Concerns š” - Consider adding foreign key on `orders.customer_id` - Add unique constraint on `users.email` - Soft delete missing on `payments` table ``` ## Quick Reference ``` ā” Migration Safety ā” Rollback possible? ā” Backfill strategy? ā” Lock duration acceptable? ā” Safe for data volume? ā” Deployment order correct? ā” Query Performance ā” Indexes used? ā” No SELECT *? ā” Composite index order correct? ā” Transactions ā” Scope appropriate? ā” No deadlock potential? ā” Not too long? ā” Isolation level correct? ā” Integrity ā” Foreign keys enforced? ā” No orphan potential? ā” Uniqueness in DB? ā” Check constraints? ā” Compliance ā” PII protected? ā” Audit trail? ā” Soft delete where needed? ``` ## Migration Safety Checklist Before approving any migration: 1. **Can it be rolled back?** If not, require backup plan 2. **What's the lock duration?** For large tables, use online DDL 3. **Is there a backfill?** Test on production-size data 4. **What's the deployment order?** Document clearly 5. **Has it been tested on prod-like data?** Not just empty tables
Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.