Alerting: fix postgres migration on conflict (#35556)

This commit is contained in:
Sofia Papagiannaki 2021-06-14 16:43:33 +03:00 committed by GitHub
parent 4cb62e4292
commit 423474325a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 3 deletions

View File

@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"os"
"strings"
pb "github.com/prometheus/alertmanager/silence/silencepb"
"xorm.io/xorm"
@ -217,7 +218,14 @@ func (m *migration) Exec(sess *xorm.Session, mg *migrator.Migrator) error {
return err
}
_, err = m.sess.Insert(rule)
if strings.HasPrefix(mg.Dialect.DriverName(), migrator.Postgres) {
err = mg.InTransaction(func(sess *xorm.Session) error {
_, err = sess.Insert(rule)
return err
})
} else {
_, err = m.sess.Insert(rule)
}
if err != nil {
// TODO better error handling, if constraint
rule.Title += fmt.Sprintf(" %v", rule.Uid)

View File

@ -103,7 +103,7 @@ func (mg *Migrator) Start() error {
Timestamp: time.Now(),
}
err := mg.inTransaction(func(sess *xorm.Session) error {
err := mg.InTransaction(func(sess *xorm.Session) error {
err := mg.exec(m, sess)
if err != nil {
mg.Logger.Error("Exec failed", "error", err, "sql", sql)
@ -183,7 +183,7 @@ func (mg *Migrator) ClearMigrationEntry(id string) error {
type dbTransactionFunc func(sess *xorm.Session) error
func (mg *Migrator) inTransaction(callback dbTransactionFunc) error {
func (mg *Migrator) InTransaction(callback dbTransactionFunc) error {
sess := mg.x.NewSession()
defer sess.Close()