collection.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. // Copyright 2022 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 xsql
  15. import (
  16. "github.com/lf-edge/ekuiper/pkg/ast"
  17. "sort"
  18. )
  19. /*
  20. * Collection interfaces
  21. */
  22. // AggregateData Could be a tuple or collection
  23. type AggregateData interface {
  24. AggregateEval(expr ast.Expr, v CallValuer) []interface{}
  25. }
  26. type SortingData interface {
  27. Len() int
  28. Swap(i, j int)
  29. Index(i int) Row
  30. }
  31. // Collection A collection of rows as a table. It is used for window, join, group by, etc.
  32. type Collection interface {
  33. SortingData
  34. // GroupRange through each group. For non-grouped collection, the whole data is a single group
  35. GroupRange(func(i int, aggRow CollectionRow) (bool, error)) error
  36. // Range through each row. For grouped collection, each row is an aggregation of groups
  37. Range(func(i int, r ReadonlyRow) (bool, error)) error
  38. // RangeSet range through each row by cloneing the row
  39. RangeSet(func(i int, r Row) (bool, error)) error
  40. Filter(indexes []int) Collection
  41. GetWindowRange() *WindowRange
  42. Clone() Collection
  43. // ToMaps returns the data as a map
  44. ToMaps() []map[string]interface{}
  45. }
  46. type SingleCollection interface {
  47. Collection
  48. CollectionRow
  49. SetIsAgg(isAgg bool)
  50. // ToAggMaps returns the aggregated data as a map
  51. ToAggMaps() []map[string]interface{}
  52. // ToRowMaps returns all the data in the collection
  53. ToRowMaps() []map[string]interface{}
  54. }
  55. type GroupedCollection interface {
  56. Collection
  57. }
  58. // MergedCollection is a collection of rows that are from different sources
  59. type MergedCollection interface {
  60. Collection
  61. GetBySrc(emitter string) []TupleRow
  62. }
  63. /*
  64. * Collection types definitions
  65. */
  66. type WindowTuples struct {
  67. Content []TupleRow // immutable
  68. *WindowRange
  69. contentBySrc map[string][]TupleRow // volatile, temporary cache]
  70. AffiliateRow
  71. cachedMap map[string]interface{}
  72. isAgg bool
  73. }
  74. var _ MergedCollection = &WindowTuples{}
  75. var _ SingleCollection = &WindowTuples{}
  76. // Window Tuples is also an aggregate row
  77. var _ CollectionRow = &WindowTuples{}
  78. type JoinTuples struct {
  79. Content []*JoinTuple
  80. *WindowRange
  81. AffiliateRow
  82. cachedMap map[string]interface{}
  83. isAgg bool
  84. }
  85. var _ SingleCollection = &JoinTuples{}
  86. var _ CollectionRow = &JoinTuples{}
  87. type GroupedTuplesSet struct {
  88. Groups []*GroupedTuples
  89. *WindowRange
  90. }
  91. var _ GroupedCollection = &GroupedTuplesSet{}
  92. /*
  93. * Collection implementations
  94. */
  95. func (w *WindowTuples) Index(index int) Row {
  96. return w.Content[index]
  97. }
  98. func (w *WindowTuples) Len() int {
  99. return len(w.Content)
  100. }
  101. func (w *WindowTuples) Swap(i, j int) {
  102. w.cachedMap = nil
  103. w.Content[i], w.Content[j] = w.Content[j], w.Content[i]
  104. }
  105. func (w *WindowTuples) GetBySrc(emitter string) []TupleRow {
  106. if w.contentBySrc == nil {
  107. w.contentBySrc = make(map[string][]TupleRow)
  108. for _, t := range w.Content {
  109. e := t.GetEmitter()
  110. if _, hasEmitter := w.contentBySrc[e]; !hasEmitter {
  111. w.contentBySrc[e] = make([]TupleRow, 0)
  112. }
  113. w.contentBySrc[e] = append(w.contentBySrc[e], t)
  114. }
  115. }
  116. return w.contentBySrc[emitter]
  117. }
  118. func (w *WindowTuples) GetWindowRange() *WindowRange {
  119. return w.WindowRange
  120. }
  121. func (w *WindowTuples) Range(f func(i int, r ReadonlyRow) (bool, error)) error {
  122. for i, r := range w.Content {
  123. b, e := f(i, r)
  124. if e != nil {
  125. return e
  126. }
  127. if !b {
  128. break
  129. }
  130. }
  131. return nil
  132. }
  133. func (w *WindowTuples) RangeSet(f func(i int, r Row) (bool, error)) error {
  134. for i, r := range w.Content {
  135. rc := r.Clone()
  136. b, e := f(i, rc)
  137. if e != nil {
  138. return e
  139. }
  140. if !b {
  141. break
  142. }
  143. w.Content[i] = rc
  144. }
  145. return nil
  146. }
  147. func (w *WindowTuples) GroupRange(f func(i int, aggRow CollectionRow) (bool, error)) error {
  148. _, err := f(0, w)
  149. return err
  150. }
  151. func (w *WindowTuples) AddTuple(tuple *Tuple) *WindowTuples {
  152. w.Content = append(w.Content, tuple)
  153. return w
  154. }
  155. //Sort by tuple timestamp
  156. func (w *WindowTuples) Sort() {
  157. w.cachedMap = nil
  158. sort.SliceStable(w.Content, func(i, j int) bool {
  159. return w.Content[i].(Event).GetTimestamp() < w.Content[j].(Event).GetTimestamp()
  160. })
  161. }
  162. func (w *WindowTuples) AggregateEval(expr ast.Expr, v CallValuer) []interface{} {
  163. var result []interface{}
  164. for _, t := range w.Content {
  165. result = append(result, Eval(expr, MultiValuer(t, &WindowRangeValuer{WindowRange: w.WindowRange}, v, &WildcardValuer{t})))
  166. }
  167. return result
  168. }
  169. // Filter the tuples by the given predicate
  170. func (w *WindowTuples) Filter(indexes []int) Collection {
  171. w.cachedMap = nil
  172. newC := make([]TupleRow, 0, len(indexes))
  173. for _, i := range indexes {
  174. newC = append(newC, w.Content[i])
  175. }
  176. w.Content = newC
  177. return w
  178. }
  179. func (w *WindowTuples) Value(key, table string) (interface{}, bool) {
  180. r, ok := w.AffiliateRow.Value(key, table)
  181. if ok {
  182. return r, ok
  183. }
  184. return w.Content[0].Value(key, table)
  185. }
  186. func (w *WindowTuples) Meta(key, table string) (interface{}, bool) {
  187. return w.Content[0].Meta(key, table)
  188. }
  189. func (w *WindowTuples) All(_ string) (Message, bool) {
  190. return w.ToMap(), true
  191. }
  192. func (w *WindowTuples) ToMap() map[string]interface{} {
  193. if w.cachedMap == nil {
  194. m := make(map[string]interface{})
  195. for k, v := range w.Content[0].ToMap() {
  196. m[k] = v
  197. }
  198. w.cachedMap = m
  199. }
  200. w.AffiliateRow.MergeMap(w.cachedMap)
  201. return w.cachedMap
  202. }
  203. func (w *WindowTuples) Clone() Collection {
  204. ts := make([]TupleRow, len(w.Content))
  205. for i, t := range w.Content {
  206. ts[i] = t.Clone()
  207. }
  208. c := &WindowTuples{
  209. Content: ts,
  210. WindowRange: w.WindowRange,
  211. AffiliateRow: w.AffiliateRow.Clone(),
  212. isAgg: w.isAgg,
  213. }
  214. return c
  215. }
  216. func (w *WindowTuples) ToAggMaps() []map[string]interface{} {
  217. return []map[string]interface{}{w.ToMap()}
  218. }
  219. func (w *WindowTuples) ToRowMaps() []map[string]interface{} {
  220. r := make([]map[string]interface{}, len(w.Content))
  221. for i, t := range w.Content {
  222. r[i] = t.ToMap()
  223. }
  224. return r
  225. }
  226. func (w *WindowTuples) ToMaps() []map[string]interface{} {
  227. if w.isAgg {
  228. return w.ToAggMaps()
  229. } else {
  230. return w.ToRowMaps()
  231. }
  232. }
  233. func (w *WindowTuples) Pick(allWildcard bool, cols [][]string, wildcardEmitters map[string]bool) {
  234. cols = w.AffiliateRow.Pick(cols)
  235. for i, t := range w.Content {
  236. tc := t.Clone()
  237. tc.Pick(allWildcard, cols, wildcardEmitters)
  238. w.Content[i] = tc
  239. }
  240. }
  241. func (w *WindowTuples) SetIsAgg(_ bool) {
  242. w.isAgg = true
  243. }
  244. func (s *JoinTuples) Len() int { return len(s.Content) }
  245. func (s *JoinTuples) Swap(i, j int) {
  246. s.cachedMap = nil
  247. s.Content[i], s.Content[j] = s.Content[j], s.Content[i]
  248. }
  249. func (s *JoinTuples) Index(i int) Row { return s.Content[i] }
  250. func (s *JoinTuples) AggregateEval(expr ast.Expr, v CallValuer) []interface{} {
  251. var result []interface{}
  252. for _, t := range s.Content {
  253. result = append(result, Eval(expr, MultiValuer(t, &WindowRangeValuer{WindowRange: s.WindowRange}, v, &WildcardValuer{t})))
  254. }
  255. return result
  256. }
  257. func (s *JoinTuples) GetWindowRange() *WindowRange {
  258. return s.WindowRange
  259. }
  260. func (s *JoinTuples) Range(f func(i int, r ReadonlyRow) (bool, error)) error {
  261. for i, r := range s.Content {
  262. b, e := f(i, r)
  263. if e != nil {
  264. return e
  265. }
  266. if !b {
  267. break
  268. }
  269. }
  270. return nil
  271. }
  272. func (s *JoinTuples) RangeSet(f func(i int, r Row) (bool, error)) error {
  273. for i, r := range s.Content {
  274. rc := r.Clone()
  275. b, e := f(i, rc)
  276. if e != nil {
  277. return e
  278. }
  279. if !b {
  280. break
  281. }
  282. s.Content[i] = rc.(*JoinTuple)
  283. }
  284. return nil
  285. }
  286. func (s *JoinTuples) GroupRange(f func(i int, aggRow CollectionRow) (bool, error)) error {
  287. _, err := f(0, s)
  288. return err
  289. }
  290. // Filter the tuples by the given predicate
  291. func (s *JoinTuples) Filter(indexes []int) Collection {
  292. newC := make([]*JoinTuple, 0, len(indexes))
  293. for _, i := range indexes {
  294. newC = append(newC, s.Content[i])
  295. }
  296. s.Content = newC
  297. s.cachedMap = nil
  298. return s
  299. }
  300. func (s *JoinTuples) Value(key, table string) (interface{}, bool) {
  301. r, ok := s.AffiliateRow.Value(key, table)
  302. if ok {
  303. return r, ok
  304. }
  305. return s.Content[0].Value(key, table)
  306. }
  307. func (s *JoinTuples) Meta(key, table string) (interface{}, bool) {
  308. return s.Content[0].Meta(key, table)
  309. }
  310. func (s *JoinTuples) All(_ string) (Message, bool) {
  311. return s.ToMap(), true
  312. }
  313. func (s *JoinTuples) ToMap() map[string]interface{} {
  314. if s.cachedMap == nil {
  315. m := make(map[string]interface{})
  316. for k, v := range s.Content[0].ToMap() {
  317. m[k] = v
  318. }
  319. s.cachedMap = m
  320. }
  321. s.AffiliateRow.MergeMap(s.cachedMap)
  322. return s.cachedMap
  323. }
  324. func (s *JoinTuples) Clone() Collection {
  325. ts := make([]*JoinTuple, len(s.Content))
  326. for i, t := range s.Content {
  327. ts[i] = t.Clone().(*JoinTuple)
  328. }
  329. c := &JoinTuples{
  330. Content: ts,
  331. WindowRange: s.WindowRange,
  332. AffiliateRow: s.AffiliateRow.Clone(),
  333. isAgg: s.isAgg,
  334. }
  335. return c
  336. }
  337. func (s *JoinTuples) ToAggMaps() []map[string]interface{} {
  338. return []map[string]interface{}{s.ToMap()}
  339. }
  340. func (s *JoinTuples) ToRowMaps() []map[string]interface{} {
  341. r := make([]map[string]interface{}, len(s.Content))
  342. for i, t := range s.Content {
  343. r[i] = t.ToMap()
  344. }
  345. return r
  346. }
  347. func (s *JoinTuples) ToMaps() []map[string]interface{} {
  348. if s.isAgg {
  349. return s.ToAggMaps()
  350. } else {
  351. return s.ToRowMaps()
  352. }
  353. }
  354. func (s *JoinTuples) Pick(allWildcard bool, cols [][]string, wildcardEmitters map[string]bool) {
  355. cols = s.AffiliateRow.Pick(cols)
  356. for i, t := range s.Content {
  357. tc := t.Clone().(*JoinTuple)
  358. tc.Pick(allWildcard, cols, wildcardEmitters)
  359. s.Content[i] = tc
  360. }
  361. }
  362. func (s *JoinTuples) SetIsAgg(_ bool) {
  363. s.isAgg = true
  364. }
  365. func (s *GroupedTuplesSet) Len() int { return len(s.Groups) }
  366. func (s *GroupedTuplesSet) Swap(i, j int) { s.Groups[i], s.Groups[j] = s.Groups[j], s.Groups[i] }
  367. func (s *GroupedTuplesSet) Index(i int) Row { return s.Groups[i] }
  368. func (s *GroupedTuplesSet) GetWindowRange() *WindowRange {
  369. return s.WindowRange
  370. }
  371. func (s *GroupedTuplesSet) Range(f func(i int, r ReadonlyRow) (bool, error)) error {
  372. for i, r := range s.Groups {
  373. b, e := f(i, r)
  374. if e != nil {
  375. return e
  376. }
  377. if !b {
  378. break
  379. }
  380. }
  381. return nil
  382. }
  383. func (s *GroupedTuplesSet) RangeSet(f func(i int, r Row) (bool, error)) error {
  384. for i, r := range s.Groups {
  385. rc := r.Clone()
  386. b, e := f(i, rc)
  387. if e != nil {
  388. return e
  389. }
  390. if !b {
  391. break
  392. }
  393. s.Groups[i] = rc.(*GroupedTuples)
  394. }
  395. return nil
  396. }
  397. func (s *GroupedTuplesSet) GroupRange(f func(i int, aggRow CollectionRow) (bool, error)) error {
  398. for i, r := range s.Groups {
  399. b, e := f(i, r)
  400. if e != nil {
  401. return e
  402. }
  403. if !b {
  404. break
  405. }
  406. }
  407. return nil
  408. }
  409. // Filter clone and return the filtered set
  410. func (s *GroupedTuplesSet) Filter(groups []int) Collection {
  411. newC := make([]*GroupedTuples, 0, len(groups))
  412. for _, i := range groups {
  413. newC = append(newC, s.Groups[i])
  414. }
  415. s.Groups = newC
  416. return s
  417. }
  418. func (s *GroupedTuplesSet) Clone() Collection {
  419. ng := make([]*GroupedTuples, len(s.Groups))
  420. for i, g := range s.Groups {
  421. ng[i] = g.Clone().(*GroupedTuples)
  422. }
  423. return &GroupedTuplesSet{
  424. Groups: ng,
  425. WindowRange: s.WindowRange,
  426. }
  427. }
  428. func (s *GroupedTuplesSet) ToMaps() []map[string]interface{} {
  429. r := make([]map[string]interface{}, len(s.Groups))
  430. for i, t := range s.Groups {
  431. r[i] = t.ToMap()
  432. }
  433. return r
  434. }
  435. /*
  436. * WindowRange definitions. It should be immutable
  437. */
  438. type WindowRangeValuer struct {
  439. *WindowRange
  440. }
  441. func (w WindowRangeValuer) Value(_, _ string) (interface{}, bool) {
  442. return nil, false
  443. }
  444. func (w WindowRangeValuer) Meta(_, _ string) (interface{}, bool) {
  445. return nil, false
  446. }
  447. type WindowRange struct {
  448. windowStart int64
  449. windowEnd int64
  450. }
  451. func NewWindowRange(windowStart int64, windowEnd int64) *WindowRange {
  452. return &WindowRange{windowStart, windowEnd}
  453. }
  454. func (r *WindowRange) FuncValue(key string) (interface{}, bool) {
  455. switch key {
  456. case "window_start":
  457. return r.windowStart, true
  458. case "window_end":
  459. return r.windowEnd, true
  460. default:
  461. return nil, false
  462. }
  463. }