yq/pkg/yqlib/operator_group_by.go

74 lines
1.9 KiB
Go
Raw Normal View History

2021-10-26 04:07:50 +00:00
package yqlib
import (
"container/list"
"fmt"
"github.com/elliotchance/orderedmap"
)
func processIntoGroups(d *dataTreeNavigator, context Context, rhsExp *ExpressionNode, node *CandidateNode) (*orderedmap.OrderedMap, error) {
2021-10-26 04:07:50 +00:00
var newMatches = orderedmap.NewOrderedMap()
for _, child := range node.Content {
2021-10-26 04:07:50 +00:00
rhs, err := d.GetMatchingNodes(context.SingleReadonlyChildContext(child), rhsExp)
if err != nil {
return nil, err
}
keyValue := "null"
if rhs.MatchingNodes.Len() > 0 {
first := rhs.MatchingNodes.Front()
keyCandidate := first.Value.(*CandidateNode)
keyValue = keyCandidate.Value
2021-10-26 04:07:50 +00:00
}
groupList, exists := newMatches.Get(keyValue)
if !exists {
groupList = list.New()
newMatches.Set(keyValue, groupList)
}
groupList.(*list.List).PushBack(child)
2021-10-26 04:07:50 +00:00
}
return newMatches, nil
}
func groupBy(d *dataTreeNavigator, context Context, expressionNode *ExpressionNode) (Context, error) {
2024-02-15 22:41:33 +00:00
log.Debugf("groupBy Operator")
2021-10-26 04:07:50 +00:00
var results = list.New()
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
candidate := el.Value.(*CandidateNode)
if candidate.Kind != SequenceNode {
return Context{}, fmt.Errorf("only arrays are supported for group by")
2021-10-26 04:07:50 +00:00
}
newMatches, err := processIntoGroups(d, context, expressionNode.RHS, candidate)
2021-10-26 04:07:50 +00:00
if err != nil {
return Context{}, err
}
resultNode := candidate.CreateReplacement(SequenceNode, "!!seq", "")
2021-10-26 04:07:50 +00:00
for groupEl := newMatches.Front(); groupEl != nil; groupEl = groupEl.Next() {
groupResultNode := &CandidateNode{Kind: SequenceNode, Tag: "!!seq"}
2021-10-26 04:07:50 +00:00
groupList := groupEl.Value.(*list.List)
for groupItem := groupList.Front(); groupItem != nil; groupItem = groupItem.Next() {
groupResultNode.AddChild(groupItem.Value.(*CandidateNode))
2021-10-26 04:07:50 +00:00
}
resultNode.AddChild(groupResultNode)
2021-10-26 04:07:50 +00:00
}
results.PushBack(resultNode)
2021-10-26 04:07:50 +00:00
}
return context.ChildContext(results), nil
}