project_operator.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. if pp.EnableLimit && pp.LimitCount > 0 && input.Len() > pp.LimitCount {
  74. var sel []int
  75. sel = make([]int, pp.LimitCount, pp.LimitCount)
  76. for i := 0; i < pp.LimitCount; i++ {
  77. sel[i] = i
  78. }
  79. input = input.Filter(sel).(xsql.SingleCollection)
  80. }
  81. } else {
  82. if pp.EnableLimit && pp.LimitCount > 0 && input.Len() > pp.LimitCount {
  83. var sel []int
  84. sel = make([]int, pp.LimitCount, pp.LimitCount)
  85. for i := 0; i < pp.LimitCount; i++ {
  86. sel[i] = i
  87. }
  88. input = input.Filter(sel).(xsql.SingleCollection)
  89. }
  90. err = input.RangeSet(func(_ int, row xsql.Row) (bool, error) {
  91. aggData, ok := input.(xsql.AggregateData)
  92. if !ok {
  93. return false, fmt.Errorf("unexpected type, cannot find aggregate data")
  94. }
  95. ve := pp.getVE(row, aggData, input.GetWindowRange(), fv, afv)
  96. if err := pp.project(row, ve); err != nil {
  97. return false, fmt.Errorf("run Select error: %s", err)
  98. }
  99. return true, nil
  100. })
  101. }
  102. if err != nil {
  103. return err
  104. }
  105. case xsql.GroupedCollection: // The order is important, because single collection usually is also a groupedCollection
  106. if pp.EnableLimit && pp.LimitCount > 0 && input.Len() > pp.LimitCount {
  107. var sel []int
  108. sel = make([]int, pp.LimitCount, pp.LimitCount)
  109. for i := 0; i < pp.LimitCount; i++ {
  110. sel[i] = i
  111. }
  112. input = input.Filter(sel).(xsql.GroupedCollection)
  113. }
  114. err := input.GroupRange(func(_ int, aggRow xsql.CollectionRow) (bool, error) {
  115. ve := pp.getVE(aggRow, aggRow, input.GetWindowRange(), fv, afv)
  116. if err := pp.project(aggRow, ve); err != nil {
  117. return false, fmt.Errorf("run Select error: %s", err)
  118. }
  119. return true, nil
  120. })
  121. if err != nil {
  122. return err
  123. }
  124. default:
  125. return fmt.Errorf("run Select error: invalid input %[1]T(%[1]v)", input)
  126. }
  127. return data
  128. }
  129. func (pp *ProjectOp) getVE(tuple xsql.Row, agg xsql.AggregateData, wr *xsql.WindowRange, fv *xsql.FunctionValuer, afv *xsql.AggregateFunctionValuer) *xsql.ValuerEval {
  130. afv.SetData(agg)
  131. if pp.IsAggregate {
  132. return &xsql.ValuerEval{Valuer: xsql.MultiAggregateValuer(agg, fv, tuple, fv, afv, &xsql.WildcardValuer{Data: tuple})}
  133. } else {
  134. if wr != nil {
  135. return &xsql.ValuerEval{Valuer: xsql.MultiValuer(tuple, &xsql.WindowRangeValuer{WindowRange: wr}, fv, &xsql.WildcardValuer{Data: tuple})}
  136. }
  137. return &xsql.ValuerEval{Valuer: xsql.MultiValuer(tuple, fv, &xsql.WildcardValuer{Data: tuple})}
  138. }
  139. }
  140. func (pp *ProjectOp) project(row xsql.Row, ve *xsql.ValuerEval) error {
  141. // Calculate all fields then pick the needed ones
  142. // To make sure all calculations are run with the same context (e.g. alias values)
  143. // Do not set value during calculations
  144. for _, f := range pp.ExprFields {
  145. vi := ve.Eval(f.Expr)
  146. if e, ok := vi.(error); ok {
  147. return e
  148. }
  149. if vi != nil {
  150. switch vt := vi.(type) {
  151. case function.ResultCols:
  152. for k, v := range vt {
  153. pp.kvs = append(pp.kvs, k, v)
  154. }
  155. default:
  156. pp.kvs = append(pp.kvs, f.Name, vi)
  157. }
  158. }
  159. }
  160. for _, f := range pp.AliasFields {
  161. vi := ve.Eval(f.Expr)
  162. if e, ok := vi.(error); ok {
  163. return e
  164. }
  165. if vi != nil {
  166. pp.alias = append(pp.alias, f.AName, vi)
  167. }
  168. }
  169. row.Pick(pp.AllWildcard, pp.ColNames, pp.WildcardEmitters, pp.ExceptNames)
  170. for i := 0; i < len(pp.kvs); i += 2 {
  171. row.Set(pp.kvs[i].(string), pp.kvs[i+1])
  172. }
  173. pp.kvs = pp.kvs[:0]
  174. for i := 0; i < len(pp.alias); i += 2 {
  175. row.AppendAlias(pp.alias[i].(string), pp.alias[i+1])
  176. }
  177. pp.alias = pp.alias[:0]
  178. return nil
  179. }