From aa0c6a42e5e15dcd90f90a79fd60db9e06b83f95 Mon Sep 17 00:00:00 2001 From: Andrew Farries Date: Wed, 10 Jul 2024 11:52:51 +0100 Subject: [PATCH] Ignore duplicate inferred migrations having the same timestamp (#369) Remove all but the last inferred migration in a group of inferred migrations that occur at the same timestamp with the same migration SQL. Such inferred migrations are typically part of a batched transaction for which we want to ignore all but the effect of the last statement in the batch. --- pkg/state/state.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/pkg/state/state.go b/pkg/state/state.go index 2a9e26b2..c008a7a5 100644 --- a/pkg/state/state.go +++ b/pkg/state/state.go @@ -311,6 +311,15 @@ BEGIN RETURN; END IF; + -- Remove any duplicate inferred migrations with the same timestamp for this + -- schema. We assume such migrations are multi-statement batched migrations + -- and we are only interested in the last one in the batch. + DELETE FROM %[1]s.migrations + WHERE schema = schemaname + AND created_at = current_timestamp + AND migration_type = 'inferred' + AND migration->'operations'->0->'sql'->>'up' = current_query(); + -- Someone did a schema change without pgroll, include it in the history SELECT INTO migration_id pg_catalog.format('sql_%%s',pg_catalog.substr(pg_catalog.md5(pg_catalog.random()::text), 0, 15)); @@ -399,7 +408,7 @@ func (s *State) Init(ctx context.Context) error { } // Perform pgroll state initialization - _, err = tx.ExecContext(ctx, fmt.Sprintf(sqlInit, pq.QuoteIdentifier(s.schema))) + _, err = tx.ExecContext(ctx, fmt.Sprintf(sqlInit, pq.QuoteIdentifier(s.schema), pq.QuoteLiteral(s.schema))) if err != nil { return err }