project_operator.go 6.1 KB

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