row.go 13 KB

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