Skip to content

[PR #159 follow-up] Fix Supabase migration idempotency and preserve orders tracking#184

Merged
adm01-debug merged 1 commit into
mainfrom
codex/fix-high-priority-bugs-in-migration-files
May 23, 2026
Merged

[PR #159 follow-up] Fix Supabase migration idempotency and preserve orders tracking#184
adm01-debug merged 1 commit into
mainfrom
codex/fix-high-priority-bugs-in-migration-files

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

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

Motivation

  • Ensure the Supabase migration chain can be replayed in a clean environment without duplicate-object or missing-column failures.
  • Prevent irreversible data loss by preserving legacy orders.tracking_code when schema evolves.
  • Make object creation (tables/indexes/policies/triggers) idempotent so replays and partial rollouts tolerate existing schema.

Description

  • Added IF NOT EXISTS to CREATE TABLE/CREATE INDEX for public_token_failures, quote_approval_tokens, and kit_share_tokens and wrapped policy creation in guarded DO $$ ... IF NOT EXISTS ... $$ blocks against pg_policies to avoid duplicate-policy errors (files: 20260522113220_*, 20260522113314_*, 20260522114122_*).
  • Guarded trigger creation using pg_trigger existence checks and replaced unconditional policy creation with existence-checked DO $$ blocks for quote_approval_tokens and kit_share_tokens to prevent trigger/policy collisions on replay.
  • Made orders migration resilient by using DROP COLUMN IF EXISTS for total, performing a guarded rename total_amount -> total only when source exists and target does not, and preserving tracking data by backfilling tracking_code into tracking_number (without overwriting non-empty values) before dropping the legacy column (file: 20260522143654_*).
  • Guarded quote_templates legacy-column renames so each rename runs only when the legacy column exists and the target column is absent to avoid column already exists errors (file: 20260522145140_*).

Testing

  • Ran git diff --check and it completed with no whitespace or conflict marker issues.
  • Verified changed files are staged/committed via git status --short and commit succeeded (Fix migration replay idempotency and preserve orders tracking data).
  • Performed a static review of the SQL diffs to confirm idempotency guards and backfill logic were added as intended.
  • Did not run a live supabase db reset or full migration replay in this environment, so runtime migration replays remain to be validated in CI or a staging database.

Codex Task


Summary by cubic

Makes Supabase migrations safe to replay and preserves orders tracking data when moving from tracking_code to tracking_number. Prevents duplicate-object errors and protects existing data during rollouts.

  • Bug Fixes

    • Add IF NOT EXISTS to table/index creation in public_token_failures, quote_approval_tokens, and kit_share_tokens.
    • Guard policy creation via pg_policies checks and trigger creation via pg_trigger checks.
    • Harden orders migration: conditional drop/rename for total_amount -> total; backfill tracking_code into tracking_number without overwriting non-empty values; then drop the legacy column.
    • Guard quote_templates column renames to avoid “column already exists” errors.
  • Migration

    • No breaking changes; safe on existing databases and clean replays.
    • Recommended: run on staging or CI with a clean reset to verify end-to-end.

Written for commit 4896ff0. Summary will update on new commits. Review in cubic

Summary by CodeRabbit

  • Bug Fixes

    • Melhorada a confiabilidade das migrações de banco de dados ao implementar verificações de existência, evitando erros ao executar migrações repetidamente.
    • Sincronização de dados aprimorada durante atualizações de schema para preservar informações existentes sem conflitos.
  • Chores

    • Padronização da estrutura de dados em tabelas para melhor consistência no sistema.

Review Change Stack

Copilot AI review requested due to automatic review settings May 23, 2026 23:46
@vercel
Copy link
Copy Markdown

vercel Bot commented May 23, 2026

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

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment May 23, 2026 11:47pm

@supabase
Copy link
Copy Markdown

supabase Bot commented May 23, 2026

This pull request has been ignored for the connected project doufsxqlfjyuvxuezpln due to reaching the limit of concurrent preview branches.
Go to Project Integrations Settings ↗︎ if you wish to update this limit.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 23, 2026

Caution

Review failed

Pull request was closed or merged during review

Walkthrough

Cinco migrações Supabase SQL são refatoradas para idempotência. Novas tabelas de token e índices agora usam IF NOT EXISTS. Triggers e RLS policies são criados condicionalmente via blocos DO $$ verificando catálogo. Tabelas existentes (orders, quote_templates) têm operações DDL e sincronização de dados tornadas defensivas contra estados prévios inconsistentes.

Changes

Padronização de idempotência em migrações Supabase

Layer / File(s) Summary
Criação idempotente de novas tabelas
supabase/migrations/20260522113220_lote_a_01_public_token_failures.sql, supabase/migrations/20260522113314_lote_a_04_quote_approval_tokens.sql, supabase/migrations/20260522114122_lote_c_02_kit_share_tokens.sql
public_token_failures, quote_approval_tokens e kit_share_tokens agora usam CREATE TABLE IF NOT EXISTS, evitando falha ao reaplicar migração se tabela já existe.
Índices, triggers e RLS policies idempotentes
supabase/migrations/20260522113220_lote_a_01_public_token_failures.sql, supabase/migrations/20260522113314_lote_a_04_quote_approval_tokens.sql, supabase/migrations/20260522114122_lote_c_02_kit_share_tokens.sql
Índices usam CREATE INDEX IF NOT EXISTS. Triggers e RLS policies são criados via blocos DO $$ que consultam pg_trigger e pg_policies, criando objeto apenas se não existir previamente.
Reestruturação defensiva de schema em tabelas existentes
supabase/migrations/20260522143654_wave_3_2_a_orders_oficial_align_client_v2.sql, supabase/migrations/20260522145140_wave_3_3_c_1_oficial_quote_templates_unificado.sql
Tabela orders padroniza colunas com DROP COLUMN IF EXISTS, ADD COLUMN IF NOT EXISTS e sincroniza tracking_number a partir de tracking_code de forma condicional. Tabela quote_templates executa renomes de coluna (default_payment_termspayment_terms, etc) apenas se coluna origem existe e destino não existe.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Justificativa: O padrão de mudança é repetitivo e homogêneo (5 migrações seguindo o mesmo princípio de idempotência), reduzindo esforço. Porém, a migração orders exige verificação cuidadosa de lógica condicional de sincronização de dados e ordem de operações DDL para garantir integridade. Sem fluxos multi-componentes ou mudanças em APIs públicas, a revisão focará em: (1) validar que IF NOT EXISTS está em todos os CREATE statement; (2) conferir blocos DO $$ consultam catálogo correto; (3) examinar sincronização de tracking_number em orders para evitar perda de dados; (4) confirmar renomes condicionais em quote_templates tratam todos os cenários de estado.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título descreve com precisão os principais objetivos da PR: corrigir idempotência nas migrações Supabase e preservar rastreamento de pedidos.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-high-priority-bugs-in-migration-files

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

Copy link
Copy Markdown
Contributor

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

This PR hardens several Supabase SQL migrations so they can be replayed safely (idempotent creation of tables/indexes/policies/triggers) and attempts to preserve orders tracking data when migrating from tracking_code to tracking_number.

Changes:

  • Added IF NOT EXISTS / existence-guarded DO $$ ... $$ blocks around table/index/policy/trigger creation to prevent duplicate-object failures on migration replays.
  • Guarded quote_templates legacy column renames so they only run when the source column exists and the target does not.
  • Updated the orders alignment migration to be more replay-tolerant and to backfill tracking_code into tracking_number before dropping the legacy column.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
supabase/migrations/20260522145140_wave_3_3_c_1_oficial_quote_templates_unificado.sql Makes quote_templates column renames idempotent via guarded DO $$ blocks.
supabase/migrations/20260522143654_wave_3_2_a_orders_oficial_align_client_v2.sql Adds replay guards for orders column changes and backfills tracking data.
supabase/migrations/20260522114122_lote_c_02_kit_share_tokens.sql Makes kit_share_tokens table/index/policy/trigger creation idempotent.
supabase/migrations/20260522113314_lote_a_04_quote_approval_tokens.sql Makes quote_approval_tokens table/index/policy/trigger creation idempotent.
supabase/migrations/20260522113220_lote_a_01_public_token_failures.sql Makes public_token_failures table/index/policy creation idempotent.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +15 to +25
ALTER TABLE public.orders DROP COLUMN IF EXISTS total;
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema='public' AND table_name='orders' AND column_name='total_amount'
) AND NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema='public' AND table_name='orders' AND column_name='total'
) THEN
ALTER TABLE public.orders RENAME COLUMN total_amount TO total;
Comment on lines +52 to +56
UPDATE public.orders
SET tracking_number = COALESCE(NULLIF(tracking_number, ''), tracking_code)
WHERE tracking_code IS NOT NULL;

ALTER TABLE public.orders DROP COLUMN tracking_code;
@adm01-debug adm01-debug merged commit 0ffeda1 into main May 23, 2026
21 of 25 checks passed
@adm01-debug adm01-debug deleted the codex/fix-high-priority-bugs-in-migration-files branch May 23, 2026 23:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants