join_operator.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. // Copyright 2021-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 operator
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/xsql"
  18. "github.com/lf-edge/ekuiper/pkg/api"
  19. "github.com/lf-edge/ekuiper/pkg/ast"
  20. )
  21. // JoinOp TODO join expr should only be the equal op between 2 streams like tb1.id = tb2.id
  22. type JoinOp struct {
  23. From *ast.Table
  24. Joins ast.Joins
  25. }
  26. // Apply
  27. // input: MergedCollection, the Row must be a Tuple
  28. // output: Collection
  29. func (jp *JoinOp) Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, _ *xsql.AggregateFunctionValuer) interface{} {
  30. log := ctx.GetLogger()
  31. var input xsql.MergedCollection
  32. switch v := data.(type) {
  33. case error:
  34. return v
  35. case xsql.MergedCollection:
  36. input = v
  37. log.Debugf("join plan receive %v", data)
  38. default:
  39. return fmt.Errorf("run Join error: join is only supported in window")
  40. }
  41. result := &xsql.JoinTuples{Content: make([]*xsql.JoinTuple, 0)}
  42. for i, join := range jp.Joins {
  43. if i == 0 {
  44. v, err := jp.evalSet(input, join, fv)
  45. if err != nil {
  46. return fmt.Errorf("run Join error: %s", err)
  47. }
  48. result = v
  49. } else {
  50. r1, err := jp.evalJoinSets(result, input, join, fv)
  51. if err != nil {
  52. return fmt.Errorf("run Join error: %s", err)
  53. }
  54. if v1, ok := r1.(*xsql.JoinTuples); ok {
  55. result = v1
  56. }
  57. }
  58. }
  59. if result.Len() <= 0 {
  60. log.Debugf("join plan yields nothing")
  61. return nil
  62. }
  63. result.WindowRange = input.GetWindowRange()
  64. return result
  65. }
  66. func (jp *JoinOp) getStreamNames(join *ast.Join) ([]string, error) {
  67. var srcs []string
  68. keys := make(map[ast.StreamName]bool)
  69. ast.WalkFunc(join, func(node ast.Node) bool {
  70. if f, ok := node.(*ast.FieldRef); ok {
  71. for _, v := range f.RefSources() {
  72. // Exclude default stream as it is a virtual stream name.
  73. if v == ast.DefaultStream {
  74. continue
  75. }
  76. if _, ok := keys[v]; !ok {
  77. srcs = append(srcs, string(v))
  78. keys[v] = true
  79. }
  80. }
  81. }
  82. return true
  83. })
  84. if len(srcs) != 2 {
  85. if jp.From.Alias != "" {
  86. srcs = append(srcs, jp.From.Alias)
  87. } else {
  88. srcs = append(srcs, jp.From.Name)
  89. }
  90. if join.Alias != "" {
  91. srcs = append(srcs, join.Alias)
  92. } else {
  93. srcs = append(srcs, join.Name)
  94. }
  95. }
  96. return srcs, nil
  97. }
  98. func (jp *JoinOp) evalSet(input xsql.MergedCollection, join ast.Join, fv *xsql.FunctionValuer) (*xsql.JoinTuples, error) {
  99. var leftStream, rightStream string
  100. if join.JoinType != ast.CROSS_JOIN {
  101. streams, err := jp.getStreamNames(&join)
  102. if err != nil {
  103. return nil, err
  104. }
  105. leftStream = streams[0]
  106. rightStream = streams[1]
  107. } else {
  108. if jp.From.Alias == "" {
  109. leftStream = jp.From.Name
  110. } else {
  111. leftStream = jp.From.Alias
  112. }
  113. if join.Alias == "" {
  114. rightStream = join.Name
  115. } else {
  116. rightStream = join.Alias
  117. }
  118. }
  119. var lefts, rights []xsql.TupleRow
  120. lefts = input.GetBySrc(leftStream)
  121. rights = input.GetBySrc(rightStream)
  122. sets := &xsql.JoinTuples{Content: make([]*xsql.JoinTuple, 0)}
  123. if join.JoinType == ast.RIGHT_JOIN {
  124. return jp.evalSetWithRightJoin(input, join, false, fv)
  125. }
  126. for _, left := range lefts {
  127. leftJoined := false
  128. for index, right := range rights {
  129. tupleJoined := false
  130. merged := &xsql.JoinTuple{}
  131. if join.JoinType == ast.LEFT_JOIN || join.JoinType == ast.FULL_JOIN || join.JoinType == ast.CROSS_JOIN {
  132. merged.AddTuple(left)
  133. }
  134. if join.JoinType == ast.CROSS_JOIN {
  135. tupleJoined = true
  136. merged.AddTuple(right)
  137. } else {
  138. temp := &xsql.JoinTuple{}
  139. temp.AddTuple(left)
  140. temp.AddTuple(right)
  141. ve := &xsql.ValuerEval{Valuer: xsql.MultiValuer(temp, fv)}
  142. result := evalOn(join, ve, left, right)
  143. merged.AliasMap = temp.AliasMap
  144. switch val := result.(type) {
  145. case error:
  146. return nil, val
  147. case bool:
  148. if val {
  149. leftJoined = true
  150. tupleJoined = true
  151. if join.JoinType == ast.INNER_JOIN {
  152. merged.AddTuple(left)
  153. merged.AddTuple(right)
  154. } else {
  155. merged.AddTuple(right)
  156. }
  157. }
  158. default:
  159. return nil, fmt.Errorf("invalid join condition that returns non-bool value %[1]T(%[1]v)", val)
  160. }
  161. }
  162. if tupleJoined || (!leftJoined && index == len(rights)-1 && len(merged.Tuples) > 0) {
  163. leftJoined = true
  164. sets.Content = append(sets.Content, merged)
  165. }
  166. }
  167. // If no messages in the right
  168. if !leftJoined && join.JoinType != ast.INNER_JOIN && join.JoinType != ast.CROSS_JOIN {
  169. merged := &xsql.JoinTuple{}
  170. merged.AddTuple(left)
  171. sets.Content = append(sets.Content, merged)
  172. }
  173. }
  174. if join.JoinType == ast.FULL_JOIN {
  175. if rightJoinSet, err := jp.evalSetWithRightJoin(input, join, true, fv); err == nil {
  176. if len(rightJoinSet.Content) > 0 {
  177. for _, jt := range rightJoinSet.Content {
  178. sets.Content = append(sets.Content, jt)
  179. }
  180. }
  181. } else {
  182. return nil, err
  183. }
  184. }
  185. return sets, nil
  186. }
  187. func evalOn(join ast.Join, ve *xsql.ValuerEval, left interface{}, right xsql.Row) interface{} {
  188. var result interface{}
  189. if join.Expr != nil {
  190. result = ve.Eval(join.Expr)
  191. } else if join.JoinType == ast.INNER_JOIN { // if no on expression
  192. result = left != nil && right != nil
  193. } else {
  194. result = true
  195. }
  196. return result
  197. }
  198. func (jp *JoinOp) evalSetWithRightJoin(input xsql.MergedCollection, join ast.Join, excludeJoint bool, fv *xsql.FunctionValuer) (*xsql.JoinTuples, error) {
  199. streams, err := jp.getStreamNames(&join)
  200. if err != nil {
  201. return nil, err
  202. }
  203. leftStream := streams[0]
  204. rightStream := streams[1]
  205. var lefts, rights []xsql.TupleRow
  206. lefts = input.GetBySrc(leftStream)
  207. rights = input.GetBySrc(rightStream)
  208. sets := &xsql.JoinTuples{Content: make([]*xsql.JoinTuple, 0)}
  209. for _, right := range rights {
  210. isJoint := false
  211. for index, left := range lefts {
  212. tupleJoined := false
  213. merged := &xsql.JoinTuple{}
  214. merged.AddTuple(right)
  215. temp := &xsql.JoinTuple{}
  216. temp.AddTuple(right)
  217. temp.AddTuple(left)
  218. ve := &xsql.ValuerEval{Valuer: xsql.MultiValuer(temp, fv)}
  219. result := evalOn(join, ve, left, right)
  220. merged.AliasMap = temp.AliasMap
  221. switch val := result.(type) {
  222. case error:
  223. return nil, val
  224. case bool:
  225. if val {
  226. merged.AddTuple(left)
  227. isJoint = true
  228. tupleJoined = true
  229. }
  230. default:
  231. return nil, fmt.Errorf("invalid join condition that returns non-bool value %[1]T(%[1]v)", val)
  232. }
  233. if !excludeJoint && (tupleJoined || (!isJoint && index == len(lefts)-1 && len(merged.Tuples) > 0)) {
  234. isJoint = true
  235. sets.Content = append(sets.Content, merged)
  236. }
  237. }
  238. if !isJoint {
  239. merged := &xsql.JoinTuple{}
  240. merged.AddTuple(right)
  241. sets.Content = append(sets.Content, merged)
  242. }
  243. }
  244. return sets, nil
  245. }
  246. func (jp *JoinOp) evalJoinSets(set *xsql.JoinTuples, input xsql.MergedCollection, join ast.Join, fv *xsql.FunctionValuer) (interface{}, error) {
  247. var rightStream string
  248. if join.Alias == "" {
  249. rightStream = join.Name
  250. } else {
  251. rightStream = join.Alias
  252. }
  253. rights := input.GetBySrc(rightStream)
  254. newSets := &xsql.JoinTuples{Content: make([]*xsql.JoinTuple, 0)}
  255. if join.JoinType == ast.RIGHT_JOIN {
  256. return jp.evalRightJoinSets(set, input, join, false, fv)
  257. }
  258. for _, left := range set.Content {
  259. leftJoined := false
  260. for index, right := range rights {
  261. tupleJoined := false
  262. merged := &xsql.JoinTuple{}
  263. if join.JoinType == ast.LEFT_JOIN || join.JoinType == ast.FULL_JOIN || join.JoinType == ast.CROSS_JOIN {
  264. merged.AddTuples(left.Tuples)
  265. }
  266. if join.JoinType == ast.CROSS_JOIN {
  267. tupleJoined = true
  268. merged.AddTuple(right)
  269. } else {
  270. temp := &xsql.JoinTuple{}
  271. temp.AddTuples(left.Tuples)
  272. temp.AddTuple(right)
  273. ve := &xsql.ValuerEval{Valuer: xsql.MultiValuer(temp, fv)}
  274. result := evalOn(join, ve, left, right)
  275. merged.AliasMap = left.AliasMap
  276. switch val := result.(type) {
  277. case error:
  278. return nil, val
  279. case bool:
  280. if val {
  281. leftJoined = true
  282. tupleJoined = true
  283. if join.JoinType == ast.INNER_JOIN {
  284. merged.AddTuples(left.Tuples)
  285. }
  286. merged.AddTuple(right)
  287. }
  288. default:
  289. return nil, fmt.Errorf("invalid join condition that returns non-bool value %[1]T(%[1]v)", val)
  290. }
  291. }
  292. if tupleJoined || (!leftJoined && index == len(rights)-1 && len(merged.Tuples) > 0) {
  293. leftJoined = true
  294. newSets.Content = append(newSets.Content, merged)
  295. }
  296. }
  297. if !leftJoined && join.JoinType != ast.INNER_JOIN && join.JoinType != ast.CROSS_JOIN {
  298. merged := &xsql.JoinTuple{}
  299. merged.AddTuples(left.Tuples)
  300. newSets.Content = append(newSets.Content, merged)
  301. }
  302. }
  303. if join.JoinType == ast.FULL_JOIN {
  304. if rightJoinSet, err := jp.evalRightJoinSets(set, input, join, true, fv); err == nil && len(rightJoinSet.Content) > 0 {
  305. for _, jt := range rightJoinSet.Content {
  306. newSets.Content = append(newSets.Content, jt)
  307. }
  308. }
  309. }
  310. return newSets, nil
  311. }
  312. func (jp *JoinOp) evalRightJoinSets(set *xsql.JoinTuples, input xsql.MergedCollection, join ast.Join, excludeJoint bool, fv *xsql.FunctionValuer) (*xsql.JoinTuples, error) {
  313. var rightStream string
  314. if join.Alias == "" {
  315. rightStream = join.Name
  316. } else {
  317. rightStream = join.Alias
  318. }
  319. rights := input.GetBySrc(rightStream)
  320. newSets := &xsql.JoinTuples{Content: make([]*xsql.JoinTuple, 0)}
  321. for _, right := range rights {
  322. isJoint := false
  323. for index, left := range set.Content {
  324. tupleJoined := false
  325. merged := &xsql.JoinTuple{}
  326. merged.AddTuple(right)
  327. temp := &xsql.JoinTuple{}
  328. temp.AddTuples(left.Tuples)
  329. temp.AddTuple(right)
  330. ve := &xsql.ValuerEval{Valuer: xsql.MultiValuer(temp, fv)}
  331. result := evalOn(join, ve, left, right)
  332. merged.AliasMap = left.AliasMap
  333. switch val := result.(type) {
  334. case error:
  335. return nil, val
  336. case bool:
  337. if val {
  338. isJoint = true
  339. tupleJoined = true
  340. merged.AddTuples(left.Tuples)
  341. }
  342. default:
  343. return nil, fmt.Errorf("invalid join condition that returns non-bool value %[1]T(%[1]v)", val)
  344. }
  345. if !excludeJoint && (tupleJoined || (!isJoint && index == len(set.Content)-1 && len(merged.Tuples) > 0)) {
  346. isJoint = true
  347. newSets.Content = append(newSets.Content, merged)
  348. }
  349. }
  350. if !isJoint {
  351. merged := &xsql.JoinTuple{}
  352. merged.AddTuple(right)
  353. newSets.Content = append(newSets.Content, merged)
  354. }
  355. }
  356. return newSets, nil
  357. }