Postgres Patterns

affaan-m/ECC/pi/core/skills/postgres-patterns

作者 affaan-mef648e01899ba3e8dc6371642deaaf64b4477775無授權條款275K 個星標收錄於 2026年10月9日更新於 2026年10月9日儲存庫4 天前更新

PostgreSQL database patterns for query optimization, schema design, indexing, and security. Based on Supabase best practices. Use when designing PostgreSQL schemas, indexes, or RLS policies, or when a query is too slow.

AI 產生的概覽

PostgreSQL 查詢最佳化、結構設計、索引與資料列層級安全模式的參考指南。

功能
提供 PostgreSQL 最佳實務的快速參考,涵蓋索引選擇、資料型別選擇、常見查詢模式、反模式偵測查詢以及設定範本。內含複合索引、涵蓋索引、部分索引、RLS 原則、UPSERT、游標分頁和佇列處理的 SQL 片段。也指向相關的 database-reviewer 代理,以進行更深入的審查工作流程。
適用情境
適用於撰寫 SQL 查詢或移轉、設計 PostgreSQL 結構或索引、排解慢速查詢、實作資料列層級安全,或設定連線集區時。
執行需求
無需指令碼或執行階段相依性,僅為純說明性參考。部分引用的查詢假設目標資料庫中已啟用 pg_stat_statements 等擴充功能。

PostgreSQL Patterns

Quick reference for PostgreSQL best practices. For detailed guidance, use the database-reviewer agent.

When to Activate

  • Writing SQL queries or migrations
  • Designing database schemas
  • Troubleshooting slow queries
  • Implementing Row Level Security
  • Setting up connection pooling

Quick Reference

Index Cheat Sheet

Query PatternIndex TypeExample
WHERE col = valueB-tree (default)CREATE INDEX idx ON t (col)
WHERE col > valueB-treeCREATE INDEX idx ON t (col)
WHERE a = x AND b > yCompositeCREATE INDEX idx ON t (a, b)
WHERE jsonb @> '{}'GINCREATE INDEX idx ON t USING gin (col)
WHERE tsv @@ queryGINCREATE INDEX idx ON t USING gin (col)
Time-series rangesBRINCREATE INDEX idx ON t USING brin (col)

Data Type Quick Reference

Use CaseCorrect TypeAvoid
IDsbigintint, random UUID
Stringstextvarchar(255)
Timestampstimestamptztimestamp
Moneynumeric(10,2)float
Flagsbooleanvarchar, int

Common Patterns

Composite Index Order:

sql
-- Equality columns first, then range columnsCREATE INDEX idx ON orders (status, created_at);-- Works for: WHERE status = 'pending' AND created_at > '2024-01-01'

Covering Index:

sql
CREATE INDEX idx ON users (email) INCLUDE (name, created_at);-- Avoids table lookup for SELECT email, name, created_at

Partial Index:

sql
CREATE INDEX idx ON users (email) WHERE deleted_at IS NULL;-- Smaller index, only includes active users

RLS Policy (Optimized):

sql
CREATE POLICY policy ON orders  USING ((SELECT auth.uid()) = user_id);  -- Wrap in SELECT!

UPSERT:

sql
INSERT INTO settings (user_id, key, value)VALUES (123, 'theme', 'dark')ON CONFLICT (user_id, key)DO UPDATE SET value = EXCLUDED.value;

Cursor Pagination:

sql
SELECT * FROM products WHERE id > $last_id ORDER BY id LIMIT 20;-- O(1) vs OFFSET which is O(n)

Queue Processing:

sql
UPDATE jobs SET status = 'processing'WHERE id = (  SELECT id FROM jobs WHERE status = 'pending'  ORDER BY created_at LIMIT 1  FOR UPDATE SKIP LOCKED) RETURNING *;

Anti-Pattern Detection

sql
-- Find unindexed foreign keysSELECT conrelid::regclass, a.attnameFROM pg_constraint cJOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey)WHERE c.contype = 'f'  AND NOT EXISTS (    SELECT 1 FROM pg_index i    WHERE i.indrelid = c.conrelid AND a.attnum = ANY(i.indkey)  );
-- Find slow queriesSELECT query, mean_exec_time, callsFROM pg_stat_statementsWHERE mean_exec_time > 100ORDER BY mean_exec_time DESC;
-- Check table bloatSELECT relname, n_dead_tup, last_vacuumFROM pg_stat_user_tablesWHERE n_dead_tup > 1000ORDER BY n_dead_tup DESC;

Configuration Template

sql
-- Connection limits (adjust for RAM)ALTER SYSTEM SET max_connections = 100;ALTER SYSTEM SET work_mem = '8MB';
-- TimeoutsALTER SYSTEM SET idle_in_transaction_session_timeout = '30s';ALTER SYSTEM SET statement_timeout = '30s';
-- MonitoringCREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- Security defaultsREVOKE ALL ON SCHEMA public FROM public;
SELECT pg_reload_conf();

Related

  • Agent: database-reviewer - Full database review workflow
  • Skill: clickhouse-io - ClickHouse analytics patterns
  • Skill: backend-patterns - API and backend patterns

Based on Supabase Agent Skills (credit: Supabase team) (MIT License)

來源與署名

來源:affaan-m/ECC位於pi/core/skills/postgres-patterns提交ef648e0

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架