Skip to content

Commit

Permalink
RHINENG-10827: unassign systems before template delete
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelMraka committed Jun 20, 2024
1 parent fc43b6c commit 95865c3
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions listener/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 95865c3

Please sign in to comment.