Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

Do not use ON CONFLICT (upsert syntax) for upserting anomaly as it will consume id on conflict

天舟aff13cb9a665
diff --git a/api/anomaly.go b/api/anomaly.go
index 5b3d825dc6..efb499ed82 100644
--- a/api/anomaly.go
+++ b/api/anomaly.go
@@ -64,6 +64,7 @@ type AnomalyFind struct {
// Related fields
DatabaseId int
+ Type *AnomalyType
}
func (find *AnomalyFind) String() string {
@@ -80,8 +81,8 @@ type AnomalyArchive struct {
}
type AnomalyService interface {
- // UpsertAnomaly would update the existing user if name matches.
- UpsertAnomaly(ctx context.Context, upsert *AnomalyUpsert) (*Anomaly, error)
+ // UpsertActiveAnomaly would update the existing active anomaly if both database id and type match, otherwise create a new one.
+ UpsertActiveAnomaly(ctx context.Context, upsert *AnomalyUpsert) (*Anomaly, error)
FindAnomalyList(ctx context.Context, find *AnomalyFind) ([]*Anomaly, error)
ArchiveAnomaly(ctx context.Context, archive *AnomalyArchive) error
}
diff --git a/server/anomaly_scanner.go b/server/anomaly_scanner.go
index 22cec25af3..1baa1c4864 100644
--- a/server/anomaly_scanner.go
+++ b/server/anomaly_scanner.go
@@ -185,7 +185,7 @@ func (s *AnomalyScanner) checkBackupAnomaly(instance *api.Instance, database *ap
zap.String("type", string(api.AnomalyBackupPolicyViolation)),
zap.Error(err))
} else {
- _, err = s.server.AnomalyService.UpsertAnomaly(context.Background(), &api.AnomalyUpsert{
+ _, err = s.server.AnomalyService.UpsertActiveAnomaly(context.Background(), &api.AnomalyUpsert{
CreatorId: api.SYSTEM_BOT_ID,
InstanceId: instance.ID,
DatabaseId: database.ID,
@@ -216,68 +216,86 @@ func (s *AnomalyScanner) checkBackupAnomaly(instance *api.Instance, database *ap
}
// Check backup missing
- // The anomaly fires if backup is enabled, however no succesful backup has been taken during the period.
- if backupSetting != nil && backupSetting.Enabled {
- expectedSchedule := api.BackupPlanPolicyScheduleWeekly
- backupMaxAge := time.Duration(7*24) * time.Hour
- if backupSetting.DayOfWeek == -1 {
- expectedSchedule = api.BackupPlanPolicyScheduleDaily
- backupMaxAge = time.Duration(24) * time.Hour
- }
-
- // Ignore if backup setting has been changed after the max age.
- if backupSetting.UpdatedTs < time.Now().Add(-backupMaxAge).Unix() {
- status := api.BackupStatusDone
- backupFind := &api.BackupFind{
- DatabaseId: &database.ID,
- Status: &status,
- }
- backupList, err := s.server.BackupService.FindBackupList(context.Background(), backupFind)
- if err != nil {
- s.l.Error("Failed to retrieve backup list",
- zap.String("instance", instance.Name),
- zap.String("database", database.Name),
- zap.Error(err))
+ {
+ var backupMissingAnomalyPayload *api.AnomalyBackupMissingPayload
+ // The anomaly fires if backup is enabled, however no succesful backup has been taken during the period.
+ if backupSetting != nil && backupSetting.Enabled {
+ expectedSchedule := api.BackupPlanPolicyScheduleWeekly
+ backupMaxAge := time.Duration(7*24) * time.Hour
+ if backupSetting.DayOfWeek == -1 {
+ expectedSchedule = api.BackupPlanPolicyScheduleDaily
+ backupMaxAge = time.Duration(24) * time.Hour
}
- hasValidBackup := false
- if len(backupList) > 0 {
- if backupList[0].CreatedTs >= time.Now().Add(-backupMaxAge).Unix() {
- hasValidBackup = true
+ // Ignore if backup setting has been changed after the max age.
+ if backupSetting.UpdatedTs < time.Now().Add(-backupMaxAge).Unix() {
+ status := api.BackupStatusDone
+ backupFind := &api.BackupFind{
+ DatabaseId: &database.ID,
+ Status: &status,
}
- }
-
- if !hasValidBackup {
- backupMissingAnomalyPayload := &api.AnomalyBackupMissingPayload{
- ExpectedBackupSchedule: expectedSchedule,
+ backupList, err := s.server.BackupService.FindBackupList(context.Background(), backupFind)
+ if err != nil {
+ s.l.Error("Failed to retrieve backup list",
+ zap.String("instance", instance.Name),
+ zap.String("database", database.Name),
+ zap.Error(err))
}
+
+ hasValidBackup := false
if len(backupList) > 0 {
- backupMissingAnomalyPayload.LastBackupTs = backupList[0].CreatedTs
+ if backupList[0].UpdatedTs >= time.Now().Add(-backupMaxAge).Unix() {
+ hasValidBackup = true
+ }
+ }
+
+ if !hasValidBackup {
+ backupMissingAnomalyPayload = &api.AnomalyBackupMissingPayload{
+ ExpectedBackupSchedule: expectedSchedule,
+ }
+ if len(backupList) > 0 {
+ backupMissingAnomalyPayload.LastBackupTs = backupList[0].UpdatedTs
+ }
}
- payload, err := json.Marshal(*backupMissingAnomalyPayload)
+ }
+ }
+
+ if backupMissingAnomalyPayload != nil {
+ payload, err := json.Marshal(*backupMissingAnomalyPayload)
+ if err != nil {
+ s.l.Error("Failed to marshal anomaly payload",
+ zap.String("instance", instance.Name),
+ zap.String("database", database.Name),
+ zap.String("type", string(api.AnomalyBackupMissing)),
+ zap.Error(err))
+ } else {
+ _, err = s.server.AnomalyService.UpsertActiveAnomaly(context.Background(), &api.AnomalyUpsert{
+ CreatorId: api.SYSTEM_BOT_ID,
+ InstanceId: instance.ID,
+ DatabaseId: database.ID,
+ Type: api.AnomalyBackupMissing,
+ Payload: string(payload),
+ })
if err != nil {
- s.l.Error("Failed to marshal anomaly payload",
+ s.l.Error("Failed to create anomaly",
zap.String("instance", instance.Name),
zap.String("database", database.Name),
zap.String("type", string(api.AnomalyBackupMissing)),
zap.Error(err))
- } else {
- _, err = s.server.AnomalyService.UpsertAnomaly(context.Background(), &api.AnomalyUpsert{
- CreatorId: api.SYSTEM_BOT_ID,
- InstanceId: instance.ID,
- DatabaseId: database.ID,
- Type: api.AnomalyBackupMissing,
- Payload: string(payload),
- })
- if err != nil {
- s.l.Error("Failed to create anomaly",
- zap.String("instance", instance.Name),
- zap.String("database", database.Name),
- zap.String("type", string(api.AnomalyBackupMissing)),
- zap.Error(err))
- }
}
}
+ } else {
+ err := s.server.AnomalyService.ArchiveAnomaly(context.Background(), &api.AnomalyArchive{
+ DatabaseId: database.ID,
+ Type: api.AnomalyBackupMissing,
+ })
+ if err != nil && common.ErrorCode(err) != common.NotFound {
+ s.l.Error("Failed to close anomaly",
+ zap.String("instance", instance.Name),
+ zap.String("database", database.Name),
+ zap.String("type", string(api.AnomalyBackupMissing)),
+ zap.Error(err))
+ }
}
}
}
diff --git a/store/anomaly.go b/store/anomaly.go
index 206d241ce8..833aeebe78 100644
--- a/store/anomaly.go
+++ b/store/anomaly.go
@@ -25,19 +25,46 @@ func NewAnomalyService(logger *zap.Logger, db *DB) *AnomalyService {
return &AnomalyService{l: logger, db: db}
}
-// UpsertAnomaly would update the existing user if name matches.
-func (s *AnomalyService) UpsertAnomaly(ctx context.Context, upsert *api.AnomalyUpsert) (*api.Anomaly, error) {
+// UpsertActiveAnomaly would update the existing active anomaly if both database id and type match, otherwise create a new one.
+// Do not use ON CONFLICT (upsert syntax) as it will consume autoincrement id. Functional wise, this is fine, but
+// from the UX perspective, it's not great, since user will see large id gaps.
+func (s *AnomalyService) UpsertActiveAnomaly(ctx context.Context, upsert *api.AnomalyUpsert) (*api.Anomaly, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.Rollback()
- anomaly, err := upsertAnomaly(ctx, tx, upsert)
+ status := api.Normal
+ find := &api.AnomalyFind{
+ RowStatus: &status,
+ DatabaseId: upsert.DatabaseId,
+ Type: &upsert.Type,
+ }
+ list, err := findAnomalyList(ctx, tx, find)
if err != nil {
return nil, err
}
+ var anomaly *api.Anomaly
+ if len(list) == 0 {
+ anomaly, err = createAnomaly(ctx, tx, upsert)
+ if err != nil {
+ return nil, err
+ }
+ } else if len(list) == 1 {
+ anomaly, err = patchAnomaly(ctx, tx, &anomalyPatch{
+ ID: list[0].ID,
+ UpdaterId: upsert.CreatorId,
+ Payload: upsert.Payload,
+ })
+ if err != nil {
+ return nil, err
+ }
+ } else {
+ return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d active anomalies with filter %+v, expect 1", len(list), find)}
+ }
+
if err := tx.Commit(); err != nil {
return nil, FormatError(err)
}
@@ -82,9 +109,9 @@ func (s *AnomalyService) ArchiveAnomaly(ctx context.Context, archive *api.Anomal
return nil
}
-// upsertAnomaly upserts a new anomaly.
-func upsertAnomaly(ctx context.Context, tx *Tx, upsert *api.AnomalyUpsert) (*api.Anomaly, error) {
- // Upsert row into database.
+// createAnomaly creates a new anomaly.
+func createAnomaly(ctx context.Context, tx *Tx, upsert *api.AnomalyUpsert) (*api.Anomaly, error) {
+ // Inserts row into database.
row, err := tx.QueryContext(ctx, `
INSERT INTO anomaly (
creator_id,
@@ -95,9 +122,6 @@ func upsertAnomaly(ctx context.Context, tx *Tx, upsert *api.AnomalyUpsert) (*api
payload
)
VALUES (?, ?, ?, ?, ?, ?)
- ON CONFLICT (database_id, `+"`type`"+`) DO UPDATE SET
- updater_id = excluded.updater_id,
- payload = excluded.payload
RETURNING id, creator_id, created_ts, updater_id, updated_ts, instance_id, database_id, `+"`type`"+`, payload
`,
upsert.CreatorId,
@@ -139,6 +163,9 @@ func findAnomalyList(ctx context.Context, tx *Tx, find *api.AnomalyFind) (_ []*a
if v := find.RowStatus; v != nil {
where, args = append(where, "row_status = ?"), append(args, *v)
}
+ if v := find.Type; v != nil {
+ where, args = append(where, "`type` = ?"), append(args, *v)
+ }
rows, err := tx.QueryContext(ctx, `
SELECT
@@ -188,6 +215,61 @@ func findAnomalyList(ctx context.Context, tx *Tx, find *api.AnomalyFind) (_ []*a
return list, nil
}
+type anomalyPatch struct {
+ ID int
+
+ // Standard fields
+ UpdaterId int
+
+ // Domain specific fields
+ Payload string
+}
+
+// patchAnomaly patches an anomaly
+func patchAnomaly(ctx context.Context, tx *Tx, patch *anomalyPatch) (*api.Anomaly, error) {
+ // Build UPDATE clause.
+ set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
+ set, args = append(set, "payload = ?"), append(args, patch.Payload)
+ args = append(args, patch.ID)
+
+ // Execute update query with RETURNING.
+ row, err := tx.QueryContext(ctx, `
+ UPDATE anomaly
+ SET `+strings.Join(set, ", ")+`
+ WHERE id = ?
+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, instance_id, database_id, `+"`type`"+`, payload
+ `,
+ args...,
+ )
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer row.Close()
+
+ row.Next()
+ var anomaly api.Anomaly
+ if err := row.Scan(
+ &anomaly.ID,
+ &anomaly.CreatorId,
+ &anomaly.CreatedTs,
+ &anomaly.UpdaterId,
+ &anomaly.UpdatedTs,
+ &anomaly.InstanceId,
+ &anomaly.DatabaseId,
+ &anomaly.Type,
+ &anomaly.Payload,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+
+ return &anomaly, err
+}
+
// archiveAnomaly archives an anomaly by ID.
func archiveAnomaly(ctx context.Context, tx *Tx, archive *api.AnomalyArchive) error {
// Remove row from database.