project_operator.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // Copyright 2022-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/binder/function"
  18. "github.com/lf-edge/ekuiper/internal/xsql"
  19. "github.com/lf-edge/ekuiper/pkg/api"
  20. "github.com/lf-edge/ekuiper/pkg/ast"
  21. "github.com/lf-edge/ekuiper/pkg/message"
  22. )
  23. type ProjectOp struct {
  24. ColNames [][]string // list of [col, table]
  25. AliasNames []string // list of alias name
  26. ExprNames []string // list of expr name
  27. ExceptNames []string // list of except name
  28. AllWildcard bool
  29. WildcardEmitters map[string]bool
  30. AliasFields ast.Fields
  31. ExprFields ast.Fields
  32. IsAggregate bool
  33. EnableLimit bool
  34. LimitCount int
  35. SendMeta bool
  36. kvs []interface{}
  37. alias []interface{}
  38. }
  39. // Apply
  40. //
  41. // input: *xsql.Tuple| xsql.Collection
  42. //
  43. // output: []map[string]interface{}
  44. func (pp *ProjectOp) Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, afv *xsql.AggregateFunctionValuer) interface{} {
  45. log := ctx.GetLogger()
  46. log.Debugf("project plan receive %v", data)
  47. if pp.LimitCount == 0 && pp.EnableLimit {
  48. return []xsql.TupleRow{}
  49. }
  50. switch input := data.(type) {
  51. case error:
  52. return input
  53. case *xsql.Tuple:
  54. ve := pp.getVE(input, input, nil, fv, afv)
  55. if err := pp.project(input, ve); err != nil {
  56. return fmt.Errorf("run Select error: %s", err)
  57. } else {
  58. if pp.SendMeta && input.Metadata != nil {
  59. input.Set(message.MetaKey, input.Metadata)
  60. }
  61. }
  62. case xsql.SingleCollection:
  63. var err error
  64. if pp.IsAggregate {
  65. input.SetIsAgg(true)
  66. err = input.GroupRange(func(_ int, aggRow xsql.CollectionRow) (bool, error) {
  67. ve := pp.getVE(aggRow, aggRow, input.GetWindowRange(), fv, afv)
  68. if err := pp.project(aggRow, ve); err != nil {
  69. return false, fmt.Errorf("run Select error: %s", err)
  70. }
  71. return true, nil
  72. })
  73. } else {
  74. err = input.RangeSet(func(_ int, row xsql.Row) (bool, error) {
  75. aggData, ok := input.(xsql.AggregateData)
  76. if !ok {
  77. return false, fmt.Errorf("unexpected type, cannot find aggregate data")
  78. }
  79. ve := pp.getVE(row, aggData, input.GetWindowRange(), fv, afv)
  80. if err := pp.project(row, ve); err != nil {
  81. return false, fmt.Errorf("run Select error: %s", err)
  82. }
  83. return true, nil
  84. })
  85. }
  86. if err != nil {
  87. return err
  88. }
  89. if pp.EnableLimit && pp.LimitCount > 0 && input.Len() > pp.LimitCount {
  90. var sel []int
  91. sel = make([]int, pp.LimitCount, pp.LimitCount)
  92. for i := 0; i < pp.LimitCount; i++ {
  93. sel[i] = i
  94. }
  95. return input.Filter(sel)
  96. }
  97. case xsql.GroupedCollection: // The order is important, because single collection usually is also a groupedCollection
  98. err := input.GroupRange(func(_ int, aggRow xsql.CollectionRow) (bool, error) {
  99. ve := pp.getVE(aggRow, aggRow, input.GetWindowRange(), fv, afv)
  100. if err := pp.project(aggRow, ve); err != nil {
  101. return false, fmt.Errorf("run Select error: %s", err)
  102. }
  103. return true, nil
  104. })
  105. if err != nil {
  106. return err
  107. }
  108. if pp.EnableLimit && pp.LimitCount > 0 && input.Len() > pp.LimitCount {
  109. var sel []int
  110. sel = make([]int, pp.LimitCount, pp.LimitCount)
  111. for i := 0; i < pp.LimitCount; i++ {
  112. sel[i] = i
  113. }
  114. return input.Filter(sel)
  115. }
  116. default:
  117. return fmt.Errorf("run Select error: invalid input %[1]T(%[1]v)", input)
  118. }
  119. return data
  120. }
  121. func (pp *ProjectOp) getVE(tuple xsql.Row, agg xsql.AggregateData, wr *xsql.WindowRange, fv *xsql.FunctionValuer, afv *xsql.AggregateFunctionValuer) *xsql.ValuerEval {
  122. afv.SetData(agg)
  123. if pp.IsAggregate {
  124. return &xsql.ValuerEval{Valuer: xsql.MultiAggregateValuer(agg, fv, tuple, fv, afv, &xsql.WildcardValuer{Data: tuple})}
  125. } else {
  126. if wr != nil {
  127. return &xsql.ValuerEval{Valuer: xsql.MultiValuer(tuple, &xsql.WindowRangeValuer{WindowRange: wr}, fv, &xsql.WildcardValuer{Data: tuple})}
  128. }
  129. return &xsql.ValuerEval{Valuer: xsql.MultiValuer(tuple, fv, &xsql.WildcardValuer{Data: tuple})}
  130. }
  131. }
  132. func (pp *ProjectOp) project(row xsql.Row, ve *xsql.ValuerEval) error {
  133. // Calculate all fields then pick the needed ones
  134. // To make sure all calculations are run with the same context (e.g. alias values)
  135. // Do not set value during calculations
  136. for _, f := range pp.ExprFields {
  137. vi := ve.Eval(f.Expr)
  138. if e, ok := vi.(error); ok {
  139. return e
  140. }
  141. if vi != nil {
  142. switch vt := vi.(type) {
  143. case function.ResultCols:
  144. for k, v := range vt {
  145. pp.kvs = append(pp.kvs, k, v)
  146. }
  147. default:
  148. pp.kvs = append(pp.kvs, f.Name, vi)
  149. }
  150. }
  151. }
  152. for _, f := range pp.AliasFields {
  153. vi := ve.Eval(f.Expr)
  154. if e, ok := vi.(error); ok {
  155. return e
  156. }
  157. if vi != nil {
  158. pp.alias = append(pp.alias, f.AName, vi)
  159. }
  160. }
  161. row.Pick(pp.AllWildcard, pp.ColNames, pp.WildcardEmitters, pp.ExceptNames)
  162. for i := 0; i < len(pp.kvs); i += 2 {
  163. row.Set(pp.kvs[i].(string), pp.kvs[i+1])
  164. }
  165. pp.kvs = pp.kvs[:0]
  166. for i := 0; i < len(pp.alias); i += 2 {
  167. row.AppendAlias(pp.alias[i].(string), pp.alias[i+1])
  168. }
  169. pp.alias = pp.alias[:0]
  170. return nil
  171. }