Skip to content

Commit

Permalink
chore: reduce db hits for comp relationship sync (#1640)
Browse files Browse the repository at this point in the history
  • Loading branch information
yashmehrotra authored Feb 1, 2024
1 parent 4213a93 commit 8c57abf
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions pkg/topology/component_relationship.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,33 +96,29 @@ func syncComponentRelationships(ctx context.Context, id uuid.UUID, relationships
return err
}

var existingChildComponentIDs []string
for _, r := range existingRelationships {
existingChildComponentIDs = append(existingChildComponentIDs, r.ComponentID.String())
}
existingChildComponentIDs := lo.Map(existingRelationships, func(c models.ComponentRelationship, _ int) string { return c.ComponentID.String() })

var newChildComponentIDs []string
for _, r := range relationships {
newChildComponentIDs = append(newChildComponentIDs, r.ComponentID.String())
}
newChildComponentIDs := lo.Map(relationships, func(c models.ComponentRelationship, _ int) string { return c.ComponentID.String() })

if len(relationships) > 0 {
if err := ctx.DB().Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "component_id"}, {Name: "relationship_id"}, {Name: "selector_id"}},
UpdateAll: true,
DoUpdates: clause.Assignments(map[string]any{"deleted_at": nil}),
}).Create(relationships).Error; err != nil {
return err
}
}

// Take set difference of these child component Ids and delete them
childComponentIDsToDelete, _ := lo.Difference(existingChildComponentIDs, newChildComponentIDs)
if err := ctx.DB().
Table("component_relationships").
Where("relationship_id = ? AND component_id IN ?", id, childComponentIDsToDelete).
Update("deleted_at", duty.Now()).
Error; err != nil {
return errors.Wrap(err, "error deleting stale component relationships")
if len(childComponentIDsToDelete) > 0 {
if err := ctx.DB().
Table("component_relationships").
Where("relationship_id = ? AND component_id IN ?", id, childComponentIDsToDelete).
Update("deleted_at", duty.Now()).
Error; err != nil {
return errors.Wrap(err, "error deleting stale component relationships")
}
}

return nil
Expand Down

0 comments on commit 8c57abf

Please sign in to comment.