row.go 14 KB

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