fixup postgres migration on fresh dendrite instances

This commit is contained in:
Kegan Dougal 2022-01-20 18:48:56 +00:00
parent 031cc1876d
commit e0147b04c1

View file

@ -20,7 +20,6 @@ import (
"github.com/matrix-org/dendrite/internal/sqlutil"
"github.com/pressly/goose"
"github.com/sirupsen/logrus"
)
func LoadFromGoose() {
@ -32,12 +31,18 @@ func LoadRefactorKeyChanges(m *sqlutil.Migrations) {
}
func UpRefactorKeyChanges(tx *sql.Tx) error {
logrus.Infof("running delta!")
// start counting from the last max offset, else 0.
var maxOffset int64
_ = tx.QueryRow(`SELECT coalesce(MAX(log_offset), 0) AS offset FROM keyserver_key_changes`).Scan(&maxOffset)
if _, err := tx.Exec(fmt.Sprintf(`CREATE SEQUENCE IF NOT EXISTS keyserver_key_changes_seq START %d`, maxOffset)); err != nil {
return fmt.Errorf("failed to CREATE SEQUENCE for key changes, starting at %d: %s", maxOffset, err)
// start counting from the last max offset, else 0. We need to do a count(*) first to see if there
// even are entries in this table to know if we can query for log_offset. Without the count then
// the query to SELECT the max log offset fails on new Dendrite instances as log_offset doesn't
// exist on that table. Even though we discard the error, the txn is tainted and gets aborted :/
var count int
_ = tx.QueryRow(`SELECT count(*) FROM keyserver_key_changes`).Scan(&count)
if count > 0 {
var maxOffset int64
_ = tx.QueryRow(`SELECT coalesce(MAX(log_offset), 0) AS offset FROM keyserver_key_changes`).Scan(&maxOffset)
if _, err := tx.Exec(fmt.Sprintf(`CREATE SEQUENCE IF NOT EXISTS keyserver_key_changes_seq START %d`, maxOffset)); err != nil {
return fmt.Errorf("failed to CREATE SEQUENCE for key changes, starting at %d: %s", maxOffset, err)
}
}
_, err := tx.Exec(`