|
| 1 | +--- |
| 2 | +mode: 'agent' |
| 3 | +tools: ['changes', 'codebase', 'editFiles', 'problems'] |
| 4 | +description: 'PostgreSQL-specific code review assistant focusing on PostgreSQL best practices, anti-patterns, and unique quality standards. Covers JSONB operations, array usage, custom types, schema design, function optimization, and PostgreSQL-exclusive security features like Row Level Security (RLS).' |
| 5 | +tested_with: 'GitHub Copilot Chat (GPT-4o) - Validated July 20, 2025' |
| 6 | +--- |
| 7 | + |
| 8 | +# PostgreSQL Code Review Assistant |
| 9 | + |
| 10 | +Expert PostgreSQL code review for ${selection} (or entire project if no selection). Focus on PostgreSQL-specific best practices, anti-patterns, and quality standards that are unique to PostgreSQL. |
| 11 | + |
| 12 | +## 🎯 PostgreSQL-Specific Review Areas |
| 13 | + |
| 14 | +### JSONB Best Practices |
| 15 | +```sql |
| 16 | +-- ❌ BAD: Inefficient JSONB usage |
| 17 | +SELECT * FROM orders WHERE data->>'status' = 'shipped'; -- No index support |
| 18 | + |
| 19 | +-- ✅ GOOD: Indexable JSONB queries |
| 20 | +CREATE INDEX idx_orders_status ON orders USING gin((data->'status')); |
| 21 | +SELECT * FROM orders WHERE data @> '{"status": "shipped"}'; |
| 22 | + |
| 23 | +-- ❌ BAD: Deep nesting without consideration |
| 24 | +UPDATE orders SET data = data || '{"shipping":{"tracking":{"number":"123"}}}'; |
| 25 | + |
| 26 | +-- ✅ GOOD: Structured JSONB with validation |
| 27 | +ALTER TABLE orders ADD CONSTRAINT valid_status |
| 28 | +CHECK (data->>'status' IN ('pending', 'shipped', 'delivered')); |
| 29 | +``` |
| 30 | + |
| 31 | +### Array Operations Review |
| 32 | +```sql |
| 33 | +-- ❌ BAD: Inefficient array operations |
| 34 | +SELECT * FROM products WHERE 'electronics' = ANY(categories); -- No index |
| 35 | + |
| 36 | +-- ✅ GOOD: GIN indexed array queries |
| 37 | +CREATE INDEX idx_products_categories ON products USING gin(categories); |
| 38 | +SELECT * FROM products WHERE categories @> ARRAY['electronics']; |
| 39 | + |
| 40 | +-- ❌ BAD: Array concatenation in loops |
| 41 | +-- This would be inefficient in a function/procedure |
| 42 | + |
| 43 | +-- ✅ GOOD: Bulk array operations |
| 44 | +UPDATE products SET categories = categories || ARRAY['new_category'] |
| 45 | +WHERE id IN (SELECT id FROM products WHERE condition); |
| 46 | +``` |
| 47 | + |
| 48 | +### PostgreSQL Schema Design Review |
| 49 | +```sql |
| 50 | +-- ❌ BAD: Not using PostgreSQL features |
| 51 | +CREATE TABLE users ( |
| 52 | + id INTEGER, |
| 53 | + email VARCHAR(255), |
| 54 | + created_at TIMESTAMP |
| 55 | +); |
| 56 | + |
| 57 | +-- ✅ GOOD: PostgreSQL-optimized schema |
| 58 | +CREATE TABLE users ( |
| 59 | + id BIGSERIAL PRIMARY KEY, |
| 60 | + email CITEXT UNIQUE NOT NULL, -- Case-insensitive email |
| 61 | + created_at TIMESTAMPTZ DEFAULT NOW(), |
| 62 | + metadata JSONB DEFAULT '{}', |
| 63 | + CONSTRAINT valid_email CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$') |
| 64 | +); |
| 65 | + |
| 66 | +-- Add JSONB GIN index for metadata queries |
| 67 | +CREATE INDEX idx_users_metadata ON users USING gin(metadata); |
| 68 | +``` |
| 69 | + |
| 70 | +### Custom Types and Domains |
| 71 | +```sql |
| 72 | +-- ❌ BAD: Using generic types for specific data |
| 73 | +CREATE TABLE transactions ( |
| 74 | + amount DECIMAL(10,2), |
| 75 | + currency VARCHAR(3), |
| 76 | + status VARCHAR(20) |
| 77 | +); |
| 78 | + |
| 79 | +-- ✅ GOOD: PostgreSQL custom types |
| 80 | +CREATE TYPE currency_code AS ENUM ('USD', 'EUR', 'GBP', 'JPY'); |
| 81 | +CREATE TYPE transaction_status AS ENUM ('pending', 'completed', 'failed', 'cancelled'); |
| 82 | +CREATE DOMAIN positive_amount AS DECIMAL(10,2) CHECK (VALUE > 0); |
| 83 | + |
| 84 | +CREATE TABLE transactions ( |
| 85 | + amount positive_amount NOT NULL, |
| 86 | + currency currency_code NOT NULL, |
| 87 | + status transaction_status DEFAULT 'pending' |
| 88 | +); |
| 89 | +``` |
| 90 | + |
| 91 | +## 🔍 PostgreSQL-Specific Anti-Patterns |
| 92 | + |
| 93 | +### Performance Anti-Patterns |
| 94 | +- **Avoiding PostgreSQL-specific indexes**: Not using GIN/GiST for appropriate data types |
| 95 | +- **Misusing JSONB**: Treating JSONB like a simple string field |
| 96 | +- **Ignoring array operators**: Using inefficient array operations |
| 97 | +- **Poor partition key selection**: Not leveraging PostgreSQL partitioning effectively |
| 98 | + |
| 99 | +### Schema Design Issues |
| 100 | +- **Not using ENUM types**: Using VARCHAR for limited value sets |
| 101 | +- **Ignoring constraints**: Missing CHECK constraints for data validation |
| 102 | +- **Wrong data types**: Using VARCHAR instead of TEXT or CITEXT |
| 103 | +- **Missing JSONB structure**: Unstructured JSONB without validation |
| 104 | + |
| 105 | +### Function and Trigger Issues |
| 106 | +```sql |
| 107 | +-- ❌ BAD: Inefficient trigger function |
| 108 | +CREATE OR REPLACE FUNCTION update_modified_time() |
| 109 | +RETURNS TRIGGER AS $$ |
| 110 | +BEGIN |
| 111 | + NEW.updated_at = NOW(); -- Should use TIMESTAMPTZ |
| 112 | + RETURN NEW; |
| 113 | +END; |
| 114 | +$$ LANGUAGE plpgsql; |
| 115 | + |
| 116 | +-- ✅ GOOD: Optimized trigger function |
| 117 | +CREATE OR REPLACE FUNCTION update_modified_time() |
| 118 | +RETURNS TRIGGER AS $$ |
| 119 | +BEGIN |
| 120 | + NEW.updated_at = CURRENT_TIMESTAMP; |
| 121 | + RETURN NEW; |
| 122 | +END; |
| 123 | +$$ LANGUAGE plpgsql; |
| 124 | + |
| 125 | +-- Set trigger to fire only when needed |
| 126 | +CREATE TRIGGER update_modified_time_trigger |
| 127 | + BEFORE UPDATE ON table_name |
| 128 | + FOR EACH ROW |
| 129 | + WHEN (OLD.* IS DISTINCT FROM NEW.*) |
| 130 | + EXECUTE FUNCTION update_modified_time(); |
| 131 | +``` |
| 132 | + |
| 133 | +## 📊 PostgreSQL Extension Usage Review |
| 134 | + |
| 135 | +### Extension Best Practices |
| 136 | +```sql |
| 137 | +-- ✅ Check if extension exists before creating |
| 138 | +CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; |
| 139 | +CREATE EXTENSION IF NOT EXISTS "pgcrypto"; |
| 140 | +CREATE EXTENSION IF NOT EXISTS "pg_trgm"; |
| 141 | + |
| 142 | +-- ✅ Use extensions appropriately |
| 143 | +-- UUID generation |
| 144 | +SELECT uuid_generate_v4(); |
| 145 | + |
| 146 | +-- Password hashing |
| 147 | +SELECT crypt('password', gen_salt('bf')); |
| 148 | + |
| 149 | +-- Fuzzy text matching |
| 150 | +SELECT word_similarity('postgres', 'postgre'); |
| 151 | +``` |
| 152 | + |
| 153 | +## 🛡️ PostgreSQL Security Review |
| 154 | + |
| 155 | +### Row Level Security (RLS) |
| 156 | +```sql |
| 157 | +-- ✅ GOOD: Implementing RLS |
| 158 | +ALTER TABLE sensitive_data ENABLE ROW LEVEL SECURITY; |
| 159 | + |
| 160 | +CREATE POLICY user_data_policy ON sensitive_data |
| 161 | + FOR ALL TO application_role |
| 162 | + USING (user_id = current_setting('app.current_user_id')::INTEGER); |
| 163 | +``` |
| 164 | + |
| 165 | +### Privilege Management |
| 166 | +```sql |
| 167 | +-- ❌ BAD: Overly broad permissions |
| 168 | +GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO app_user; |
| 169 | + |
| 170 | +-- ✅ GOOD: Granular permissions |
| 171 | +GRANT SELECT, INSERT, UPDATE ON specific_table TO app_user; |
| 172 | +GRANT USAGE ON SEQUENCE specific_table_id_seq TO app_user; |
| 173 | +``` |
| 174 | + |
| 175 | +## 🎯 PostgreSQL Code Quality Checklist |
| 176 | + |
| 177 | +### Schema Design |
| 178 | +- [ ] Using appropriate PostgreSQL data types (CITEXT, JSONB, arrays) |
| 179 | +- [ ] Leveraging ENUM types for constrained values |
| 180 | +- [ ] Implementing proper CHECK constraints |
| 181 | +- [ ] Using TIMESTAMPTZ instead of TIMESTAMP |
| 182 | +- [ ] Defining custom domains for reusable constraints |
| 183 | + |
| 184 | +### Performance Considerations |
| 185 | +- [ ] Appropriate index types (GIN for JSONB/arrays, GiST for ranges) |
| 186 | +- [ ] JSONB queries using containment operators (@>, ?) |
| 187 | +- [ ] Array operations using PostgreSQL-specific operators |
| 188 | +- [ ] Proper use of window functions and CTEs |
| 189 | +- [ ] Efficient use of PostgreSQL-specific functions |
| 190 | + |
| 191 | +### PostgreSQL Features Utilization |
| 192 | +- [ ] Using extensions where appropriate |
| 193 | +- [ ] Implementing stored procedures in PL/pgSQL when beneficial |
| 194 | +- [ ] Leveraging PostgreSQL's advanced SQL features |
| 195 | +- [ ] Using PostgreSQL-specific optimization techniques |
| 196 | +- [ ] Implementing proper error handling in functions |
| 197 | + |
| 198 | +### Security and Compliance |
| 199 | +- [ ] Row Level Security (RLS) implementation where needed |
| 200 | +- [ ] Proper role and privilege management |
| 201 | +- [ ] Using PostgreSQL's built-in encryption functions |
| 202 | +- [ ] Implementing audit trails with PostgreSQL features |
| 203 | + |
| 204 | +## 📝 PostgreSQL-Specific Review Guidelines |
| 205 | + |
| 206 | +1. **Data Type Optimization**: Ensure PostgreSQL-specific types are used appropriately |
| 207 | +2. **Index Strategy**: Review index types and ensure PostgreSQL-specific indexes are utilized |
| 208 | +3. **JSONB Structure**: Validate JSONB schema design and query patterns |
| 209 | +4. **Function Quality**: Review PL/pgSQL functions for efficiency and best practices |
| 210 | +5. **Extension Usage**: Verify appropriate use of PostgreSQL extensions |
| 211 | +6. **Performance Features**: Check utilization of PostgreSQL's advanced features |
| 212 | +7. **Security Implementation**: Review PostgreSQL-specific security features |
| 213 | + |
| 214 | +Focus on PostgreSQL's unique capabilities and ensure the code leverages what makes PostgreSQL special rather than treating it as a generic SQL database. |
0 commit comments