row.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. cachedMap[k] = v
  140. }
  141. for k, v := range d.AliasMap {
  142. cachedMap[k] = v
  143. }
  144. }
  145. func (d *AffiliateRow) Pick(cols [][]string) [][]string {
  146. d.lock.Lock()
  147. defer d.lock.Unlock()
  148. if len(cols) > 0 {
  149. newAliasMap := make(map[string]interface{})
  150. newCalCols := make(map[string]interface{})
  151. var newCols [][]string
  152. for _, a := range cols {
  153. if a[1] == "" || a[1] == string(ast.DefaultStream) {
  154. if v, ok := d.AliasMap[a[0]]; ok {
  155. newAliasMap[a[0]] = v
  156. continue
  157. }
  158. if v, ok := d.CalCols[a[0]]; ok {
  159. newCalCols[a[0]] = v
  160. continue
  161. }
  162. }
  163. newCols = append(newCols, a)
  164. }
  165. d.AliasMap = newAliasMap
  166. d.CalCols = newCalCols
  167. return newCols
  168. } else {
  169. d.AliasMap = nil
  170. d.CalCols = nil
  171. return cols
  172. }
  173. }
  174. /*
  175. * Message definition
  176. */
  177. // Message is a valuer that substitutes values for the mapped interface. It is the basic type for data events.
  178. type Message map[string]interface{}
  179. var _ Valuer = Message{}
  180. type Metadata Message
  181. // Alias will not need to convert cases
  182. type Alias struct {
  183. AliasMap map[string]interface{}
  184. }
  185. /*
  186. * All row types definitions, watermark, barrier
  187. */
  188. // Tuple The input row, produced by the source
  189. type Tuple struct {
  190. Emitter string
  191. Message Message // the original pointer is immutable & big; may be cloned
  192. Timestamp int64
  193. Metadata Metadata // immutable
  194. AffiliateRow
  195. lock sync.Mutex // lock for the cachedMap, because it is possible to access by multiple sinks
  196. cachedMap map[string]interface{} // clone of the row and cached for performance
  197. }
  198. var _ TupleRow = &Tuple{}
  199. // JoinTuple is a row produced by a join operation
  200. type JoinTuple struct {
  201. Tuples []TupleRow // The content is immutable, but the slice may be add or removed
  202. AffiliateRow
  203. lock sync.Mutex
  204. cachedMap map[string]interface{} // clone of the row and cached for performance of toMap
  205. }
  206. func (jt *JoinTuple) AggregateEval(expr ast.Expr, v CallValuer) []interface{} {
  207. return []interface{}{Eval(expr, MultiValuer(jt, v, &WildcardValuer{jt}))}
  208. }
  209. var _ TupleRow = &JoinTuple{}
  210. // GroupedTuples is a collection of tuples grouped by a key
  211. type GroupedTuples struct {
  212. Content []TupleRow
  213. *WindowRange
  214. AffiliateRow
  215. lock sync.Mutex
  216. cachedMap map[string]interface{} // clone of the row and cached for performance of toMap
  217. }
  218. var _ CollectionRow = &GroupedTuples{}
  219. /*
  220. * Implementations
  221. */
  222. func ToMessage(input interface{}) (Message, bool) {
  223. var result Message
  224. switch m := input.(type) {
  225. case Message:
  226. result = m
  227. case Metadata:
  228. result = Message(m)
  229. case map[string]interface{}:
  230. result = m
  231. default:
  232. return nil, false
  233. }
  234. return result, true
  235. }
  236. func (m Message) Value(key, _ string) (interface{}, bool) {
  237. if v, ok := m[key]; ok {
  238. return v, ok
  239. } else if conf.Config == nil || conf.Config.Basic.IgnoreCase {
  240. //Only when with 'SELECT * FROM ...' and 'schemaless', the key in map is not convert to lower case.
  241. //So all of keys in map should be convert to lowercase and then compare them.
  242. return m.getIgnoreCase(key)
  243. } else {
  244. return nil, false
  245. }
  246. }
  247. func (m Message) getIgnoreCase(key interface{}) (interface{}, bool) {
  248. if k, ok := key.(string); ok {
  249. for mk, v := range m {
  250. if strings.EqualFold(k, mk) {
  251. return v, true
  252. }
  253. }
  254. }
  255. return nil, false
  256. }
  257. func (m Message) Meta(key, table string) (interface{}, bool) {
  258. if key == "*" {
  259. return map[string]interface{}(m), true
  260. }
  261. return m.Value(key, table)
  262. }
  263. // MetaData implementation
  264. func (m Metadata) Value(key, table string) (interface{}, bool) {
  265. msg := Message(m)
  266. return msg.Value(key, table)
  267. }
  268. func (m Metadata) Meta(key, table string) (interface{}, bool) {
  269. if key == "*" {
  270. return map[string]interface{}(m), true
  271. }
  272. msg := Message(m)
  273. return msg.Meta(key, table)
  274. }
  275. // Tuple implementation
  276. func (t *Tuple) Value(key, table string) (interface{}, bool) {
  277. r, ok := t.AffiliateRow.Value(key, table)
  278. if ok {
  279. return r, ok
  280. }
  281. return t.Message.Value(key, table)
  282. }
  283. func (t *Tuple) All(string) (Message, bool) {
  284. return t.ToMap(), true
  285. }
  286. func (t *Tuple) Clone() TupleRow {
  287. return &Tuple{
  288. Emitter: t.Emitter,
  289. Timestamp: t.Timestamp,
  290. Message: t.Message,
  291. Metadata: t.Metadata,
  292. AffiliateRow: t.AffiliateRow.Clone(),
  293. }
  294. }
  295. // ToMap should only use in sink.
  296. func (t *Tuple) ToMap() map[string]interface{} {
  297. t.lock.Lock()
  298. defer t.lock.Unlock()
  299. if t.AffiliateRow.IsEmpty() {
  300. return t.Message
  301. }
  302. if t.cachedMap == nil { // clone the message
  303. m := make(map[string]interface{})
  304. for k, v := range t.Message {
  305. m[k] = v
  306. }
  307. t.cachedMap = m
  308. }
  309. t.AffiliateRow.MergeMap(t.cachedMap)
  310. return t.cachedMap
  311. }
  312. func (t *Tuple) Meta(key, table string) (interface{}, bool) {
  313. if key == "*" {
  314. return map[string]interface{}(t.Metadata), true
  315. }
  316. return t.Metadata.Value(key, table)
  317. }
  318. func (t *Tuple) GetEmitter() string {
  319. return t.Emitter
  320. }
  321. func (t *Tuple) AggregateEval(expr ast.Expr, v CallValuer) []interface{} {
  322. return []interface{}{Eval(expr, MultiValuer(t, v, &WildcardValuer{t}))}
  323. }
  324. func (t *Tuple) GetTimestamp() int64 {
  325. return t.Timestamp
  326. }
  327. func (t *Tuple) IsWatermark() bool {
  328. return false
  329. }
  330. func (t *Tuple) Pick(allWildcard bool, cols [][]string, wildcardEmitters map[string]bool) {
  331. cols = t.AffiliateRow.Pick(cols)
  332. if !allWildcard && wildcardEmitters[t.Emitter] {
  333. allWildcard = true
  334. }
  335. if !allWildcard {
  336. if len(cols) > 0 {
  337. pickedMap := make(map[string]interface{})
  338. for _, colTab := range cols {
  339. if colTab[1] == "" || colTab[1] == string(ast.DefaultStream) || colTab[1] == t.Emitter {
  340. if v, ok := t.Message.Value(colTab[0], colTab[1]); ok {
  341. pickedMap[colTab[0]] = v
  342. }
  343. }
  344. }
  345. t.Message = pickedMap
  346. } else {
  347. t.Message = make(map[string]interface{})
  348. t.cachedMap = make(map[string]interface{})
  349. }
  350. }
  351. }
  352. // JoinTuple implementation
  353. func (jt *JoinTuple) AddTuple(tuple TupleRow) {
  354. jt.Tuples = append(jt.Tuples, tuple)
  355. }
  356. func (jt *JoinTuple) AddTuples(tuples []TupleRow) {
  357. for _, t := range tuples {
  358. jt.Tuples = append(jt.Tuples, t)
  359. }
  360. }
  361. func (jt *JoinTuple) doGetValue(key, table string, isVal bool) (interface{}, bool) {
  362. tuples := jt.Tuples
  363. if table == "" {
  364. if len(tuples) > 1 {
  365. for _, tuple := range tuples { //TODO support key without modifier?
  366. v, ok := getTupleValue(tuple, key, isVal)
  367. if ok {
  368. return v, ok
  369. }
  370. }
  371. conf.Log.Debugf("Wrong key: %s not found", key)
  372. return nil, false
  373. } else {
  374. return getTupleValue(tuples[0], key, isVal)
  375. }
  376. } else {
  377. //TODO should use hash here
  378. for _, tuple := range tuples {
  379. if tuple.GetEmitter() == table {
  380. return getTupleValue(tuple, key, isVal)
  381. }
  382. }
  383. return nil, false
  384. }
  385. }
  386. func getTupleValue(tuple Row, key string, isVal bool) (interface{}, bool) {
  387. if isVal {
  388. return tuple.Value(key, "")
  389. } else {
  390. return tuple.Meta(key, "")
  391. }
  392. }
  393. func (jt *JoinTuple) GetEmitter() string {
  394. return "$$JOIN"
  395. }
  396. func (jt *JoinTuple) Value(key, table string) (interface{}, bool) {
  397. r, ok := jt.AffiliateRow.Value(key, table)
  398. if ok {
  399. return r, ok
  400. }
  401. return jt.doGetValue(key, table, true)
  402. }
  403. func (jt *JoinTuple) Meta(key, table string) (interface{}, bool) {
  404. return jt.doGetValue(key, table, false)
  405. }
  406. func (jt *JoinTuple) All(stream string) (Message, bool) {
  407. if stream != "" {
  408. for _, t := range jt.Tuples {
  409. if t.GetEmitter() == stream {
  410. return t.ToMap(), true
  411. }
  412. }
  413. } else {
  414. return jt.ToMap(), true
  415. }
  416. return nil, false
  417. }
  418. func (jt *JoinTuple) Clone() TupleRow {
  419. ts := make([]TupleRow, len(jt.Tuples))
  420. for i, t := range jt.Tuples {
  421. ts[i] = t.Clone()
  422. }
  423. c := &JoinTuple{
  424. Tuples: ts,
  425. AffiliateRow: jt.AffiliateRow.Clone(),
  426. }
  427. return c
  428. }
  429. func (jt *JoinTuple) ToMap() map[string]interface{} {
  430. jt.lock.Lock()
  431. defer jt.lock.Unlock()
  432. if jt.cachedMap == nil { // clone the message
  433. m := make(map[string]interface{})
  434. for i := len(jt.Tuples) - 1; i >= 0; i-- {
  435. for k, v := range jt.Tuples[i].ToMap() {
  436. m[k] = v
  437. }
  438. }
  439. jt.cachedMap = m
  440. }
  441. jt.AffiliateRow.MergeMap(jt.cachedMap)
  442. return jt.cachedMap
  443. }
  444. func (jt *JoinTuple) Pick(allWildcard bool, cols [][]string, wildcardEmitters map[string]bool) {
  445. cols = jt.AffiliateRow.Pick(cols)
  446. if !allWildcard {
  447. if len(cols) > 0 {
  448. for _, tuple := range jt.Tuples {
  449. if _, ok := wildcardEmitters[tuple.GetEmitter()]; ok {
  450. continue
  451. }
  452. tuple.Pick(allWildcard, cols, wildcardEmitters)
  453. }
  454. } else {
  455. jt.Tuples = jt.Tuples[:0]
  456. }
  457. }
  458. jt.cachedMap = nil
  459. }
  460. // GroupedTuple implementation
  461. func (s *GroupedTuples) AggregateEval(expr ast.Expr, v CallValuer) []interface{} {
  462. var result []interface{}
  463. for _, t := range s.Content {
  464. result = append(result, Eval(expr, MultiValuer(t, &WindowRangeValuer{WindowRange: s.WindowRange}, v, &WildcardValuer{t})))
  465. }
  466. return result
  467. }
  468. func (s *GroupedTuples) Value(key, table string) (interface{}, bool) {
  469. r, ok := s.AffiliateRow.Value(key, table)
  470. if ok {
  471. return r, ok
  472. }
  473. return s.Content[0].Value(key, table)
  474. }
  475. func (s *GroupedTuples) Meta(key, table string) (interface{}, bool) {
  476. return s.Content[0].Meta(key, table)
  477. }
  478. func (s *GroupedTuples) All(_ string) (Message, bool) {
  479. return s.ToMap(), true
  480. }
  481. func (s *GroupedTuples) ToMap() map[string]interface{} {
  482. s.lock.Lock()
  483. defer s.lock.Unlock()
  484. if s.cachedMap == nil {
  485. m := make(map[string]interface{})
  486. for k, v := range s.Content[0].ToMap() {
  487. m[k] = v
  488. }
  489. s.cachedMap = m
  490. }
  491. s.AffiliateRow.MergeMap(s.cachedMap)
  492. return s.cachedMap
  493. }
  494. func (s *GroupedTuples) Clone() CollectionRow {
  495. ts := make([]TupleRow, len(s.Content))
  496. for i, t := range s.Content {
  497. ts[i] = t
  498. }
  499. c := &GroupedTuples{
  500. Content: ts,
  501. WindowRange: s.WindowRange,
  502. AffiliateRow: s.AffiliateRow.Clone(),
  503. }
  504. return c
  505. }
  506. func (s *GroupedTuples) Pick(allWildcard bool, cols [][]string, wildcardEmitters map[string]bool) {
  507. cols = s.AffiliateRow.Pick(cols)
  508. s.Content[0].Pick(allWildcard, cols, wildcardEmitters)
  509. }