row.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. "github.com/lf-edge/ekuiper/internal/conf"
  17. "github.com/lf-edge/ekuiper/pkg/ast"
  18. "strings"
  19. "sync"
  20. )
  21. // The original message map may be big. Make sure it is immutable so that never make a copy of it.
  22. // The tuple clone should be cheap.
  23. /*
  24. * Interfaces definition
  25. */
  26. type Wildcarder interface {
  27. // All Value returns the value and existence flag for a given key.
  28. All(stream string) (Message, bool)
  29. }
  30. type Event interface {
  31. GetTimestamp() int64
  32. IsWatermark() bool
  33. }
  34. type ReadonlyRow interface {
  35. Valuer
  36. AliasValuer
  37. Wildcarder
  38. }
  39. type Row interface {
  40. ReadonlyRow
  41. // Del Only for some ops like functionOp * and Alias
  42. Del(col string)
  43. // Set Only for some ops like functionOp *
  44. Set(col string, value interface{})
  45. // ToMap converts the row to a map to export to other systems *
  46. ToMap() map[string]interface{}
  47. // Pick the columns and discard others. It replaces the underlying message with a new value. There are 3 types to pick: column, alias and annonymous expressions.
  48. // cols is a list [columnname, tablename]
  49. Pick(allWildcard bool, cols [][]string, wildcardEmitters map[string]bool)
  50. }
  51. // TupleRow is a mutable row. Function with * could modify the row.
  52. type TupleRow interface {
  53. Row
  54. // GetEmitter returns the emitter of the row
  55. GetEmitter() string
  56. // Clone when broadcast to make sure each row are dealt single threaded
  57. Clone() TupleRow
  58. }
  59. // CollectionRow is the aggregation row of a non-grouped collection. Thinks of it as a single group.
  60. // The row data is immutable
  61. type CollectionRow interface {
  62. Row
  63. AggregateData
  64. // Clone when broadcast to make sure each row are dealt single threaded
  65. //Clone() CollectionRow
  66. }
  67. // AffiliateRow part of other row types do help calculation of newly added cols
  68. type AffiliateRow struct {
  69. lock sync.RWMutex
  70. CalCols map[string]interface{} // mutable and must be cloned when broadcast
  71. AliasMap map[string]interface{}
  72. }
  73. func (d *AffiliateRow) AppendAlias(key string, value interface{}) bool {
  74. d.lock.Lock()
  75. defer d.lock.Unlock()
  76. if d.AliasMap == nil {
  77. d.AliasMap = make(map[string]interface{})
  78. }
  79. d.AliasMap[key] = value
  80. return true
  81. }
  82. func (d *AffiliateRow) AliasValue(key string) (interface{}, bool) {
  83. d.lock.RLock()
  84. defer d.lock.RUnlock()
  85. if d.AliasMap == nil {
  86. return nil, false
  87. }
  88. v, ok := d.AliasMap[key]
  89. return v, ok
  90. }
  91. func (d *AffiliateRow) Value(key, table string) (interface{}, bool) {
  92. d.lock.RLock()
  93. defer d.lock.RUnlock()
  94. if table == "" {
  95. r, ok := d.AliasValue(key)
  96. if ok {
  97. return r, ok
  98. }
  99. r, ok = d.CalCols[key]
  100. if ok {
  101. return r, ok
  102. }
  103. }
  104. return nil, false
  105. }
  106. func (d *AffiliateRow) Set(col string, value interface{}) {
  107. d.lock.Lock()
  108. defer d.lock.Unlock()
  109. if d.CalCols == nil {
  110. d.CalCols = make(map[string]interface{})
  111. }
  112. d.CalCols[col] = value
  113. }
  114. func (d *AffiliateRow) Del(col string) {
  115. d.lock.Lock()
  116. defer d.lock.Unlock()
  117. if d.CalCols != nil {
  118. delete(d.CalCols, col)
  119. }
  120. if d.AliasMap != nil {
  121. delete(d.AliasMap, col)
  122. }
  123. }
  124. func (d *AffiliateRow) Clone() AffiliateRow {
  125. d.lock.RLock()
  126. defer d.lock.RUnlock()
  127. nd := &AffiliateRow{}
  128. if d.CalCols != nil && len(d.CalCols) > 0 {
  129. nd.CalCols = make(map[string]interface{}, len(d.CalCols))
  130. for k, v := range d.CalCols {
  131. nd.CalCols[k] = v
  132. }
  133. }
  134. if d.AliasMap != nil && len(d.AliasMap) > 0 {
  135. nd.AliasMap = make(map[string]interface{}, len(d.AliasMap))
  136. for k, v := range d.AliasMap {
  137. nd.AliasMap[k] = v
  138. }
  139. }
  140. return *nd
  141. }
  142. func (d *AffiliateRow) IsEmpty() bool {
  143. d.lock.RLock()
  144. defer d.lock.RUnlock()
  145. return len(d.CalCols) == 0 && len(d.AliasMap) == 0
  146. }
  147. func (d *AffiliateRow) MergeMap(cachedMap map[string]interface{}) {
  148. d.lock.RLock()
  149. defer d.lock.RUnlock()
  150. for k, v := range d.CalCols {
  151. // Do not write out the internal fields
  152. if !strings.HasPrefix(k, "$$") {
  153. cachedMap[k] = v
  154. }
  155. }
  156. for k, v := range d.AliasMap {
  157. cachedMap[k] = v
  158. }
  159. }
  160. func (d *AffiliateRow) Pick(cols [][]string) [][]string {
  161. d.lock.Lock()
  162. defer d.lock.Unlock()
  163. if len(cols) > 0 {
  164. newAliasMap := make(map[string]interface{})
  165. newCalCols := make(map[string]interface{})
  166. var newCols [][]string
  167. for _, a := range cols {
  168. if a[1] == "" || a[1] == string(ast.DefaultStream) {
  169. if v, ok := d.AliasMap[a[0]]; ok {
  170. newAliasMap[a[0]] = v
  171. continue
  172. }
  173. if v, ok := d.CalCols[a[0]]; ok {
  174. newCalCols[a[0]] = v
  175. continue
  176. }
  177. }
  178. newCols = append(newCols, a)
  179. }
  180. d.AliasMap = newAliasMap
  181. d.CalCols = newCalCols
  182. return newCols
  183. } else {
  184. d.AliasMap = nil
  185. d.CalCols = nil
  186. return cols
  187. }
  188. }
  189. /*
  190. * Message definition
  191. */
  192. // Message is a valuer that substitutes values for the mapped interface. It is the basic type for data events.
  193. type Message map[string]interface{}
  194. var _ Valuer = Message{}
  195. type Metadata Message
  196. // Alias will not need to convert cases
  197. type Alias struct {
  198. AliasMap map[string]interface{}
  199. }
  200. /*
  201. * All row types definitions, watermark, barrier
  202. */
  203. // Tuple The input row, produced by the source
  204. type Tuple struct {
  205. Emitter string
  206. Message Message // the original pointer is immutable & big; may be cloned
  207. Timestamp int64
  208. Metadata Metadata // immutable
  209. AffiliateRow
  210. lock sync.Mutex // lock for the cachedMap, because it is possible to access by multiple sinks
  211. cachedMap map[string]interface{} // clone of the row and cached for performance
  212. }
  213. var _ TupleRow = &Tuple{}
  214. // JoinTuple is a row produced by a join operation
  215. type JoinTuple struct {
  216. Tuples []TupleRow // The content is immutable, but the slice may be add or removed
  217. AffiliateRow
  218. lock sync.Mutex
  219. cachedMap map[string]interface{} // clone of the row and cached for performance of toMap
  220. }
  221. func (jt *JoinTuple) AggregateEval(expr ast.Expr, v CallValuer) []interface{} {
  222. return []interface{}{Eval(expr, MultiValuer(jt, v, &WildcardValuer{jt}))}
  223. }
  224. var _ TupleRow = &JoinTuple{}
  225. // GroupedTuples is a collection of tuples grouped by a key
  226. type GroupedTuples struct {
  227. Content []TupleRow
  228. *WindowRange
  229. AffiliateRow
  230. lock sync.Mutex
  231. cachedMap map[string]interface{} // clone of the row and cached for performance of toMap
  232. }
  233. var _ CollectionRow = &GroupedTuples{}
  234. /*
  235. * Implementations
  236. */
  237. func ToMessage(input interface{}) (Message, bool) {
  238. var result Message
  239. switch m := input.(type) {
  240. case Message:
  241. result = m
  242. case Metadata:
  243. result = Message(m)
  244. case map[string]interface{}:
  245. result = m
  246. default:
  247. return nil, false
  248. }
  249. return result, true
  250. }
  251. func (m Message) Value(key, _ string) (interface{}, bool) {
  252. if v, ok := m[key]; ok {
  253. return v, ok
  254. } else if conf.Config == nil || conf.Config.Basic.IgnoreCase {
  255. //Only when with 'SELECT * FROM ...' and 'schemaless', the key in map is not convert to lower case.
  256. //So all of keys in map should be convert to lowercase and then compare them.
  257. return m.getIgnoreCase(key)
  258. } else {
  259. return nil, false
  260. }
  261. }
  262. func (m Message) getIgnoreCase(key interface{}) (interface{}, bool) {
  263. if k, ok := key.(string); ok {
  264. for mk, v := range m {
  265. if strings.EqualFold(k, mk) {
  266. return v, true
  267. }
  268. }
  269. }
  270. return nil, false
  271. }
  272. func (m Message) Meta(key, table string) (interface{}, bool) {
  273. if key == "*" {
  274. return map[string]interface{}(m), true
  275. }
  276. return m.Value(key, table)
  277. }
  278. // MetaData implementation
  279. func (m Metadata) Value(key, table string) (interface{}, bool) {
  280. msg := Message(m)
  281. return msg.Value(key, table)
  282. }
  283. func (m Metadata) Meta(key, table string) (interface{}, bool) {
  284. if key == "*" {
  285. return map[string]interface{}(m), true
  286. }
  287. msg := Message(m)
  288. return msg.Meta(key, table)
  289. }
  290. // Tuple implementation
  291. func (t *Tuple) Value(key, table string) (interface{}, bool) {
  292. r, ok := t.AffiliateRow.Value(key, table)
  293. if ok {
  294. return r, ok
  295. }
  296. return t.Message.Value(key, table)
  297. }
  298. func (t *Tuple) All(string) (Message, bool) {
  299. return t.ToMap(), true
  300. }
  301. func (t *Tuple) Clone() TupleRow {
  302. return &Tuple{
  303. Emitter: t.Emitter,
  304. Timestamp: t.Timestamp,
  305. Message: t.Message,
  306. Metadata: t.Metadata,
  307. AffiliateRow: t.AffiliateRow.Clone(),
  308. }
  309. }
  310. // ToMap should only use in sink.
  311. func (t *Tuple) ToMap() map[string]interface{} {
  312. t.lock.Lock()
  313. defer t.lock.Unlock()
  314. if t.AffiliateRow.IsEmpty() {
  315. return t.Message
  316. }
  317. if t.cachedMap == nil { // clone the message
  318. m := make(map[string]interface{})
  319. for k, v := range t.Message {
  320. m[k] = v
  321. }
  322. t.cachedMap = m
  323. t.AffiliateRow.MergeMap(t.cachedMap)
  324. }
  325. return t.cachedMap
  326. }
  327. func (t *Tuple) Meta(key, table string) (interface{}, bool) {
  328. if key == "*" {
  329. return map[string]interface{}(t.Metadata), true
  330. }
  331. return t.Metadata.Value(key, table)
  332. }
  333. func (t *Tuple) GetEmitter() string {
  334. return t.Emitter
  335. }
  336. func (t *Tuple) AggregateEval(expr ast.Expr, v CallValuer) []interface{} {
  337. return []interface{}{Eval(expr, MultiValuer(t, v, &WildcardValuer{t}))}
  338. }
  339. func (t *Tuple) GetTimestamp() int64 {
  340. return t.Timestamp
  341. }
  342. func (t *Tuple) IsWatermark() bool {
  343. return false
  344. }
  345. func (t *Tuple) Pick(allWildcard bool, cols [][]string, wildcardEmitters map[string]bool) {
  346. cols = t.AffiliateRow.Pick(cols)
  347. if !allWildcard && wildcardEmitters[t.Emitter] {
  348. allWildcard = true
  349. }
  350. if !allWildcard {
  351. if len(cols) > 0 {
  352. pickedMap := make(map[string]interface{})
  353. for _, colTab := range cols {
  354. if colTab[1] == "" || colTab[1] == string(ast.DefaultStream) || colTab[1] == t.Emitter {
  355. if v, ok := t.Message.Value(colTab[0], colTab[1]); ok {
  356. pickedMap[colTab[0]] = v
  357. }
  358. }
  359. }
  360. t.Message = pickedMap
  361. } else {
  362. t.Message = make(map[string]interface{})
  363. // invalidate cache, will calculate again
  364. t.cachedMap = nil
  365. }
  366. }
  367. }
  368. // JoinTuple implementation
  369. func (jt *JoinTuple) AddTuple(tuple TupleRow) {
  370. jt.Tuples = append(jt.Tuples, tuple)
  371. }
  372. func (jt *JoinTuple) AddTuples(tuples []TupleRow) {
  373. for _, t := range tuples {
  374. jt.Tuples = append(jt.Tuples, t)
  375. }
  376. }
  377. func (jt *JoinTuple) doGetValue(key, table string, isVal bool) (interface{}, bool) {
  378. tuples := jt.Tuples
  379. if table == "" {
  380. if len(tuples) > 1 {
  381. for _, tuple := range tuples { //TODO support key without modifier?
  382. v, ok := getTupleValue(tuple, key, isVal)
  383. if ok {
  384. return v, ok
  385. }
  386. }
  387. conf.Log.Debugf("Wrong key: %s not found", key)
  388. return nil, false
  389. } else {
  390. return getTupleValue(tuples[0], key, isVal)
  391. }
  392. } else {
  393. //TODO should use hash here
  394. for _, tuple := range tuples {
  395. if tuple.GetEmitter() == table {
  396. return getTupleValue(tuple, key, isVal)
  397. }
  398. }
  399. return nil, false
  400. }
  401. }
  402. func getTupleValue(tuple Row, key string, isVal bool) (interface{}, bool) {
  403. if isVal {
  404. return tuple.Value(key, "")
  405. } else {
  406. return tuple.Meta(key, "")
  407. }
  408. }
  409. func (jt *JoinTuple) GetEmitter() string {
  410. return "$$JOIN"
  411. }
  412. func (jt *JoinTuple) Value(key, table string) (interface{}, bool) {
  413. r, ok := jt.AffiliateRow.Value(key, table)
  414. if ok {
  415. return r, ok
  416. }
  417. return jt.doGetValue(key, table, true)
  418. }
  419. func (jt *JoinTuple) Meta(key, table string) (interface{}, bool) {
  420. return jt.doGetValue(key, table, false)
  421. }
  422. func (jt *JoinTuple) All(stream string) (Message, bool) {
  423. if stream != "" {
  424. for _, t := range jt.Tuples {
  425. if t.GetEmitter() == stream {
  426. return t.ToMap(), true
  427. }
  428. }
  429. } else {
  430. return jt.ToMap(), true
  431. }
  432. return nil, false
  433. }
  434. func (jt *JoinTuple) Clone() TupleRow {
  435. ts := make([]TupleRow, len(jt.Tuples))
  436. for i, t := range jt.Tuples {
  437. ts[i] = t.Clone()
  438. }
  439. c := &JoinTuple{
  440. Tuples: ts,
  441. AffiliateRow: jt.AffiliateRow.Clone(),
  442. }
  443. return c
  444. }
  445. func (jt *JoinTuple) ToMap() map[string]interface{} {
  446. jt.lock.Lock()
  447. defer jt.lock.Unlock()
  448. if jt.cachedMap == nil { // clone the message
  449. m := make(map[string]interface{})
  450. for i := len(jt.Tuples) - 1; i >= 0; i-- {
  451. for k, v := range jt.Tuples[i].ToMap() {
  452. m[k] = v
  453. }
  454. }
  455. jt.cachedMap = m
  456. jt.AffiliateRow.MergeMap(jt.cachedMap)
  457. }
  458. return jt.cachedMap
  459. }
  460. func (jt *JoinTuple) Pick(allWildcard bool, cols [][]string, wildcardEmitters map[string]bool) {
  461. cols = jt.AffiliateRow.Pick(cols)
  462. if !allWildcard {
  463. if len(cols) > 0 {
  464. for i, tuple := range jt.Tuples {
  465. if _, ok := wildcardEmitters[tuple.GetEmitter()]; ok {
  466. continue
  467. }
  468. nt := tuple.Clone()
  469. nt.Pick(allWildcard, cols, wildcardEmitters)
  470. jt.Tuples[i] = nt
  471. }
  472. } else {
  473. jt.Tuples = jt.Tuples[:0]
  474. }
  475. }
  476. jt.cachedMap = nil
  477. }
  478. // GroupedTuple implementation
  479. func (s *GroupedTuples) AggregateEval(expr ast.Expr, v CallValuer) []interface{} {
  480. var result []interface{}
  481. for _, t := range s.Content {
  482. result = append(result, Eval(expr, MultiValuer(t, &WindowRangeValuer{WindowRange: s.WindowRange}, v, &WildcardValuer{t})))
  483. }
  484. return result
  485. }
  486. func (s *GroupedTuples) Value(key, table string) (interface{}, bool) {
  487. r, ok := s.AffiliateRow.Value(key, table)
  488. if ok {
  489. return r, ok
  490. }
  491. return s.Content[0].Value(key, table)
  492. }
  493. func (s *GroupedTuples) Meta(key, table string) (interface{}, bool) {
  494. return s.Content[0].Meta(key, table)
  495. }
  496. func (s *GroupedTuples) All(_ string) (Message, bool) {
  497. return s.ToMap(), true
  498. }
  499. func (s *GroupedTuples) ToMap() map[string]interface{} {
  500. s.lock.Lock()
  501. defer s.lock.Unlock()
  502. if s.cachedMap == nil {
  503. m := make(map[string]interface{})
  504. for k, v := range s.Content[0].ToMap() {
  505. m[k] = v
  506. }
  507. s.cachedMap = m
  508. s.AffiliateRow.MergeMap(s.cachedMap)
  509. }
  510. return s.cachedMap
  511. }
  512. func (s *GroupedTuples) Clone() CollectionRow {
  513. ts := make([]TupleRow, len(s.Content))
  514. for i, t := range s.Content {
  515. ts[i] = t
  516. }
  517. c := &GroupedTuples{
  518. Content: ts,
  519. WindowRange: s.WindowRange,
  520. AffiliateRow: s.AffiliateRow.Clone(),
  521. }
  522. return c
  523. }
  524. func (s *GroupedTuples) Pick(allWildcard bool, cols [][]string, wildcardEmitters map[string]bool) {
  525. cols = s.AffiliateRow.Pick(cols)
  526. sc := s.Content[0].Clone()
  527. sc.Pick(allWildcard, cols, wildcardEmitters)
  528. s.Content[0] = sc
  529. }