From 95865c3d1777767d654d70937371e2f38a6e140b Mon Sep 17 00:00:00 2001 From: Michael Mraka Date: Thu, 20 Jun 2024 12:03:03 +0200 Subject: [PATCH] RHINENG-10827: unassign systems before template delete --- listener/templates.go | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/listener/templates.go b/listener/templates.go index e9fe8cd24..a1996acc4 100644 --- a/listener/templates.go +++ b/listener/templates.go @@ -61,9 +61,32 @@ func TemplateDelete(template mqueue.TemplateResponse) error { tStart := time.Now() defer utils.ObserveSecondsSince(tStart, templateMsgHandlingDuration.WithLabelValues(TemplateEventDelete)) - err := database.DB. - Delete(&models.Template{}, "uuid = ?::uuid AND rh_account_id = (SELECT id FROM rh_account WHERE org_id = ?)", - template.UUID, template.OrgID).Error + // check account + accountID, err := middlewares.GetOrCreateAccount(template.OrgID) + if err != nil { + return errors.Wrap(err, "saving account into the database") + } + + var templateID int64 + err = database.DB.Model(&models.Template{}). + Select("id"). + Where("rh_account_id = ? AND uuid = ?::uuid ", accountID, template.UUID). + // use Find() not First() otherwise it returns error "no rows found" if uuid is not present + Find(&templateID).Error + if err != nil { + return errors.Wrap(err, "looking for template") + } + + // unassign systems from the template + err = database.DB.Model(&models.SystemPlatform{}). + Where("rh_account_id = ? AND template_id = ?", accountID, templateID). + Update("template_id", nil).Error + if err != nil { + return errors.Wrap(err, "removing systems from template") + } + + err = database.DB. + Delete(&models.Template{}, "id = ? AND rh_account_id = ?", templateID, accountID).Error if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { utils.LogWarn("template", template.UUID, WarnNoRowsModified) return nil