From 81b78f3af45b5dafa2ba523a5e5b3687f7c36ef6 Mon Sep 17 00:00:00 2001 From: "Grot (@grafanabot)" <43478413+grafanabot@users.noreply.github.com> Date: Tue, 18 Apr 2023 07:48:16 -0500 Subject: [PATCH] [v9.5.x] Annotations: Ignore unique constraint violations for tags (#66757) (cherry picked from commit 948131aac3ba136a336f06cfe9dd982bcba3896b) Co-authored-by: Emil Tullstedt --- pkg/services/tag/tagimpl/xorm_store.go | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/pkg/services/tag/tagimpl/xorm_store.go b/pkg/services/tag/tagimpl/xorm_store.go index 1bf77111c9d..834dc48e334 100644 --- a/pkg/services/tag/tagimpl/xorm_store.go +++ b/pkg/services/tag/tagimpl/xorm_store.go @@ -14,16 +14,18 @@ type sqlStore struct { func (s *sqlStore) EnsureTagsExist(ctx context.Context, tags []*tag.Tag) ([]*tag.Tag, error) { err := s.db.WithDbSession(ctx, func(sess *db.Session) error { for _, tagElement := range tags { - var existingTag tag.Tag - exists, err := sess.Table("tag").Where("`key`=? AND `value`=?", tagElement.Key, tagElement.Value).Get(&existingTag) + exists, err := s.innerGetTag(sess, tagElement) if err != nil { return err } - if exists { - tagElement.Id = existingTag.Id - } else { + if !exists { _, err := sess.Table("tag").Insert(tagElement) if err != nil { + if s.db.GetDialect().IsUniqueConstraintViolation(err) { + _, err := s.innerGetTag(sess, tagElement) + return err + } + return err } } @@ -32,3 +34,17 @@ func (s *sqlStore) EnsureTagsExist(ctx context.Context, tags []*tag.Tag) ([]*tag }) return tags, err } + +func (s *sqlStore) innerGetTag(sess *db.Session, tagElement *tag.Tag) (bool, error) { + var existingTag tag.Tag + exists, err := sess.Table("tag").Where("`key`=? AND `value`=?", tagElement.Key, tagElement.Value).Get(&existingTag) + if err != nil { + return false, err + } + if !exists { + return false, nil + } + + tagElement.Id = existingTag.Id + return true, nil +}