Skip to content

Commit

Permalink
Add transaction attribute to actions
Browse files Browse the repository at this point in the history
  • Loading branch information
qbart committed May 5, 2023
1 parent 45f4bac commit c6bafce
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
17 changes: 15 additions & 2 deletions krab/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
)

// Action represents custom action to execute.
//
type Action struct {
krabhcl.Source

Expand All @@ -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 {
Expand All @@ -37,6 +37,10 @@ var schemaAction = &hcl.BodySchema{
Name: "sql",
Required: true,
},
{
Name: "transaction",
Required: false,
},
},
}

Expand All @@ -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() {
Expand Down Expand Up @@ -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)
}
Expand Down
15 changes: 14 additions & 1 deletion krab/cmd_action.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}

0 comments on commit c6bafce

Please sign in to comment.