Skip to content

fix(db): corrige 2 migrations pending que travavam Supabase Preview CI#204

Merged
adm01-debug merged 3 commits into
mainfrom
claude/fix-chat-freeze-jfEXO
May 14, 2026
Merged

fix(db): corrige 2 migrations pending que travavam Supabase Preview CI#204
adm01-debug merged 3 commits into
mainfrom
claude/fix-chat-freeze-jfEXO

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented May 14, 2026

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 inexistentes

A 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 divergente

O arquivo no git tinha timestamp 20260514112057 mas o banco de produção registrou a migration como 20260514112149 (aplicada via MCP com timestamp ligeiramente diferente). O Supabase usa o timestamp como chave primária em schema_migrations, então tratava o arquivo git como uma migration nova e distinta → sempre "PENDING".

Fix

  • 20260514000001: Cada bloco SQL agora é protegido por DO $$ 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 em schema_migrations.

  • 2026051411205720260514112149: Arquivo renomeado para alinhar o timestamp do git com o registro em schema_migrations de produção. Supabase Preview CI passa a reconhecer a migration como já aplicada.

Resultado esperado

Após merge, qualquer branch baseado em main terá 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 main e em execuções do zero.

  • Bug Fixes
    • 20260514000001_fix_policy_idempotency_and_security.sql: envolve cada operação em DO $$ ... IF EXISTS (...) ... $$, evitando relation does not exist e ajustando políticas RLS.
    • 20250103_02_rls_organizations.sql: envolve a migration inteira em DO $outer$ com guard para public.organizations; aplica RLS/policies só quando a tabela existir, evitando falhas em previews “from scratch”.
    • Renomeia 20260514112057_edge_function_secrets_callers_hardening.sql para 20260514112149_edge_function_secrets_callers_hardening.sql para alinhar com schema_migrations e eliminar o “pending” falso.
    • 20250103_01_remove_gamification.sql: protege DELETE em feature_flags e system_settings com DO $$ ... 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

    • Corrigida remoção de recursos de gamificação para evitar falhas em ambientes sem dependências iniciais.
  • Chores

    • Melhorias de robustez e segurança nas verificações de integridade do banco de dados durante inicializações.
    • Aprimoramentos nas políticas de acesso para garantir operações mais seguras e previsíveis.

Review Change Stack

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
@vercel
Copy link
Copy Markdown

vercel Bot commented May 14, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
promo-gifts Error Error May 14, 2026 8:34pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c40bde1a-ad4f-4955-b670-e63ffe101ffb

📥 Commits

Reviewing files that changed from the base of the PR and between dc00e46 and 65989a5.

📒 Files selected for processing (4)
  • supabase/migrations/20250103_01_remove_gamification.sql
  • supabase/migrations/20250103_02_rls_organizations.sql
  • supabase/migrations/20260514000001_fix_policy_idempotency_and_security.sql
  • supabase/migrations/20260514112149_edge_function_secrets_callers_hardening.sql

Walkthrough

Três migrações Supabase refatoradas para robustez: deleção de gamificação, setup RLS multi-tenant e políticas adicionais passam a usar blocos DO com verificação de existência de tabelas, evitando falhas em ambientes parciais e garantindo idempotência.

Changes

Robustez e Idempotência de Migrações

Layer / File(s) Summary
Deleção Condicional de Entradas de Gamificação
supabase/migrations/20250103_01_remove_gamification.sql
Operações DELETE contra feature_flags e system_settings passam de execução direta para blocos anônimos DO com tratamento de exceção undefined_table, permitindo que a migração execute sem falhar se as tabelas não existirem.
Setup Multi-tenant com RLS e Guardas de Tabela
supabase/migrations/20250103_02_rls_organizations.sql
Toda migração RLS envolve-se em wrapper DO $outer$ que verifica existência de public.organizations; se presente, adiciona organization_id com FK/cascata, cria função user_is_org_member(), habilita RLS e aplica políticas por organização, membro e role; se ausente, emite NOTICE e retorna sem alterações.
Políticas de RLS Idempotentes para Tabelas Adicionais
supabase/migrations/20260514000001_fix_policy_idempotency_and_security.sql
Políticas RLS em product_novelties, tabelas de CRM (companies, company_contacts, contact_phones, contact_emails, company_addresses) e função org_has_any_members() para organization_members passam a ser criadas/removidas apenas se as tabelas existirem no public, usando DO $$ + IF EXISTS (pg_tables).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/fix-chat-freeze-jfEXO

Comment @coderabbitai help to get the list of available commands and usage tips.

@supabase
Copy link
Copy Markdown

supabase Bot commented May 14, 2026

Updates to Preview Branch (claude/fix-chat-freeze-jfEXO) ↗︎

Deployments Status Updated
Database Thu, 14 May 2026 20:34:54 UTC
Services Thu, 14 May 2026 20:34:54 UTC
APIs Thu, 14 May 2026 20:34:54 UTC

Tasks are run on every commit but only new migration files are pushed.
Close and reopen this PR if you want to apply changes from existing seed or migration files.

Tasks Status Updated
Configurations Thu, 14 May 2026 20:34:55 UTC
Migrations Thu, 14 May 2026 20:35:00 UTC
Seeding ⏸️ Thu, 14 May 2026 20:34:48 UTC
Edge Functions ⏸️ Thu, 14 May 2026 20:34:48 UTC

❌ Branch Error • Thu, 14 May 2026 20:35:00 UTC

ERROR: duplicate key value violates unique constraint "schema_migrations_pkey" (SQLSTATE 23505)
Key (version)=(20250103) already exists.
At statement: 1
INSERT INTO supabase_migrations.schema_migrations(version, name, statements) VALUES($1, $2, $3)

View logs for this Workflow Run ↗︎.
Learn more about Supabase for Git ↗︎.

…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
@adm01-debug adm01-debug marked this pull request as ready for review May 14, 2026 20:45
Copilot AI review requested due to automatic review settings May 14, 2026 20:45
@adm01-debug adm01-debug merged commit 0a5fbe2 into main May 14, 2026
16 of 20 checks passed
@adm01-debug adm01-debug deleted the claude/fix-chat-freeze-jfEXO branch May 14, 2026 20:45
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

-- ORIGEM: Aplicado via MCP `apply_migration` em 2026-05-14 11:20 UTC.

P2 Badge Keep applied migration version unchanged

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;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_migrations e 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;
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot May 14, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Fix with Cubic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants