Communitygithub.com

lguidolin/postgres-postgraphile-rls-e-sql

Use ao escrever PostgreSQL, config PostGraphile, políticas Row-Level Security, arquivos SQL de esquema, ou ao trabalhar no caminho de dados Browser→App→PostGraphile→Postgres. Palavras-chave: RLS, SECURITY DEFINER, search_path, pgSettings, grants, roles, limite de profundidade GraphQL, custo de consulta, statement_timeout, organização de arquivos SQL.

O que é postgres-postgraphile-rls-e-sql?

Este skill define a camada de dados para uma stack específica, implementando o princípio de defesa em profundidade com Row-Level Security (RLS) como barreira final e um único caminho legal de dados: Browser → Servidor App → PostGraphile → PostgreSQL. Ele é útil para desenvolvedores que trabalham com PostGraphile e PostgreSQL, garantindo que todas as consultas passem por um pipeline controlado, onde o contexto de sessão é transmitido apenas como cabeçalhos e a autorização é aplicada exclusivamente no banco de dados. O skill impõe regras rigorosas: RLS como camada de enforcement final, funções SECURITY DEFINER com search_path inline, ausência de valores como NULL (nunca string vazia), e limites de segurança GraphQL como depth, custo de consulta e statement_timeout. Ele também padroniza a organização do código SQL com um objeto por arquivo, estrutura de diretórios schema/object_type/name, e comentários inline, suportando plataformas como Claude Code, Cursor e Codex.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/lguidolin/agent-skills/tree/main/skills/postgres-postgraphile-rls-and-sql

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Postgres, PostGraphile, RLS e SQL

Visão Geral

Mecanismo da camada de dados para esta stack. Implementa defesa em profundidade (RLS como parede final) e o caminho de dados legal único. Específico da stack — não se aplica a projetos sem PostGraphile/Postgres.

O Caminho de Dados

Browser → Servidor App → PostGraphile → PostgreSQL. Exatamente um caminho legal.

  • O navegador nunca fala diretamente com GraphQL/BD; o app nunca consulta o BD diretamente para dados de aplicação.
  • O app passa contexto de sessão apenas como cabeçalhos (id do usuário, dica de org) — nenhuma lógica de autorização no app; o contexto é validado downstream, não confiado.
  • Um único caminho = um único lugar para aplicar contexto de auth, validação e RLS. Canais laterais são os buracos que burlam a imposição.

Regras de Segurança

  • RLS é a camada de enforcement final. Verificações na camada do app são UX; o banco de dados é a parede. Mesmo um bug nas camadas acima não pode vazar linhas de outro tenant.
  • Roles modelam estados reais de sessão — não-logado, logado-sem-org, logado-com-org, um role de conexão, um role de migração. Roles significam algo.
  • O role de conexão privilegiado nunca executa consultas de aplicação. Consultas do app são executadas sob um role restrito, sujeito a RLS.
  • Funções SECURITY DEFINER definem search_path inline em sua definição — toda vez, sem exceção.
  • Ausência é NULL, nunca string vazia. Sentinelas de string vazia são proibidos; omita o valor quando ausente.
  • GraphQL é uma superfície de DoS — limite-a. Aplique limites de profundidade de consulta e análise de custo/complexidade; rejeite consultas acima do orçamento. Limite o tamanho da paginação. Defina um statement_timeout no BD para roles de app. Desabilite introspecção em produção a menos que deliberadamente necessária.

Estilo SQL

  • Um objeto por arquivo — cada tabela, função, política, conjunto de grants em seu próprio arquivo.
  • Organizado em schema/object_type/name — diretório espelha a organização do banco de dados.
  • Ordem de inclusão é ordem de dependência; o manifesto de inclusão é o sumário da estrutura.
  • Documente inline. COMMENT ON vive no mesmo arquivo que o objeto — o que e por quê.
  • Aliases descritivos (singular do nome da tabela, não letras únicas); siga os idiomas do Postgres (current_* getters).
  • Tipos e roles voltados ao usuário são dados, não restrições hardcoded — tabelas de lookup com chave/rótulo/descrição, validados por FK, extensíveis sem mudanças no schema.

Referência Rápida

RegraVerificação
Nova função SECURITY DEFINERsearch_path definido inline?
Nova tabela com dados de tenantPolítica RLS + testes de negação (veja graphql-contract-testing)?
Valor ausenteNULL, não ''?
Nova superfície GraphQLLimite de profundidade/custo e limite de paginação?
Novo objetoArquivo próprio, include ordenado por dependência, COMMENT ON inline?

Justificativa completa: Artigos XIII, XIV, XVIII da constituição, agrupados em engineering-constitution/references/engineering-constitution.md. Migrações: zero-downtime-migrations. Testes de contrato: graphql-contract-testing.

Individual skills in this repo

This repo contains 18 individual skills — each has its own dedicated page.

lguidolin/change-hygiene-and-code-craft

