filterPlan.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 planner
  15. import (
  16. "github.com/lf-edge/ekuiper/internal/xsql"
  17. "github.com/lf-edge/ekuiper/pkg/ast"
  18. )
  19. type FilterPlan struct {
  20. baseLogicalPlan
  21. condition ast.Expr
  22. stateFuncs []*ast.Call
  23. }
  24. func (p FilterPlan) Init() *FilterPlan {
  25. p.baseLogicalPlan.self = &p
  26. return &p
  27. }
  28. func (p *FilterPlan) PushDownPredicate(condition ast.Expr) (ast.Expr, LogicalPlan) {
  29. // if no child, swallow all conditions
  30. a := combine(condition, p.condition)
  31. if len(p.children) == 0 {
  32. p.condition = a
  33. return nil, p
  34. }
  35. rest, _ := p.baseLogicalPlan.PushDownPredicate(a)
  36. if rest != nil {
  37. p.condition = rest
  38. return nil, p
  39. } else if len(p.children) == 1 {
  40. // eliminate this filter
  41. return nil, p.children[0]
  42. } else {
  43. return nil, p
  44. }
  45. }
  46. func (p *FilterPlan) PruneColumns(fields []ast.Expr) error {
  47. f := getFields(p.condition)
  48. return p.baseLogicalPlan.PruneColumns(append(fields, f...))
  49. }
  50. func (p *FilterPlan) ExtractStateFunc() {
  51. aliases := make(map[string]ast.Expr)
  52. ast.WalkFunc(p.condition, func(n ast.Node) bool {
  53. switch f := n.(type) {
  54. case *ast.Call:
  55. p.transform(f)
  56. case *ast.FieldRef:
  57. if f.AliasRef != nil {
  58. aliases[f.Name] = f.AliasRef.Expression
  59. }
  60. }
  61. return true
  62. })
  63. for _, ex := range aliases {
  64. ast.WalkFunc(ex, func(n ast.Node) bool {
  65. switch f := n.(type) {
  66. case *ast.Call:
  67. p.transform(f)
  68. }
  69. return true
  70. })
  71. }
  72. }
  73. func (p *FilterPlan) transform(f *ast.Call) {
  74. if _, ok := xsql.ImplicitStateFuncs[f.Name]; ok {
  75. f.Cached = true
  76. p.stateFuncs = append(p.stateFuncs, &ast.Call{
  77. Name: f.Name,
  78. FuncId: f.FuncId,
  79. FuncType: f.FuncType,
  80. })
  81. }
  82. }