AgentSkillsCN

postgres-best-practices

Supabase提供的Postgres性能优化和最佳实践。当编写SQL、设计模式或优化Prisma查询时,可使用此功能。

SKILL.md
--- frontmatter
name: postgres-best-practices
description: Postgres performance optimization and best practices from Supabase. Use when writing SQL, designing schemas, or optimizing Prisma queries.

Postgres Best Practices (Supabase)

Guidelines for high-performance and secure Postgres usage, specifically optimized for Supabase environments.

1. Query Performance

  • Indexes: Always index columns used in WHERE and JOIN clauses.
  • Index Types: Use B-tree for most cases, GIN for JSONB/Full-text, and Partial Indexes for filtered queries.
  • Covering Indexes: Use the INCLUDE clause to avoid table lookups for common projection columns.

2. Schema Design

  • Data Types: Choose the most compact data type (e.g., int4 instead of int8 if range allows).
  • Foreign Keys: Always index foreign key columns to speed up joins and deletions.
  • Naming: Use lowercase identifiers for maximum compatibility with various drivers and tools.

3. Connection Management

  • Pooling: Use connection pooling for all application connections to handle high concurrency.
  • Timeouts: Configure idle connection timeouts to prevent resource exhaustion.

4. Security & RLS

  • Principle of Least Privilege: Grant only necessary permissions to database roles.
  • Row Level Security (RLS): Enable RLS for multi-tenant data isolation.
  • Policy Optimization: Ensure RLS policies are performant by using indexed columns in policy conditions.

5. Data Access Patterns

  • Batching: Use batch INSERT or COPY for bulk data operations.
  • N+1 Queries: Use joins or batch loading (Prisma handles this via include or select) to eliminate N+1 issues.
  • Pagination: Prefer cursor-based pagination over OFFSET for large datasets.

6. Advanced Features

  • JSONB: Use JSONB for unstructured data and create GIN indexes for efficient querying.
  • Full-Text Search: Use tsvector and tsquery for robust search capabilities.