Use when writing or refactoring code, structuring a commit or PR, or deciding whether to abstract duplication. Symptoms — mixing reorg with logic changes, a PR doing several things at once, a file growing large, the second copy of similar code, or unsure whether to DRY something up.

lguidolin/cloud-delivery-aks

Use when deploying to Kubernetes or Azure Kubernetes Service (AKS), configuring cloud secrets, setting up progressive rollout/canary, per-PR ephemeral environments, or k8s health probes. Keywords — Kubernetes, AKS, Key Vault, Argo Rollouts, Flagger, canary, blue-green, liveness, readiness, PodDisruptionBudget, HPA, rollback, GHCR.

lguidolin/commit-history-rewrite

Use when an existing repository has messy commit history that needs to conform to conventional commits before adopting release-please, or when intermediate WIP/fixup/merge commits need to be cleaned up.

lguidolin/conventional-commits-and-releases

Use when committing, writing a commit message, opening a PR that will be squash-merged, or configuring automated versioning/changelogs. Keywords — conventional commits, release-please, semver, feat/fix/chore, breaking change, changelog.

lguidolin/defense-in-depth-security

Use when handling untrusted input, secrets, authentication/authorization, or dependencies — or threat-modeling a new surface. Keywords — STRIDE, threat model, least privilege, secrets management, supply chain, dependency scanning, input validation, audit log, defense in depth.

lguidolin/designing-before-building

Use when starting a feature, fixing a non-trivial bug, or about to write implementation code — before any code exists. Symptoms you need this: "this is simple, I'll just code it", reaching for the editor before a design is approved, or an idea that hasn't been turned into a spec and plan.

lguidolin/engineering-constitution

Use when starting work in a project that follows the engineering constitution, orienting to its rules, or deciding which engineering practice applies to a task — spec writing, commits, testing, security, deploys, database, or UI work.

lguidolin/graphql-contract-testing

Use when writing a GraphQL query/mutation that the UI and a test will share, or building route/schema contract or smoke tests. Symptoms — copying a query into a test, a test asserting on query text, schema change that didn't break the UI build, or RLS/permission drift. Keywords — graphql-codegen, typed document, contract test, route smoke test.

lguidolin/init-repo-CI

Use when setting up a new repository with conventional commits, release-please, and CI automation, or when retrofitting an existing repository that lacks automated versioning and PR validation workflows.

lguidolin/interface-craft-and-accessibility

Use when building or styling UI — components, layouts, forms, design tokens — or making accessibility decisions. Keywords — a11y, WCAG, keyboard navigation, focus state, contrast, design system, minimalist UI, component reuse, ARIA, semantic HTML.

lguidolin/merge-gates-and-automation

Use when setting up or changing CI, pre-push hooks, or a task runner, or deciding what must pass before merge. Symptoms — tempted to put authoritative checks only in a local hook, skip CI, bypass with --no-verify, or unsure what gates a merge vs. runs locally.

lguidolin/observability-and-slos

Use when adding logging, metrics, tracing, health checks, SLOs, or alerting — or when building a service surface that needs to be operable and debuggable. Keywords — structured logs, OpenTelemetry, correlation id, RED metrics, liveness, readiness, SLI, SLO, error budget, alerting.

lguidolin/performance-and-scale

Use when working on hot paths, list endpoints, pagination, data-access in loops, or public interfaces/schemas. Symptoms — unbounded queries, N+1 access, no latency budget, optimizing without measuring, or changing an interface many consumers depend on. Keywords — pagination, N+1, Hyrum's Law, performance budget, bundle size.

lguidolin/recording-decisions

Use when a design or architecture decision has been made and needs to be captured — writing a decision record or ADR, updating a decision index, noting a deferred idea, or superseding a past decision. Keywords — ADR, decision record, rationale, rejected alternatives, dependency index.

lguidolin/resilience-and-deploy-safety

Use when planning a deploy, designing a rollback, or responding to an incident or writing a postmortem. Keywords — deploy safety, rollback, immutable artifact, progressive delivery, canary, blast radius, incident response, blameless postmortem, error budget.

lguidolin/ship-it

Use when the user wants to ship work — push, PR, archive decision records, merge, and clean up. Handles the full lifecycle from committing final changes through post-merge cleanup including converting specs/plans to compact decision records.

lguidolin/tests-as-a-control

Use when writing or modifying tests, when a test breaks during a refactor, or when testing permission/role rules. Symptoms — tempted to edit a test to make it pass, testing only the happy path, a deny-test that started passing, flaky tests, or unsure what to assert.

lguidolin/zero-downtime-migrations

Use when changing a database schema where data must survive the change — adding/removing/renaming columns, constraints, indexes, or backfilling. Symptoms — a destructive migration bundled with a code deploy, a NOT NULL column with a backfill, a table-locking UPDATE, or a rename. Keywords — expand/contract, parallel change, backfill, NOT VALID, CREATE INDEX CONCURRENTLY, graphile-migrate.

Habilidades Relacionadas