having_operator.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2021-2023 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. StateFuncs []*ast.Call
  24. }
  25. func (p *HavingOp) Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, afv *xsql.AggregateFunctionValuer) interface{} {
  26. log := ctx.GetLogger()
  27. log.Debugf("having plan receive %v", data)
  28. switch input := data.(type) {
  29. case error:
  30. return input
  31. case xsql.Collection:
  32. var groups []int
  33. err := input.GroupRange(func(i int, aggRow xsql.CollectionRow) (bool, error) {
  34. afv.SetData(aggRow)
  35. ve := &xsql.ValuerEval{Valuer: xsql.MultiAggregateValuer(aggRow, fv, aggRow, fv, afv, &xsql.WildcardValuer{Data: aggRow})}
  36. result := ve.Eval(p.Condition)
  37. switch val := result.(type) {
  38. case error:
  39. return false, fmt.Errorf("run Having error: %s", val)
  40. case bool:
  41. if val {
  42. groups = append(groups, i)
  43. }
  44. return true, nil
  45. default:
  46. return false, fmt.Errorf("run Having error: invalid condition that returns non-bool value %[1]T(%[1]v)", val)
  47. }
  48. })
  49. if err != nil {
  50. return err
  51. }
  52. if len(groups) > 0 {
  53. // update trigger
  54. ve := &xsql.ValuerEval{Valuer: xsql.MultiValuer(fv)}
  55. for _, f := range p.StateFuncs {
  56. _ = ve.Eval(f)
  57. }
  58. switch gi := input.(type) {
  59. case *xsql.GroupedTuplesSet:
  60. return gi.Filter(groups)
  61. default:
  62. return gi
  63. }
  64. }
  65. default:
  66. return fmt.Errorf("run Having error: invalid input %[1]T(%[1]v)", input)
  67. }
  68. return nil
  69. }