collection.go 12 KB

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