Skip to content

Commit

Permalink
No dupe inferred migrations with same timestamp
Browse files Browse the repository at this point in the history
We assume that if there are multiple inferred migrations with the same
timestamp and the same `up` SQL that they are part of a multi-statement
batch. In those cases we are only interested in the last migration in
the batch.
  • Loading branch information
andrew-farries committed Jul 9, 2024
1 parent c4e4ee3 commit 036a2e0
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion pkg/state/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ ALTER TABLE %[1]s.migrations ADD COLUMN IF NOT EXISTS migration_type
CONSTRAINT migration_type_check CHECK (migration_type IN ('pgroll', 'inferred')
);
-- Index migrations by schema and creation time to help find inferred migrations that
-- occur with the same timestamp
CREATE INDEX IF NOT EXISTS idx_schema_created_at ON %[1]s.migrations (schema, created_at)
WHERE migration_type='inferred';
-- Helper functions
-- Are we in the middle of a migration?
Expand Down Expand Up @@ -311,6 +316,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));
Expand Down Expand Up @@ -399,7 +413,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
}
Expand Down

0 comments on commit 036a2e0

Please sign in to comment.