{"kind":"Skill","metadata":{"namespace":"community","name":"sql-code-review","version":"0.1.0"},"spec":{"description":"Universal SQL code review assistant that performs comprehensive security, maintainability, and code quality analysis across all SQL databases (MySQL, PostgreSQL, SQL Server, Oracle). Focuses on SQL injection prevention, access control, code standards, and anti-pattern detection. Complements SQL optimization prompt for complete development coverage.","files":{"SKILL.md":"---\nname: sql-code-review\ndescription: 'Universal SQL code review assistant that performs comprehensive security, maintainability, and code quality analysis across all SQL databases (MySQL, PostgreSQL, SQL Server, Oracle). Focuses on SQL injection prevention, access control, code standards, and anti-pattern detection. Complements SQL optimization prompt for complete development coverage.'\n---\n\n# SQL Code Review\n\nPerform a thorough SQL code review of ${selection} (or entire project if no selection) focusing on security, performance, maintainability, and database best practices.\n\n## 🔒 Security Analysis\n\n### SQL Injection Prevention\n```sql\n-- ❌ CRITICAL: SQL Injection vulnerability\nquery = \"SELECT * FROM users WHERE id = \" + userInput;\nquery = f\"DELETE FROM orders WHERE user_id = {user_id}\";\n\n-- ✅ SECURE: Parameterized queries\n-- PostgreSQL/MySQL\nPREPARE stmt FROM 'SELECT * FROM users WHERE id = ?';\nEXECUTE stmt USING @user_id;\n\n-- SQL Server\nEXEC sp_executesql N'SELECT * FROM users WHERE id = @id', N'@id INT', @id = @user_id;\n```\n\n### Access Control \u0026 Permissions\n- **Principle of Least Privilege**: Grant minimum required permissions\n- **Role-Based Access**: Use database roles instead of direct user permissions\n- **Schema Security**: Proper schema ownership and access controls\n- **Function/Procedure Security**: Review DEFINER vs INVOKER rights\n\n### Data Protection\n- **Sensitive Data Exposure**: Avoid SELECT * on tables with sensitive columns\n- **Audit Logging**: Ensure sensitive operations are logged\n- **Data Masking**: Use views or functions to mask sensitive data\n- **Encryption**: Verify encrypted storage for sensitive data\n\n## ⚡ Performance Optimization\n\n### Query Structure Analysis\n```sql\n-- ❌ BAD: Inefficient query patterns\nSELECT DISTINCT u.* \nFROM users u, orders o, products p\nWHERE u.id = o.user_id \nAND o.product_id = p.id\nAND YEAR(o.order_date) = 2024;\n\n-- ✅ GOOD: Optimized structure\nSELECT u.id, u.name, u.email\nFROM users u\nINNER JOIN orders o ON u.id = o.user_id\nWHERE o.order_date \u003e= '2024-01-01' \nAND o.order_date \u003c '2025-01-01';\n```\n\n### Index Strategy Review\n- **Missing Indexes**: Identify columns that need indexing\n- **Over-Indexing**: Find unused or redundant indexes\n- **Composite Indexes**: Multi-column indexes for complex queries\n- **Index Maintenance**: Check for fragmented or outdated indexes\n\n### Join Optimization\n- **Join Types**: Verify appropriate join types (INNER vs LEFT vs EXISTS)\n- **Join Order**: Optimize for smaller result sets first\n- **Cartesian Products**: Identify and fix missing join conditions\n- **Subquery vs JOIN**: Choose the most efficient approach\n\n### Aggregate and Window Functions\n```sql\n-- ❌ BAD: Inefficient aggregation\nSELECT user_id, \n       (SELECT COUNT(*) FROM orders o2 WHERE o2.user_id = o1.user_id) as order_count\nFROM orders o1\nGROUP BY user_id;\n\n-- ✅ GOOD: Efficient aggregation\nSELECT user_id, COUNT(*) as order_count\nFROM orders\nGROUP BY user_id;\n```\n\n## 🛠️ Code Quality \u0026 Maintainability\n\n### SQL Style \u0026 Formatting\n```sql\n-- ❌ BAD: Poor formatting and style\nselect u.id,u.name,o.total from users u left join orders o on u.id=o.user_id where u.status='active' and o.order_date\u003e='2024-01-01';\n\n-- ✅ GOOD: Clean, readable formatting\nSELECT u.id,\n       u.name,\n       o.total\nFROM users u\nLEFT JOIN orders o ON u.id = o.user_id\nWHERE u.status = 'active'\n  AND o.order_date \u003e= '2024-01-01';\n```\n\n### Naming Conventions\n- **Consistent Naming**: Tables, columns, constraints follow consistent patterns\n- **Descriptive Names**: Clear, meaningful names for database objects\n- **Reserved Words**: Avoid using database reserved words as identifiers\n- **Case Sensitivity**: Consistent case usage across schema\n\n### Schema Design Review\n- **Normalization**: Appropriate normalization level (avoid over/under-normalization)\n- **Data Types**: Optimal data type choices for storage and performance\n- **Constraints**: Proper use of PRIMARY KEY, FOREIGN KEY, CHECK, NOT NULL\n- **Default Values**: Appropriate default values for columns\n\n## 🗄️ Database-Specific Best Practices\n\n### PostgreSQL\n```sql\n-- Use JSONB for JSON data\nCREATE TABLE events (\n    id SERIAL PRIMARY KEY,\n    data JSONB NOT NULL,\n    created_at TIMESTAMPTZ DEFAULT NOW()\n);\n\n-- GIN index for JSONB queries\nCREATE INDEX idx_events_data ON events USING gin(data);\n\n-- Array types for multi-value columns\nCREATE TABLE tags (\n    post_id INT,\n    tag_names TEXT[]\n);\n```\n\n### MySQL\n```sql\n-- Use appropriate storage engines\nCREATE TABLE sessions (\n    id VARCHAR(128) PRIMARY KEY,\n    data TEXT,\n    expires TIMESTAMP\n) ENGINE=InnoDB;\n\n-- Optimize for InnoDB\nALTER TABLE large_table \nADD INDEX idx_covering (status, created_at, id);\n```\n\n### SQL Server\n```sql\n-- Use appropriate data types\nCREATE TABLE products (\n    id BIGINT IDENTITY(1,1) PRIMARY KEY,\n    name NVARCHAR(255) NOT NULL,\n    price DECIMAL(10,2) NOT NULL,\n    created_at DATETIME2 DEFAULT GETUTCDATE()\n);\n\n-- Columnstore indexes for analytics\nCREATE COLUMNSTORE INDEX idx_sales_cs ON sales;\n```\n\n### Oracle\n```sql\n-- Use sequences for auto-increment\nCREATE SEQUENCE user_id_seq START WITH 1 INCREMENT BY 1;\n\nCREATE TABLE users (\n    id NUMBER DEFAULT user_id_seq.NEXTVAL PRIMARY KEY,\n    name VARCHAR2(255) NOT NULL\n);\n```\n\n## 🧪 Testing \u0026 Validation\n\n### Data Integrity Checks\n```sql\n-- Verify referential integrity\nSELECT o.user_id \nFROM orders o \nLEFT JOIN users u ON o.user_id = u.id \nWHERE u.id IS NULL;\n\n-- Check for data consistency\nSELECT COUNT(*) as inconsistent_records\nFROM products \nWHERE price \u003c 0 OR stock_quantity \u003c 0;\n```\n\n### Performance Testing\n- **Execution Plans**: Review query execution plans\n- **Load Testing**: Test queries with realistic data volumes\n- **Stress Testing**: Verify performance under concurrent load\n- **Regression Testing**: Ensure optimizations don't break functionality\n\n## 📊 Common Anti-Patterns\n\n### N+1 Query Problem\n```sql\n-- ❌ BAD: N+1 queries in application code\nfor user in users:\n    orders = query(\"SELECT * FROM orders WHERE user_id = ?\", user.id)\n\n-- ✅ GOOD: Single optimized query\nSELECT u.*, o.*\nFROM users u\nLEFT JOIN orders o ON u.id = o.user_id;\n```\n\n### Overuse of DISTINCT\n```sql\n-- ❌ BAD: DISTINCT masking join issues\nSELECT DISTINCT u.name \nFROM users u, orders o \nWHERE u.id = o.user_id;\n\n-- ✅ GOOD: Proper join without DISTINCT\nSELECT u.name\nFROM users u\nINNER JOIN orders o ON u.id = o.user_id\nGROUP BY u.name;\n```\n\n### Function Misuse in WHERE Clauses\n```sql\n-- ❌ BAD: Functions prevent index usage\nSELECT * FROM orders \nWHERE YEAR(order_date) = 2024;\n\n-- ✅ GOOD: Range conditions use indexes\nSELECT * FROM orders \nWHERE order_date \u003e= '2024-01-01' \n  AND order_date \u003c '2025-01-01';\n```\n\n## 📋 SQL Review Checklist\n\n### Security\n- [ ] All user inputs are parameterized\n- [ ] No dynamic SQL construction with string concatenation\n- [ ] Appropriate access controls and permissions\n- [ ] Sensitive data is properly protected\n- [ ] SQL injection attack vectors are eliminated\n\n### Performance\n- [ ] Indexes exist for frequently queried columns\n- [ ] No unnecessary SELECT * statements\n- [ ] JOINs are optimized and use appropriate types\n- [ ] WHERE clauses are selective and use indexes\n- [ ] Subqueries are optimized or converted to JOINs\n\n### Code Quality\n- [ ] Consistent naming conventions\n- [ ] Proper formatting and indentation\n- [ ] Meaningful comments for complex logic\n- [ ] Appropriate data types are used\n- [ ] Error handling is implemented\n\n### Schema Design\n- [ ] Tables are properly normalized\n- [ ] Constraints enforce data integrity\n- [ ] Indexes support query patterns\n- [ ] Foreign key relationships are defined\n- [ ] Default values are appropriate\n\n## 🎯 Review Output Format\n\n### Issue Template\n```\n## [PRIORITY] [CATEGORY]: [Brief Description]\n\n**Location**: [Table/View/Procedure name and line number if applicable]\n**Issue**: [Detailed explanation of the problem]\n**Security Risk**: [If applicable - injection risk, data exposure, etc.]\n**Performance Impact**: [Query cost, execution time impact]\n**Recommendation**: [Specific fix with code example]\n\n**Before**:\n```sql\n-- Problematic SQL\n```\n\n**After**:\n```sql\n-- Improved SQL\n```\n\n**Expected Improvement**: [Performance gain, security benefit]\n```\n\n### Summary Assessment\n- **Security Score**: [1-10] - SQL injection protection, access controls\n- **Performance Score**: [1-10] - Query efficiency, index usage\n- **Maintainability Score**: [1-10] - Code quality, documentation\n- **Schema Quality Score**: [1-10] - Design patterns, normalization\n\n### Top 3 Priority Actions\n1. **[Critical Security Fix]**: Address SQL injection vulnerabilities\n2. **[Performance Optimization]**: Add missing indexes or optimize queries\n3. **[Code Quality]**: Improve naming conventions and documentation\n\nFocus on providing actionable, database-agnostic recommendations while highlighting platform-specific optimizations and best practices.\n"},"import":{"commit_sha":"541b7819d8c3545c6df122491af4fa1eae415779","imported_at":"2026-05-18T20:05:35Z","license_text":"MIT License\n\nCopyright GitHub, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.","owner":"github","repo":"github/awesome-copilot","source_url":"https://github.com/github/awesome-copilot/tree/541b7819d8c3545c6df122491af4fa1eae415779/plugins/database-data-management/skills/sql-code-review"}},"content_hash":[228,129,83,249,132,166,131,170,172,117,10,36,186,214,157,231,171,96,151,246,235,85,70,51,127,121,130,56,39,104,149,75],"trust_level":"unsigned","yanked":false}
