fix(db): corrige 2 migrations pending que travavam Supabase Preview CI#204
Conversation
Problema: Supabase Preview CI falhava com "MIGRATIONS: FAILED — 2 PENDING" em qualquer branch baseado em main. Causa raiz: 1. `20260514000001_fix_policy_idempotency_and_security.sql` tentava criar políticas em tabelas que não existem no banco de produção atual (product_novelties, companies, company_contacts, contact_phones, contact_emails, company_addresses). Resultado: SQL error "relation X does not exist" → migration FAILED. 2. `20260514112057_edge_function_secrets_callers_hardening.sql` tinha timestamp divergente do registro no banco (DB: 20260514112149 vs arquivo: 20260514112057). O Supabase via versionamento por timestamp, então tratava o arquivo como migration distinta → sempre "PENDING". Fix: 1. Envolve cada bloco de `20260514000001` em `DO $$ BEGIN IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = '...') THEN ... END IF; END $$` — aplica o que existir, pula o que não existir. Migração aplicada em prod via MCP (ADR 0006). 2. Renomeia `20260514112057` → `20260514112149` para alinhar timestamp do arquivo com o registro na schema_migrations de prod. https://claude.ai/code/session_01XZaQkYaicuFwEvo4oMk32H
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
WalkthroughTrês migrações Supabase refatoradas para robustez: deleção de gamificação, setup RLS multi-tenant e políticas adicionais passam a usar blocos ChangesRobustez e Idempotência de Migrações
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
Updates to Preview Branch (claude/fix-chat-freeze-jfEXO) ↗︎
Tasks are run on every commit but only new migration files are pushed.
❌ Branch Error • Thu, 14 May 2026 20:35:00 UTC View logs for this Workflow Run ↗︎. |
…cation The migration did a bare DELETE FROM feature_flags and system_settings without checking whether those tables exist, causing MIGRATIONS_FAILED on every Supabase Preview branch that runs migrations from scratch. Wraps both DELETEs in DO $$ BEGIN ... EXCEPTION WHEN undefined_table END $$. https://claude.ai/code/session_01WcZw7BgEJPoKKTsfrQaMfh
The migration references public.organizations in FK constraints and policies. On a fresh Supabase Preview Branch that replays all migrations from scratch, organizations doesn't exist at this point in the sequence. Wrapping the entire file in DO $outer$ with an early RETURN skips it cleanly when the prerequisite table is absent. https://claude.ai/code/session_01WcZw7BgEJPoKKTsfrQaMfh
There was a problem hiding this comment.
💡 Codex Review
This file says it is a snapshot of a migration already applied via MCP, and the repo docs note that MCP apply_migration records the version in supabase_migrations.schema_migrations; renaming it from 20260514112057... to 20260514112149... leaves any database that already recorded 20260514112057 with a migration version that no longer exists locally, while the new 20260514112149 appears pending. In those environments migration-history checks or pushes will see divergent history (or re-run the same DDL under a new version), so keep the original timestamped filename and fix ordering with a new follow-up migration if needed.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| WHERE table_schema = 'public' AND table_name = 'organizations' | ||
| ) THEN | ||
| RAISE NOTICE 'Migration 20250103_02_rls_organizations skipped: public.organizations does not exist yet.'; | ||
| RETURN; |
There was a problem hiding this comment.
Preserve artifacts required by later migrations
When a fresh preview replay reaches this file, public.organizations is still not created until 20260317194959_..., so this RETURN records the migration as applied without creating public.user_is_org_member or adding products.organization_id. Later migrations still depend on those artifacts (for example 20250103_07_complete_catalog_structure.sql creates policies referencing products.organization_id and public.user_is_org_member, and 20260513000004... unconditionally alters that function), so the preview CI will fail later with missing column/function instead of being fixed. The migration should not be skipped permanently unless the required artifacts are created elsewhere before those downstream references.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pull request overview
Este PR ajusta migrations do Supabase para eliminar o estado “PENDING/FAILED” no Supabase Preview CI, alinhando o histórico do repositório ao que já foi aplicado em produção e tornando algumas migrations mais tolerantes a variações de schema.
Changes:
- Renomeia a migration de hardening dos chamadores de edge functions para alinhar o timestamp com
schema_migrationse adiciona helper para ler secrets do Vault. - Torna a migration de correção de policies idempotente/segura em bancos onde certas tabelas não existem (guards por existência).
- Adiciona guards para evitar falhas em migrations legadas (RLS orgs / remoção de gamificação) quando tabelas ainda não existem.
Reviewed changes
Copilot reviewed 3 out of 4 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| supabase/migrations/20260514112149_edge_function_secrets_callers_hardening.sql | Snapshot que cria helper de Vault + atualiza chamadores SQL (trigger/RPC/cron) para autenticação por header. |
| supabase/migrations/20260514000001_fix_policy_idempotency_and_security.sql | Guards por existência de tabela para evitar falhas ao ajustar policies em schemas divergentes. |
| supabase/migrations/20250103_02_rls_organizations.sql | Envelopa a migration em DO block com early-exit quando public.organizations não existe. |
| supabase/migrations/20250103_01_remove_gamification.sql | Protege deletes em tabelas possivelmente inexistentes via tratamento de undefined_table. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| AND user_id = auth.uid() | ||
| ); | ||
| END; | ||
| $fn$ LANGUAGE plpgsql SECURITY DEFINER STABLE; |
There was a problem hiding this comment.
1 issue found across 4 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="supabase/migrations/20250103_02_rls_organizations.sql">
<violation number="1" location="supabase/migrations/20250103_02_rls_organizations.sql:19">
P1: The early `RETURN` can permanently skip this migration, leaving required function/RLS objects unapplied and causing later migrations that reference `user_is_org_member` to fail.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.
| WHERE table_schema = 'public' AND table_name = 'organizations' | ||
| ) THEN | ||
| RAISE NOTICE 'Migration 20250103_02_rls_organizations skipped: public.organizations does not exist yet.'; | ||
| RETURN; |
There was a problem hiding this comment.
P1: The early RETURN can permanently skip this migration, leaving required function/RLS objects unapplied and causing later migrations that reference user_is_org_member to fail.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At supabase/migrations/20250103_02_rls_organizations.sql, line 19:
<comment>The early `RETURN` can permanently skip this migration, leaving required function/RLS objects unapplied and causing later migrations that reference `user_is_org_member` to fail.</comment>
<file context>
@@ -3,484 +3,426 @@
+ WHERE table_schema = 'public' AND table_name = 'organizations'
+ ) THEN
+ RAISE NOTICE 'Migration 20250103_02_rls_organizations skipped: public.organizations does not exist yet.';
+ RETURN;
+ END IF;
+
</file context>
Problema
Supabase Preview CI falhava com "MIGRATIONS: FAILED — 2 PENDING" em qualquer branch baseado em
main, travando sessões de agente.Causa raiz
1.
20260514000001_fix_policy_idempotency_and_security.sql— tabelas inexistentesA migration tentava criar políticas RLS em tabelas que não existem no banco de produção atual (
product_novelties,companies,company_contacts,contact_phones,contact_emails,company_addresses). O banco de produção foi construído a partir das migrations canônicas de março/2026 em diante, e essas tabelas do schema Lovable original nunca foram criadas nele.Resultado: erro
relation "X" does not exist→ migration FAILED → Preview CI trava.2.
20260514112057_edge_function_secrets_callers_hardening.sql— timestamp divergenteO arquivo no git tinha timestamp
20260514112057mas o banco de produção registrou a migration como20260514112149(aplicada via MCP com timestamp ligeiramente diferente). O Supabase usa o timestamp como chave primária emschema_migrations, então tratava o arquivo git como uma migration nova e distinta → sempre "PENDING".Fix
20260514000001: Cada bloco SQL agora é protegido porDO $$ BEGIN IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = '...') THEN ... END IF; END $$. A migration aplica o que existir e pula o que não existir. Aplicada em produção via MCP (ADR 0006) — agora consta emschema_migrations.20260514112057→20260514112149: Arquivo renomeado para alinhar o timestamp do git com o registro emschema_migrationsde produção. Supabase Preview CI passa a reconhecer a migration como já aplicada.Resultado esperado
Após merge, qualquer branch baseado em
mainterá as 2 migrations alinhadas com o banco de produção — zero migrations "pending" → Preview CI verde.https://claude.ai/code/session_01XZaQkYaicuFwEvo4oMk32H
Generated by Claude Code
Summary by cubic
Corrige as migrations que deixavam o Supabase Preview CI com “2 PENDING” e torna a limpeza de gamificação e a RLS de organizações seguras em bancos sem essas tabelas. Resultado: Preview CI verde em branches baseadas em
maine em execuções do zero.20260514000001_fix_policy_idempotency_and_security.sql: envolve cada operação emDO $$ ... IF EXISTS (...) ... $$, evitandorelation does not existe ajustando políticas RLS.20250103_02_rls_organizations.sql: envolve a migration inteira emDO $outer$com guard parapublic.organizations; aplica RLS/policies só quando a tabela existir, evitando falhas em previews “from scratch”.20260514112057_edge_function_secrets_callers_hardening.sqlpara20260514112149_edge_function_secrets_callers_hardening.sqlpara alinhar comschema_migrationse eliminar o “pending” falso.20250103_01_remove_gamification.sql: protegeDELETEemfeature_flagsesystem_settingscomDO $$ ... EXCEPTION WHEN undefined_table THEN NULL; END $$.Written for commit 65989a5. Summary will update on new commits.
Summary by CodeRabbit
Notas de Lançamento
Bug Fixes
Chores