Skip to content

Commit

Permalink
chore: modify recursion flow in topology/save
Browse files Browse the repository at this point in the history
  • Loading branch information
yashmehrotra authored and moshloop committed Sep 25, 2024
1 parent d684c03 commit e28fe26
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions topology/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package topology
import (
"strings"

"github.com/flanksource/commons/collections/set"
"github.com/flanksource/duty/context"
"github.com/flanksource/duty/db"
"github.com/flanksource/duty/models"
Expand All @@ -14,16 +13,15 @@ import (

// Save the component and its children returing the ids that were inserted/updated
func SaveComponent(ctx context.Context, c *models.Component) ([]string, error) {
ids := set.New[string]()
returnedIDs, err := saveComponentsRecursively(ctx, c, ids)
if err != nil {
var ids []string
if err := saveComponentsRecursively(ctx, c, &ids); err != nil {
return nil, err
}
return returnedIDs.ToSlice(), nil
return ids, nil
}

// We keep a list of ids to track all the insert/updated ids
func saveComponentsRecursively(ctx context.Context, c *models.Component, ids set.Set[string]) (set.Set[string], error) {
func saveComponentsRecursively(ctx context.Context, c *models.Component, ids *[]string) error {
if c.ParentId != nil && !strings.Contains(c.Path, c.ParentId.String()) {
if c.Path == "" {
c.Path = c.ParentId.String()
Expand All @@ -35,13 +33,13 @@ func saveComponentsRecursively(ctx context.Context, c *models.Component, ids set
if existing, err := query.ComponentFromCache(ctx, c.ID.String(), true); err == nil {
// Update component if it exists
if err := ctx.DB().UpdateColumns(c).Error; err != nil {
return nil, db.ErrorDetails(err)
return db.ErrorDetails(err)
}

// Unset deleted_at if it was non nil
if existing.DeletedAt != nil && c.DeletedAt == nil {
if err := ctx.DB().Update("deleted_at", nil).Error; err != nil {
return nil, db.ErrorDetails(err)
return db.ErrorDetails(err)
}
}
} else {
Expand All @@ -53,21 +51,23 @@ func saveComponentsRecursively(ctx context.Context, c *models.Component, ids set
Columns: []clause.Column{{Name: "topology_id"}, {Name: "type"}, {Name: "name"}, {Name: "parent_id"}},
UpdateAll: true,
}, clause.Returning{Columns: []clause.Column{{Name: "id"}}}).Create(c).Error; err != nil {
return nil, db.ErrorDetails(err)
return db.ErrorDetails(err)
}
}
ids.Add(c.ID.String())

if ids != nil {
*ids = append(*ids, c.ID.String())
}

if len(c.Components) > 0 {
for _, child := range c.Components {
child.TopologyID = c.TopologyID
child.ParentId = &c.ID
returnedIDs, err := saveComponentsRecursively(ctx, child, ids)
err := saveComponentsRecursively(ctx, child, ids)
if err != nil {
return nil, err
return err
}
ids.Union(returnedIDs)
}
}
return ids, nil
return nil
}

0 comments on commit e28fe26

Please sign in to comment.