Skip to content

Commit ae1ec5d

Browse files
committed
fix(migrate): roll back the whole migration when any step fails
A schema migration that failed partway left the database half migrated. Atlas ran each statement on its own connection with autocommit, and the function scripts, schema changes and view scripts each committed separately. In mission-control#3688 the NULLS NOT DISTINCT index failed on Postgres 14 after the config_items cost columns were dropped and the dependent views removed, so the old pod still serving traffic failed with column "cost_total_30d" does not exist. RunMigrations now runs the function scripts, PostgREST role grants, Atlas schema changes, view scripts and migration_logs writes in one transaction, and schema.Apply runs Atlas on that transaction. A failure rolls everything back. The optional role GRANT runs in a savepoint so its failure stays non-fatal. The error message now reports the number of planned changes instead of claiming they were applied. Closes #2148
1 parent 7b21932 commit ae1ec5d

2 files changed

Lines changed: 64 additions & 82 deletions

File tree

‎migrate/migrate.go‎

Lines changed: 45 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -54,30 +54,47 @@ func RunMigrations(pool *sql.DB, config api.Config) error {
5454
return fmt.Errorf("failed to get executable scripts: %w", err)
5555
}
5656

57+
// Run every step in one transaction, so a failure anywhere leaves the database as it was.
58+
tx, err := pool.Begin()
59+
if err != nil {
60+
return err
61+
}
62+
defer func() { _ = tx.Rollback() }()
63+
64+
// SQL uses the configured role names, not just the default PostgREST roles.
65+
if _, err := tx.Exec("SELECT set_config('duty.postgrest_api_role', $1, true), set_config('duty.postgrest_anon_role', $2, true)", config.Postgrest.DBRole, config.Postgrest.AnonDBRole); err != nil {
66+
return fmt.Errorf("failed to set PostgREST roles for migrations: %w", err)
67+
}
68+
5769
l.V(3).Infof("Running %d scripts (functions)", len(allFunctions))
58-
// Do not mark these scripts complete until their dependent views exist again.
59-
// If schema or view migration fails, the next run must repeat the drops and rebuilds.
60-
if err := runScripts(pool, allFunctions, nil, config); err != nil {
70+
if err := runScripts(tx, allFunctions); err != nil {
6171
return fmt.Errorf("failed to run scripts: %w", err)
6272
}
6373

6474
l.V(3).Infof("Granting roles to current user")
6575
// Grant postgrest roles in ./functions/postgrest.sql to the current user
66-
if err := grantPostgrestRolesToCurrentUser(pool, config); err != nil {
76+
if err := grantPostgrestRolesToCurrentUser(tx, config); err != nil {
6777
return oops.Wrapf(err, "failed to grant postgrest roles")
6878
}
6979

7080
l.V(3).Infof("Applying schema migrations")
71-
if err := schema.Apply(context.TODO(), config.ConnectionString); err != nil {
81+
if err := schema.Apply(context.TODO(), tx, config.ConnectionString); err != nil {
7282
return fmt.Errorf("failed to apply schema migrations: %w", err)
7383
}
7484

7585
l.V(3).Infof("Running %d scripts (views)", len(allViews))
76-
if err := runScripts(pool, allViews, lo.Assign(allFunctions, allViews), config); err != nil {
86+
if err := runScripts(tx, allViews); err != nil {
7787
return fmt.Errorf("failed to run scripts for views: %w", err)
7888
}
7989

80-
return nil
90+
for file, content := range lo.Assign(allFunctions, allViews) {
91+
hash := sha1.Sum([]byte(content))
92+
if _, err := tx.Exec("INSERT INTO migration_logs(path, hash) VALUES($1, $2) ON CONFLICT (path) DO UPDATE SET hash = $2", file, hash[:]); err != nil {
93+
return fmt.Errorf("failed to save migration log %s: %w", file, err)
94+
}
95+
}
96+
97+
return tx.Commit()
8198
}
8299

83100
// GetExecutableScripts returns functions & views that must be applied.
@@ -211,16 +228,16 @@ func readMigrationLogs(pool *sql.DB) (map[string]string, error) {
211228
return migrationHashes, nil
212229
}
213230

214-
func createRole(db *sql.DB, roleName string, config api.Config) error {
231+
func createRole(tx *sql.Tx, roleName string, config api.Config) error {
215232
if roleName == "" {
216233
return nil
217234
}
218235
log := logger.GetLogger("migrate")
219236
count := 0
220-
if err := db.QueryRow("SELECT count(*) FROM pg_catalog.pg_roles WHERE rolname = $1 LIMIT 1", roleName).Scan(&count); err != nil {
237+
if err := tx.QueryRow("SELECT count(*) FROM pg_catalog.pg_roles WHERE rolname = $1 LIMIT 1", roleName).Scan(&count); err != nil {
221238
return err
222239
} else if count == 0 {
223-
if _, err := db.Exec(fmt.Sprintf("CREATE ROLE %s", roleName)); err != nil {
240+
if _, err := tx.Exec(fmt.Sprintf("CREATE ROLE %s", roleName)); err != nil {
224241
return err
225242
} else {
226243
log.Infof("Created role %s", roleName)
@@ -230,11 +247,18 @@ func createRole(db *sql.DB, roleName string, config api.Config) error {
230247
if user == "" {
231248
log.Errorf("Unable to find current user, %s may not be setup correctly", roleName)
232249
} else {
233-
if granted, err := checkIfRoleIsGranted(db, roleName, user); err != nil {
250+
if granted, err := checkIfRoleIsGranted(tx, roleName, user); err != nil {
234251
return err
235252
} else if !granted {
236-
if _, err := db.Exec(fmt.Sprintf(`GRANT %s TO "%s"`, roleName, user)); err != nil {
253+
// A failed statement aborts the transaction, so isolate the GRANT in a savepoint to keep it non-fatal.
254+
if _, err := tx.Exec("SAVEPOINT grant_role"); err != nil {
255+
return err
256+
}
257+
if _, err := tx.Exec(fmt.Sprintf(`GRANT %s TO "%s"`, roleName, user)); err != nil {
237258
log.Errorf("Failed to grant role %s to %s", roleName, user)
259+
if _, err := tx.Exec("ROLLBACK TO SAVEPOINT grant_role"); err != nil {
260+
return err
261+
}
238262
} else {
239263
log.Infof("Granted %s to %s", roleName, user)
240264
}
@@ -244,16 +268,16 @@ func createRole(db *sql.DB, roleName string, config api.Config) error {
244268
return nil
245269
}
246270

247-
func grantPostgrestRolesToCurrentUser(pool *sql.DB, config api.Config) error {
271+
func grantPostgrestRolesToCurrentUser(tx *sql.Tx, config api.Config) error {
248272
// Roles must exist before we create policies that refer to them.
249273
// Table and function access is granted later, in 9999_postgrest_permissions.sql.
250-
if err := createRole(pool, config.Postgrest.DBRole, config); err != nil {
274+
if err := createRole(tx, config.Postgrest.DBRole, config); err != nil {
251275
return err
252276
}
253-
return createRole(pool, config.Postgrest.AnonDBRole, config)
277+
return createRole(tx, config.Postgrest.AnonDBRole, config)
254278
}
255279

256-
func checkIfRoleIsGranted(pool *sql.DB, group, member string) (bool, error) {
280+
func checkIfRoleIsGranted(tx *sql.Tx, group, member string) (bool, error) {
257281
query := `
258282
SELECT COUNT(*)
259283
FROM pg_auth_members a, pg_roles b, pg_roles c
@@ -262,7 +286,7 @@ func checkIfRoleIsGranted(pool *sql.DB, group, member string) (bool, error) {
262286
a.member = c.oid AND b.rolname = $1 AND c.rolname = $2
263287
`
264288

265-
row := pool.QueryRow(query, group, member)
289+
row := tx.QueryRow(query, group, member)
266290
var count int
267291
err := row.Scan(&count)
268292
if err != nil {
@@ -274,53 +298,20 @@ func checkIfRoleIsGranted(pool *sql.DB, group, member string) (bool, error) {
274298
return true, nil
275299
}
276300

277-
func runScripts(pool *sql.DB, scripts, completedScripts map[string]string, config api.Config) error {
301+
func runScripts(tx *sql.Tx, scripts map[string]string) error {
278302
l := logger.GetLogger("migrate")
279303

280-
// Keep new views and their permissions in the same transaction. If a revoke
281-
// fails, roll back the grants too, rather than leaving private data exposed.
282-
tx, err := pool.Begin()
283-
if err != nil {
284-
return err
285-
}
286-
defer func() { _ = tx.Rollback() }()
287-
288-
// SQL uses the configured role names, not just the default PostgREST roles.
289-
if _, err := tx.Exec("SELECT set_config('duty.postgrest_api_role', $1, true), set_config('duty.postgrest_anon_role', $2, true)", config.Postgrest.DBRole, config.Postgrest.AnonDBRole); err != nil {
290-
return fmt.Errorf("failed to set PostgREST roles for migrations: %w", err)
291-
}
292-
293-
var filenames []string
294-
for name := range scripts {
295-
filenames = append(filenames, name)
296-
}
304+
filenames := lo.Keys(scripts)
297305
sort.Strings(filenames)
298306

299307
for _, file := range filenames {
300-
content, ok := scripts[file]
301-
if !ok {
302-
continue
303-
}
304-
305-
// Commit the removal of old hashes with the scripts, so a later failure cannot
306-
// make a retry skip a script that dropped objects needed by another batch.
307-
if _, err := tx.Exec("DELETE FROM migration_logs WHERE path = $1", file); err != nil {
308-
return fmt.Errorf("failed to clear migration log %s: %w", file, err)
309-
}
310308
l.Tracef("running script %s", file)
311-
if _, err := tx.Exec(content); err != nil {
309+
if _, err := tx.Exec(scripts[file]); err != nil {
312310
return fmt.Errorf("failed to run script %s: %w", file, db.ErrorDetails(err))
313311
}
314312
}
315313

316-
for file, content := range completedScripts {
317-
hash := sha1.Sum([]byte(content))
318-
if _, err := tx.Exec("INSERT INTO migration_logs(path, hash) VALUES($1, $2) ON CONFLICT (path) DO UPDATE SET hash = $2", file, hash[:]); err != nil {
319-
return fmt.Errorf("failed to save migration log %s: %w", file, err)
320-
}
321-
}
322-
323-
return tx.Commit()
314+
return nil
324315
}
325316

326317
func createMigrationLogTable(pool *sql.DB) error {

‎schema/apply.go‎

Lines changed: 19 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@ package schema
66

77
import (
88
"context"
9+
"database/sql"
910
"embed"
10-
"errors"
1111
"fmt"
1212
"io"
1313

1414
"ariga.io/atlas/sql/migrate"
15-
_ "ariga.io/atlas/sql/postgres"
15+
"ariga.io/atlas/sql/postgres"
1616
"ariga.io/atlas/sql/schema"
1717
"ariga.io/atlas/sql/sqlclient"
1818
"github.com/flanksource/commons/logger"
@@ -43,7 +43,8 @@ func skipDropTables(changes []schema.Change) []schema.Change {
4343
return filtered
4444
}
4545

46-
func Apply(ctx context.Context, connection string) error {
46+
// Apply migrates the schema within tx, so a failed change leaves the database untouched once tx rolls back.
47+
func Apply(ctx context.Context, tx *sql.Tx, connection string) error {
4748
log := logger.GetLogger("migrate")
4849

4950
// https://atlasgo.io/versioned/diff#exclude-objects
@@ -61,18 +62,22 @@ func Apply(ctx context.Context, connection string) error {
6162
"notification_group_resources.unique_notification_group_resources_unresolved_component",
6263
}
6364

64-
from, err := dbReader(ctx, connection, exclude)
65+
u, err := sqlclient.ParseURL(connection)
6566
if err != nil {
66-
return fmt.Errorf("failed to open connection: %w", err)
67+
return fmt.Errorf("failed to parse connection string: %w", err)
6768
}
68-
defer from.Close()
6969

70-
client, ok := from.Closer.(*sqlclient.Client)
71-
if !ok {
72-
return errors.New("--url must be a database connection")
70+
client, err := postgres.Open(tx)
71+
if err != nil {
72+
return fmt.Errorf("failed to open atlas driver: %w", err)
73+
}
74+
75+
from := &stateReadCloser{
76+
StateReader: migrate.SchemaConn(client, u.Query().Get("search_path"), &schema.InspectOptions{Exclude: exclude}),
77+
schema: u.Query().Get("search_path"),
7378
}
7479

75-
to, err := hclStateReader(ctx, client, schemas)
80+
to, err := hclStateReader(schemas)
7681
if err != nil {
7782
return fmt.Errorf("failed to initiate HCL state reader: %w", err)
7883
}
@@ -100,14 +105,14 @@ func Apply(ctx context.Context, connection string) error {
100105
}
101106

102107
if err = client.ApplyChanges(ctx, changes); err != nil {
103-
return fmt.Errorf("applied %d changes and then failed: %w", len(changes), err)
108+
return fmt.Errorf("failed to apply %d changes: %w", len(changes), err)
104109
}
105110

106111
log.V(1).Infof("Applied %d changes", len(changes))
107112
return nil
108113
}
109114

110-
func computeDiff(ctx context.Context, differ *sqlclient.Client, from, to *stateReadCloser) ([]schema.Change, error) {
115+
func computeDiff(ctx context.Context, differ migrate.Driver, from, to *stateReadCloser) ([]schema.Change, error) {
111116
current, err := from.ReadState(ctx)
112117
if err != nil {
113118
return nil, fmt.Errorf("failed to read state: %w", err)
@@ -139,7 +144,7 @@ func computeDiff(ctx context.Context, differ *sqlclient.Client, from, to *stateR
139144
}
140145

141146
// hclStateReadr returns a StateReader that reads the state from the given HCL paths urls.
142-
func hclStateReader(ctx context.Context, client *sqlclient.Client, fs embed.FS) (*stateReadCloser, error) {
147+
func hclStateReader(fs embed.FS) (*stateReadCloser, error) {
143148
scripts, err := schemas.ReadDir(".")
144149
if err != nil {
145150
return nil, fmt.Errorf("failed to read scripts: %w", err)
@@ -160,28 +165,14 @@ func hclStateReader(ctx context.Context, client *sqlclient.Client, fs embed.FS)
160165
}
161166

162167
realm := &schema.Realm{}
163-
if err := client.Eval(p, realm, make(map[string]cty.Value)); err != nil {
168+
if err := postgres.EvalHCL.Eval(p, realm, make(map[string]cty.Value)); err != nil {
164169
return nil, fmt.Errorf("failed to evaluate HCL: %w", err)
165170
}
166171

167172
t := &stateReadCloser{StateReader: migrate.Realm(realm), hcl: true}
168173
return t, nil
169174
}
170175

171-
func dbReader(ctx context.Context, connection string, exclude []string) (*stateReadCloser, error) {
172-
c, err := sqlclient.Open(ctx, connection)
173-
if err != nil {
174-
return nil, err
175-
}
176-
sr := migrate.SchemaConn(c.Driver, c.URL.Schema, &schema.InspectOptions{Exclude: exclude})
177-
178-
return &stateReadCloser{
179-
StateReader: sr,
180-
Closer: c,
181-
schema: c.URL.Schema,
182-
}, nil
183-
}
184-
185176
// Close redirects calls to Close to the enclosed io.Closer.
186177
func (sr *stateReadCloser) Close() {
187178
if sr.Closer != nil {

0 commit comments

Comments
 (0)