@@ -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
326317func createMigrationLogTable (pool * sql.DB ) error {
0 commit comments