storj/private/migrate/create.go
paul cannon 0c88a7b475 private/migrate: use transactional helpers and not Begin()
This code needs to work against cockroachDB, so transactions must be retried
when a retryable error is returned. This change puts migrate
transactions into the dbutil.WithTx transactional helpers to achieve
this in the easiest way.

Change-Id: Ib930e82d55cb0257357a222ce9131e6e53372c03
2020-01-07 18:25:38 +00:00

64 lines
1.5 KiB
Go

// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package migrate
import (
"context"
"database/sql"
"github.com/zeebo/errs"
)
// Error is the default migrate errs class
var Error = errs.Class("migrate")
// Create with a previous schema check
func Create(identifier string, db DBX) error {
// is this necessary? it's not immediately obvious why we roll back the transaction
// when the schemas match.
justRollbackPlease := errs.Class("only used to tell WithTx to do a rollback")
err := WithTx(context.Background(), db, func(ctx context.Context, tx *sql.Tx) (err error) {
schema := db.Schema()
_, err = tx.Exec(db.Rebind(`CREATE TABLE IF NOT EXISTS table_schemas (id text, schemaText text);`))
if err != nil {
return err
}
row := tx.QueryRow(db.Rebind(`SELECT schemaText FROM table_schemas WHERE id = ?;`), identifier)
var previousSchema string
err = row.Scan(&previousSchema)
// not created yet
if err == sql.ErrNoRows {
_, err := tx.Exec(schema)
if err != nil {
return err
}
_, err = tx.Exec(db.Rebind(`INSERT INTO table_schemas(id, schemaText) VALUES (?, ?);`), identifier, schema)
if err != nil {
return err
}
return nil
}
if err != nil {
return err
}
if schema != previousSchema {
return Error.New("schema mismatch:\nold %v\nnew %v", previousSchema, schema)
}
return justRollbackPlease.New("")
})
if justRollbackPlease.Has(err) {
err = nil
}
return Error.Wrap(err)
}