Skip to content

Commit

Permalink
added fix for template soft deletes
Browse files Browse the repository at this point in the history
Signed-off-by: cvillanueva@equinix.com <cvillanueva@equinix.com>
  • Loading branch information
cvillanueva@equinix.com committed Dec 4, 2020
1 parent 86057d3 commit 27d9647
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 12 deletions.
12 changes: 12 additions & 0 deletions db/migration/202012031335-remove-unique-name-template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package migration

import migrate "github.com/rubenv/sql-migrate"

func Get202012031335() *migrate.Migration {
return &migrate.Migration{
Id: "202012031335-remove-unique-name-template",
Up: []string{`
ALTER TABLE template DROP CONSTRAINT template_name_key;
`},
}
}
1 change: 1 addition & 0 deletions db/migration/migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ func GetMigrations() *migrate.MemoryMigrationSource {
Migrations: []*migrate.Migration{
Get202009171251(),
Get202010221010(),
Get202012031335(),
},
}
}
33 changes: 21 additions & 12 deletions db/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package db
import (
"context"
"database/sql"
"fmt"
"strings"
"time"

"github.com/golang/protobuf/ptypes"
Expand All @@ -18,26 +20,33 @@ func (d TinkDB) CreateTemplate(ctx context.Context, name string, data string, id
if err != nil {
return err
}

filter := make(map[string]string)
filter["name"] = name
uuid, data, _, err := d.GetTemplate(ctx, filter)
if err != nil && !strings.Contains(err.Error(), "no rows in result set") {
return err
}
if uuid != "" {
err = fmt.Errorf("%s %s already exists", uuid, name)
return err
}
tx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
return errors.Wrap(err, "BEGIN transaction")
}

_, err = tx.Exec(`
INSERT INTO
template (created_at, updated_at, name, data, id)
VALUES
($1, $1, $2, $3, $4)
ON CONFLICT (id)
DO
UPDATE SET
(updated_at, deleted_at, name, data) = ($1, NULL, $2, $3);
`, time.Now(), name, data, id)
INSERT INTO
template (created_at, updated_at, name, data, id)
VALUES
($1, $1, $2, $3, $4)
ON CONFLICT (id)
DO
UPDATE SET
(updated_at, deleted_at, name, data) = ($1, NULL, $2, $3);
`, time.Now(), name, data, id)
if err != nil {
return errors.Wrap(err, "INSERT")
}

err = tx.Commit()
if err != nil {
return errors.Wrap(err, "COMMIT")
Expand Down

0 comments on commit 27d9647

Please sign in to comment.