From c6bafce3d9da01f0090085ca712567bf198ee32c Mon Sep 17 00:00:00 2001 From: qbart Date: Fri, 5 May 2023 19:26:16 +0200 Subject: [PATCH] Add transaction attribute to actions --- docker-compose.yml | 2 +- krab/action.go | 17 +++++++++++++++-- krab/cmd_action.go | 15 ++++++++++++++- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 0183af6..c1d0685 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,6 +16,6 @@ services: ports: - "8081:8081" environment: - - DATABASE_URL=postgres://krab:secret@pg:5432/krab?sslmode=disable + - PGWEB_DATABASE_URL=postgres://krab:secret@pg:5432/krab?sslmode=disable depends_on: - pg diff --git a/krab/action.go b/krab/action.go index 5dd4b53..6e12e22 100644 --- a/krab/action.go +++ b/krab/action.go @@ -9,7 +9,6 @@ import ( ) // Action represents custom action to execute. -// type Action struct { krabhcl.Source @@ -18,7 +17,8 @@ type Action struct { Arguments *Arguments - SQL string + SQL string + Transaction bool // wrap operation in transaction } func (a *Action) Addr() krabhcl.Addr { @@ -37,6 +37,10 @@ var schemaAction = &hcl.BodySchema{ Name: "sql", Required: true, }, + { + Name: "transaction", + Required: false, + }, }, } @@ -47,6 +51,7 @@ func (a *Action) DecodeHCL(ctx *hcl.EvalContext, block *hcl.Block) error { a.Namespace = block.Labels[0] a.RefName = block.Labels[1] a.Arguments = &Arguments{} + a.Transaction = true content, diags := block.Body.Content(schemaAction) if diags.HasErrors() { @@ -76,6 +81,14 @@ func (a *Action) DecodeHCL(ctx *hcl.EvalContext, block *hcl.Block) error { } a.SQL = val + case "transaction": + expr := krabhcl.Expression{Expr: v.Expr, EvalContext: ctx} + val, err := expr.Bool() + if err != nil { + return err + } + a.Transaction = val + default: return fmt.Errorf("Unknown attribute `%s` for `%s` block", k, block.Type) } diff --git a/krab/cmd_action.go b/krab/cmd_action.go index 64da968..546d581 100644 --- a/krab/cmd_action.go +++ b/krab/cmd_action.go @@ -9,6 +9,7 @@ import ( "github.com/ohkrab/krab/krabhcl" "github.com/ohkrab/krab/krabtpl" "github.com/ohkrab/krab/tpls" + "github.com/pkg/errors" ) // CmdAction returns migration status information. @@ -51,7 +52,19 @@ func (c *CmdAction) run(ctx context.Context, db krabdb.DB, inputs NamedInputs) ( c.Action.ToSQL(&sb) sql := tpl.Render(sb.String()) - _, err := db.ExecContext(ctx, sql) + tx, err := db.NewTx(ctx, c.Action.Transaction) + if err != nil { + return result, errors.Wrap(err, "failed to create transaction") + } + _, err = tx.ExecContext(ctx, sql) + if err != nil { + tx.Rollback() + return result, errors.Wrap(err, "action failed") + } + err = tx.Commit() + if err != nil { + return result, errors.Wrap(err, "failed to commit transaction") + } return result, err }