Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lock DB Upgrades #160

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions harmony/harmonydb/harmonydb.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,18 +234,39 @@ func ensureSchemaExists(connString, schema string) error {
//go:embed sql
var fs embed.FS

func (db *DB) upgrade() error {
func (db *DB) upgrade() (err error) {
// Does the version table exist? if not, make it.
// NOTE: This cannot change except via the next sql file.
_, err := db.Exec(context.Background(), `CREATE TABLE IF NOT EXISTS base (
_, err = db.Exec(context.Background(), `CREATE TABLE IF NOT EXISTS base (
id SERIAL PRIMARY KEY,
entry CHAR(12),
applied TIMESTAMP DEFAULT current_timestamp
)`)
)`)
if err != nil {
logger.Error("Upgrade failed.")
return xerrors.Errorf("Cannot create base table %w", err)
}
done := make(chan struct{})
txErr := make(chan error)
go func() {
_, err = db.BeginTransaction(context.Background(), func(tx *Tx) (commit bool, err error) {
_, err = tx.Exec(`LOCK TABLE base`)
if err != nil {
logger.Error("Upgrade failed: could not lock.")
return false, xerrors.Errorf("Cannot create base table %w", err)
}
<-done
return true, nil
})
txErr <- err
}()
defer func() {
close(done)
err2 := <-txErr
if err == nil {
err = err2
}
}()

// __Run scripts in order.__

Expand Down Expand Up @@ -310,7 +331,8 @@ func (db *DB) upgrade() error {
return xerrors.Errorf("cannot insert into base: %w", err)
}
}
return nil

return err
}

func parseSQLStatements(sqlContent string) []string {
Expand Down