postgresql-code-review
作者: github
PostgreSQL 程式碼審查助手,涵蓋 JSONB、陣列、自訂型別、資料表設計及安全最佳實務。審查 JSONB 操作以確保索引效率、搭配 GIN 索引的陣列使用,以及正確的包含運算子。評估資料表設計,包括 ENUM 型別、用於不區分大小寫資料的 CITEXT、TIMESTAMPTZ 的使用,以及 CHECK 約束。識別函式最佳化、觸發器設計與擴充功能使用中的反模式。評估列層級安全性(RLS)實作、權限...
npx skills add https://github.com/github/awesome-copilot --skill postgresql-code-reviewPostgreSQL Code Review Assistant
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.
🎯 PostgreSQL-Specific Review Areas
JSONB Best Practices
-- ❌ BAD: Inefficient JSONB usage
SELECT * FROM orders WHERE data->>'status' = 'shipped'; -- No index support
-- ✅ GOOD: Indexable JSONB queries
CREATE INDEX idx_orders_status ON orders USING gin((data->'status'));
SELECT * FROM orders WHERE data @> '{"status": "shipped"}';
-- ❌ BAD: Deep nesting without consideration
UPDATE orders SET data = data || '{"shipping":{"tracking":{"number":"123"}}}';
-- ✅ GOOD: Structured JSONB with validation
ALTER TABLE orders ADD CONSTRAINT valid_status
CHECK (data->>'status' IN ('pending', 'shipped', 'delivered'));
Array Operations Review
-- ❌ BAD: Inefficient array operations
SELECT * FROM products WHERE 'electronics' = ANY(categories); -- No index
-- ✅ GOOD: GIN indexed array queries
CREATE INDEX idx_products_categories ON products USING gin(categories);
SELECT * FROM products WHERE categories @> ARRAY['electronics'];
-- ❌ BAD: Array concatenation in loops
-- This would be inefficient in a function/procedure
-- ✅ GOOD: Bulk array operations
UPDATE products SET categories = categories || ARRAY['new_category']
WHERE id IN (SELECT id FROM products WHERE condition);
PostgreSQL Schema Design Review
-- ❌ BAD: Not using PostgreSQL features
CREATE TABLE users (
id INTEGER,
email VARCHAR(255),
created_at TIMESTAMP
);
-- ✅ GOOD: PostgreSQL-optimized schema
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
email CITEXT UNIQUE NOT NULL, -- Case-insensitive email
created_at TIMESTAMPTZ DEFAULT NOW(),
metadata JSONB DEFAULT '{}',
CONSTRAINT valid_email CHECK (email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$')
);
-- Add JSONB GIN index for metadata queries
CREATE INDEX idx_users_metadata ON users USING gin(metadata);
Custom Types and Domains
-- ❌ BAD: Using generic types for specific data
CREATE TABLE transactions (
amount DECIMAL(10,2),
currency VARCHAR(3),
status VARCHAR(20)
);
-- ✅ GOOD: PostgreSQL custom types
CREATE TYPE currency_code AS ENUM ('USD', 'EUR', 'GBP', 'JPY');
CREATE TYPE transaction_status AS ENUM ('pending', 'completed', 'failed', 'cancelled');
CREATE DOMAIN positive_amount AS DECIMAL(10,2) CHECK (VALUE > 0);
CREATE TABLE transactions (
amount positive_amount NOT NULL,
currency currency_code NOT NULL,
status transaction_status DEFAULT 'pending'
);
🔍 PostgreSQL-Specific Anti-Patterns
Performance Anti-Patterns
- Avoiding PostgreSQL-specific indexes: Not using GIN/GiST for appropriate data types
- Misusing JSONB: Treating JSONB like a simple string field
- Ignoring array operators: Using inefficient array operations
- Poor partition key selection: Not leveraging PostgreSQL partitioning effectively
Schema Design Issues
- Not using ENUM types: Using VARCHAR for limited value sets
- Ignoring constraints: Missing CHECK constraints for data validation
- Wrong data types: Using VARCHAR instead of TEXT or CITEXT
- Missing JSONB structure: Unstructured JSONB without validation
Function and Trigger Issues
-- ❌ BAD: Inefficient trigger function
CREATE OR REPLACE FUNCTION update_modified_time()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW(); -- Should use TIMESTAMPTZ
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- ✅ GOOD: Optimized trigger function
CREATE OR REPLACE FUNCTION update_modified_time()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Set trigger to fire only when needed
CREATE TRIGGER update_modified_time_trigger
BEFORE UPDATE ON table_name
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION update_modified_time();
📊 PostgreSQL Extension Usage Review
Extension Best Practices
-- ✅ Check if extension exists before creating
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
CREATE EXTENSION IF NOT EXISTS "pg_trgm";
-- ✅ Use extensions appropriately
-- UUID generation
SELECT uuid_generate_v4();
-- Password hashing
SELECT crypt('password', gen_salt('bf'));
-- Fuzzy text matching
SELECT word_similarity('postgres', 'postgre');
🛡️ PostgreSQL Security Review
Row Level Security (RLS)
-- ✅ GOOD: Implementing RLS
ALTER TABLE sensitive_data ENABLE ROW LEVEL SECURITY;
CREATE POLICY user_data_policy ON sensitive_data
FOR ALL TO application_role
USING (user_id = current_setting('app.current_user_id')::INTEGER);
Privilege Management
-- ❌ BAD: Overly broad permissions
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO app_user;
-- ✅ GOOD: Granular permissions
GRANT SELECT, INSERT, UPDATE ON specific_table TO app_user;
GRANT USAGE ON SEQUENCE specific_table_id_seq TO app_user;
🎯 PostgreSQL Code Quality Checklist
Schema Design
- Using appropriate PostgreSQL data types (CITEXT, JSONB, arrays)
- Leveraging ENUM types for constrained values
- Implementing proper CHECK constraints
- Using TIMESTAMPTZ instead of TIMESTAMP
- Defining custom domains for reusable constraints
Performance Considerations
- Appropriate index types (GIN for JSONB/arrays, GiST for ranges)
- JSONB queries using containment operators (@>, ?)
- Array operations using PostgreSQL-specific operators
- Proper use of window functions and CTEs
- Efficient use of PostgreSQL-specific functions
PostgreSQL Features Utilization
- Using extensions where appropriate
- Implementing stored procedures in PL/pgSQL when beneficial
- Leveraging PostgreSQL's advanced SQL features
- Using PostgreSQL-specific optimization techniques
- Implementing proper error handling in functions
Security and Compliance
- Row Level Security (RLS) implementation where needed
- Proper role and privilege management
- Using PostgreSQL's built-in encryption functions
- Implementing audit trails with PostgreSQL features
📝 PostgreSQL-Specific Review Guidelines
- Data Type Optimization: Ensure PostgreSQL-specific types are used appropriately
- Index Strategy: Review index types and ensure PostgreSQL-specific indexes are utilized
- JSONB Structure: Validate JSONB schema design and query patterns
- Function Quality: Review PL/pgSQL functions for efficiency and best practices
- Extension Usage: Verify appropriate use of PostgreSQL extensions
- Performance Features: Check utilization of PostgreSQL's advanced features
- Security Implementation: Review PostgreSQL-specific security features
Focus on PostgreSQL's unique capabilities and ensure the code leverages what makes PostgreSQL special rather than treating it as a generic SQL database.
來自 github 的更多技能
console-rendering
github
在 Go 中使用基於結構體標籤的控制台渲染系統的說明
official
acquire-codebase-knowledge
github
當使用者明確要求對現有程式碼庫進行映射、文件化或入門引導時,使用此技能。觸發詞如「映射此程式碼庫」、「文件化…」等提示。
official
acreadiness-assess
github
Run the AgentRC readiness assessment on the current repository and produce a static HTML dashboard at reports/index.html. Wraps `npx github:microsoft/agentrc…
official
acreadiness-generate-instructions
github
透過 AgentRC 指令命令生成量身打造的 AI 代理指令檔案。產生 .github/copilot-instructions.md(預設,建議用於 VS Code 中的 Copilot…
official
acreadiness-policy
github
幫助使用者選取、撰寫或套用 AgentRC 政策。政策可透過停用不相關的檢查、覆寫影響/等級、設定…來自訂整備度評分。
official
add-educational-comments
github
為程式碼檔案添加教育性註解,將其轉化為有效的學習資源。根據三個可設定的知識層級(初學者、中級、進階)調整解釋深度與語氣。若未提供檔案,會自動請求提供,並以編號清單對應以便快速選取。僅透過教育性註解將檔案擴充最多125%(嚴格上限:400行新註解;超過1,000行的檔案上限為300行)。保留檔案編碼、縮排風格、語法正確性及……
official
adobe-illustrator-scripting
github
使用 ExtendScript (JavaScript/JSX) 編寫、除錯及最佳化 Adobe Illustrator 自動化腳本。適用於建立或修改操控…的腳本時。
official
agent-governance
github
宣告式政策、意圖分類與稽核軌跡,用於控制AI代理工具存取與行為。可組合的治理政策定義允許/封鎖的工具、內容過濾器、速率限制與核准要求——以配置而非程式碼形式儲存。語意意圖分類在工具執行前,透過基於模式的訊號偵測危險提示(資料外洩、權限提升、提示注入)。工具層級治理裝飾器在函式層級強制執行政策……
official