having_operator.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2021-2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package operator
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/xsql"
  18. "github.com/lf-edge/ekuiper/pkg/api"
  19. "github.com/lf-edge/ekuiper/pkg/ast"
  20. )
  21. type HavingOp struct {
  22. Condition ast.Expr
  23. }
  24. func (p *HavingOp) Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, afv *xsql.AggregateFunctionValuer) interface{} {
  25. log := ctx.GetLogger()
  26. log.Debugf("having plan receive %v", data)
  27. switch input := data.(type) {
  28. case error:
  29. return input
  30. case xsql.Collection:
  31. var groups []int
  32. err := input.GroupRange(func(i int, aggRow xsql.CollectionRow) (bool, error) {
  33. afv.SetData(aggRow)
  34. ve := &xsql.ValuerEval{Valuer: xsql.MultiAggregateValuer(aggRow, fv, aggRow, fv, afv, &xsql.WildcardValuer{Data: aggRow})}
  35. result := ve.Eval(p.Condition)
  36. switch val := result.(type) {
  37. case error:
  38. return false, fmt.Errorf("run Having error: %s", val)
  39. case bool:
  40. if val {
  41. groups = append(groups, i)
  42. }
  43. return true, nil
  44. default:
  45. return false, fmt.Errorf("run Having error: invalid condition that returns non-bool value %[1]T(%[1]v)", val)
  46. }
  47. })
  48. if err != nil {
  49. return err
  50. }
  51. if len(groups) > 0 {
  52. switch gi := input.(type) {
  53. case *xsql.GroupedTuplesSet:
  54. return gi.Filter(groups)
  55. default:
  56. return gi
  57. }
  58. }
  59. default:
  60. return fmt.Errorf("run Having error: invalid input %[1]T(%[1]v)", input)
  61. }
  62. return nil
  63. }