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