data-supabase-patterns
Skill6 starsChanged 25 days agoMITView on GitHub
Melhores práticas de Postgres e Supabase — indexação, RLS performática, connection pooling, schema design, locking e diagnóstico com EXPLAIN. Use ao escrever queries SQL, criar migrations, desenhar schema, implementar políticas RLS, otimizar queries lentas ou investigar timeouts e problemas de conexão em projetos Supabase/Postgres.
In this repository124 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- accessibilitySkill
- ai-ml-data-scienceSkill
- ai-ml-timeseriesSkill
- brand-platformSkill
- brand-researchSkill
- brand-rolloutSkill
- brand-trackingSkill
- brand-verbal-identitySkill
- brand-visual-systemSkill
- copy-humanizeSkill
- core-web-vitalsSkill
- data-analytics-engineeringSkill
- data-lake-platformSkill
- data-sql-optimizationSkill
- deep-researchSkill
- dev-api-designSkill
- dev-database-patternsSkill
- dev-debuggingSkill
- dev-defuddleSkill
- dev-error-handlingSkill
- dev-git-workflowSkill
- dev-security-patternsSkill
- dev-technical-writingSkill
- dev-testing-strategySkill
- dev-typescript-patternsSkill
- doc-to-markdownSkill
- finance-bookkeepingSkill
- finance-cash-flowSkill
- finance-receivables-payablesSkill
- finance-reportingSkill
- finance-tax-complianceSkill
- instagram-dm-flowsSkill
- instagram-publishingSkill
- instagram-strategySkill
- legal-clause-librarySkill
- legal-compliance-lgpdSkill
- legal-contract-draftingSkill
- legal-contract-lifecycleSkill
- legal-researchSkill
- linkedin-publishingSkill
- linkedin-strategySkill
- negotiationSkill
- nextjs-react-best-practicesSkill
- presentation-designSkill
- pricingSkill
- sala-de-controleSkill
- sales-deck-productionSkill
- sales-discovery-intakeSkill
- sales-enablementSkill
- sales-pricing-paybackSkill
- sales-proposal-copySkill
- sales-proposal-planningSkill
- security-audit-methodSkill
- security-incident-responseSkill
- security-privacy-data-mapSkill
- security-threat-modelingSkill
- seo-ahrefsSkill
- seo-auditSkill
- seo-backlinksSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 60
2.2 — Transaction mode does not support session state: no prepared statements at protocol level (disable in the client, e.g.
- Very specific: line 87
3.5 — Avoid joins inside policies;: prefer a SECURITY DEFINER helper function (e.g.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Supabase / Postgres Patterns
Skill de banco de dados destilada do guia oficial supabase-postgres-best-practices (8 categorias priorizadas por impacto). Usada por dev-data-engineer, sites-data (schema, migrations, RLS) e dev-bi (queries analíticas), com dev-qa/sites-qa em review de migrations. Segue o protocolo de segurança da squad: snapshot → dry-run → apply → smoke-test.
1. Query Performance (CRITICAL)
1.1 — Index every column used in WHERE, JOIN, and ORDER BY of hot queries. Missing indexes are the #1 cause of slow queries.
-- ❌ seq scan on 1M rows
SELECT * FROM orders WHERE customer_id = $1;
-- ✅
CREATE INDEX idx_orders_customer_id ON orders (customer_id);1.2 — Composite indexes: equality columns first, then range/sort.
-- query: WHERE status = 'paid' AND created_at > now() - interval '30 days'
CREATE INDEX idx_orders_status_created ON orders (status, created_at);1.3 — Partial indexes for skewed data (e.g., only 2% of rows are pending):
CREATE INDEX idx_orders_pending ON orders (created_at) WHERE status = 'pending';1.4 — Never wrap an indexed column in a function — it disables the index. Index the expression instead:
-- ❌ WHERE lower(email) = $1 (index on email unused)
CREATE INDEX idx_users_email_lower ON users (lower(email)); -- ✅1.5 — Covering indexes (INCLUDE) for index-only scans on hot read paths.
1.6 — Keyset pagination, not OFFSET, for deep pages:
-- ❌ OFFSET 100000 scans and discards 100k rows
-- ✅ WHERE (created_at, id) < ($last_created_at, $last_id) ORDER BY created_at DESC, id DESC LIMIT 201.7 — SELECT only needed columns — SELECT * breaks index-only scans and inflates payloads (especially over PostgREST).
1.8 — Always EXPLAIN (ANALYZE, BUFFERS) before and after optimizing. Look for Seq Scan on large tables, misestimated rows, and high buffer reads.
2. Connection Management (CRITICAL)
2.1 — Serverless/edge functions MUST use the transaction-mode pooler (Supavisor, port 6543), never direct connections — each lambda invocation would otherwise hold a Postgres backend.
2.2 — Transaction mode does not support session state: no prepared statements at protocol level (disable in the client, e.g. pgbouncer=true / prepare: false), no SET without LOCAL, no advisory locks held across transactions.
2.3 — Long-lived servers: direct connection (5432) with a small app-side pool. Rule of thumb: pool size ≈ cores × 2–4, not hundreds.
2.4 — Set statement timeouts (statement_timeout, idle_in_transaction_session_timeout) so runaway queries and abandoned transactions don't exhaust the pool.
3. Security & RLS (CRITICAL)
3.1 — Enable RLS on every table in exposed schemas (public is exposed via PostgREST):
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;3.2 — Wrap auth functions in a subselect so they're evaluated once per query, not per row — the single biggest RLS performance fix:
-- ❌ auth.uid() re-evaluated for every row
CREATE POLICY p ON documents USING (auth.uid() = user_id);
-- ✅ initPlan: evaluated once
CREATE POLICY p ON documents USING ((SELECT auth.uid()) = user_id);3.3 — Index the columns referenced by policies (user_id, org_id, team_id). RLS turns every query into a filtered query.
3.4 — Specify the role in policies (TO authenticated) so anon traffic short-circuits without evaluating the expression.
3.5 — Avoid joins inside policies; prefer a SECURITY DEFINER helper function (e.g. private.user_org_ids()) with a stable result, and keep it in a non-exposed schema.
3.6 — Functions: pin search_path (SET search_path = '', use schema-qualified names) and grant EXECUTE deliberately. Never put SECURITY DEFINER functions in exposed schemas without need.
3.7 — Never string-interpolate SQL — parameterized queries only, including inside plpgsql (format() + %I/%L when dynamic SQL is unavoidable).
4. Schema Design (HIGH)
bigint GENERATED ALWAYS AS IDENTITY(ou UUIDv7) para PKs; evite UUIDv4 como PK clusterizada de tabelas gigantes (index bloat / cache locality).textem vez devarchar(n)+CHECKconstraint quando precisar de limite — mesmo desempenho, migração mais fácil.timestamptzsempre, nuncatimestamp.- FKs sempre indexadas — Postgres não cria índice em FK automaticamente; deletes/updates no pai fazem seq scan no filho sem ele.
NOT NULL+ defaults em tudo que a regra de negócio permitir; constraints são documentação executável.- Enum de domínio: prefira tabela de lookup ou
CHECKaCREATE TYPE enumquando os valores mudam com frequência.
5. Migrations seguras (HIGH)
5.1 — Zero-downtime playbook:
-- Adicionar coluna NOT NULL em tabela grande: 3 passos
ALTER TABLE t ADD COLUMN c text; -- 1. nullable, instantâneo
UPDATE t SET c = '...' WHERE c IS NULL; -- 2. backfill em batches
ALTER TABLE t ALTER COLUMN c SET NOT NULL; -- 3. depois de validado5.2 — CREATE INDEX CONCURRENTLY em tabelas em produção (fora de transaction block).
5.3 — Constraints em duas fases: ADD CONSTRAINT ... NOT VALID seguido de VALIDATE CONSTRAINT — valida sem lock longo.
5.4 — Nunca DROP COLUMN/RENAME no mesmo deploy que o código — expand/contract: adicionar novo → migrar código → remover velho.
6. Concurrency & Locking (MEDIUM-HIGH)
- Transações curtas. Nunca segure uma transação aberta durante chamadas de rede/API externa.
SELECT ... FOR UPDATE SKIP LOCKEDpara filas e workers concorrentes.- Ordene updates multi-linha por chave estável para evitar deadlocks entre transações concorrentes.
lock_timeoutcurto em DDL (SET LOCAL lock_timeout = '2s') — melhor falhar e repetir do que enfileirar atrás de um lock e travar o sistema.
7. Diagnóstico (quando algo está lento)
pg_stat_statements— top queries portotal_exec_timeemean_exec_time.EXPLAIN (ANALYZE, BUFFERS)na query suspeita.pg_stat_activity— conexõesidle in transaction, queries longas, waits.pg_stat_user_indexes— índices nunca usados (candidatos a drop: cada índice custa em escrita).- Em Supabase: Query Performance report + Index Advisor no dashboard;
supabase inspect dbna CLI.
Checklist de review (migrations/queries)
- Toda tabela nova em schema exposto tem RLS habilitada + policies com
(SELECT auth.uid()) - Colunas de policy e FKs indexadas
- Índices criados com
CONCURRENTLYem produção - Sem
SELECT *em código de aplicação - Paginação keyset em listagens profundas
timestamptz,text, identity PKs- Plano testado com
EXPLAIN (ANALYZE, BUFFERS)antes do merge
Adaptado de supabase/agent-skills → supabase-postgres-best-practices (skills.sh) — 2026-08-26. O SKILL.md fonte é um índice de ~50 regras em arquivos de referência; as regras acima foram destiladas das categorias oficiais (query/conn/security/schema/lock/data/monitor) complementadas com conhecimento próprio dos mesmos tópicos.
Skill relacionada
- Otimização SQL genérica (EXPLAIN profundo, indexing, HA, multi-plataforma) → ../data-sql-optimization/SKILL.md.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

