From e0147b04c1978e697dc445475d0a129a677df0de Mon Sep 17 00:00:00 2001 From: Kegan Dougal Date: Thu, 20 Jan 2022 18:48:56 +0000 Subject: [PATCH] fixup postgres migration on fresh dendrite instances --- .../deltas/2022012016470000_key_changes.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/keyserver/storage/postgres/deltas/2022012016470000_key_changes.go b/keyserver/storage/postgres/deltas/2022012016470000_key_changes.go index dabdf2715..e5bcf08d1 100644 --- a/keyserver/storage/postgres/deltas/2022012016470000_key_changes.go +++ b/keyserver/storage/postgres/deltas/2022012016470000_key_changes.go @@ -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(`