analyzer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 planner
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/binder/function"
  18. "github.com/lf-edge/ekuiper/internal/xsql"
  19. "github.com/lf-edge/ekuiper/pkg/ast"
  20. "github.com/lf-edge/ekuiper/pkg/kv"
  21. "strings"
  22. )
  23. // Analyze the select statement by decorating the info from stream statement.
  24. // Typically, set the correct stream name for fieldRefs
  25. func decorateStmt(s *ast.SelectStatement, store kv.KeyValue) ([]*ast.StreamStmt, []*ast.Call, error) {
  26. streamsFromStmt := xsql.GetStreams(s)
  27. streamStmts := make([]*ast.StreamStmt, len(streamsFromStmt))
  28. isSchemaless := false
  29. for i, s := range streamsFromStmt {
  30. streamStmt, err := xsql.GetDataSource(store, s)
  31. if err != nil {
  32. return nil, nil, fmt.Errorf("fail to get stream %s, please check if stream is created", s)
  33. }
  34. streamStmts[i] = streamStmt
  35. // TODO fine grain control of schemaless
  36. if streamStmt.StreamFields == nil {
  37. isSchemaless = true
  38. }
  39. }
  40. dsn := ast.DefaultStream
  41. if len(streamsFromStmt) == 1 {
  42. dsn = streamStmts[0].Name
  43. }
  44. // [fieldName][streamsName][*aliasRef] if alias, with special key alias/default. Each key has exactly one value
  45. fieldsMap := newFieldsMap(isSchemaless, dsn)
  46. if !isSchemaless {
  47. for _, streamStmt := range streamStmts {
  48. for _, field := range streamStmt.StreamFields {
  49. fieldsMap.reserve(field.Name, streamStmt.Name)
  50. }
  51. }
  52. }
  53. var (
  54. walkErr error
  55. aliasFields []*ast.Field
  56. analyticFuncs []*ast.Call
  57. )
  58. // Scan columns fields: bind all field refs, collect alias
  59. for i, f := range s.Fields {
  60. ast.WalkFunc(f.Expr, func(n ast.Node) bool {
  61. switch f := n.(type) {
  62. case *ast.FieldRef:
  63. walkErr = fieldsMap.bind(f)
  64. }
  65. return true
  66. })
  67. if walkErr != nil {
  68. return nil, nil, walkErr
  69. }
  70. if f.AName != "" {
  71. aliasFields = append(aliasFields, &s.Fields[i])
  72. }
  73. }
  74. // bind alias field expressions
  75. for _, f := range aliasFields {
  76. ar, err := ast.NewAliasRef(f.Expr)
  77. if err != nil {
  78. walkErr = err
  79. } else {
  80. f.Expr = &ast.FieldRef{
  81. StreamName: ast.AliasStream,
  82. Name: f.AName,
  83. AliasRef: ar,
  84. }
  85. walkErr = fieldsMap.save(f.AName, ast.AliasStream, ar)
  86. }
  87. }
  88. // Bind field ref for alias AND set StreamName for all field ref
  89. ast.WalkFunc(s, func(n ast.Node) bool {
  90. switch f := n.(type) {
  91. case ast.Fields: // do not bind selection fields, should have done above
  92. return false
  93. case *ast.FieldRef:
  94. if f.StreamName != "" && f.StreamName != ast.DefaultStream {
  95. // check if stream exists
  96. found := false
  97. for _, sn := range streamsFromStmt {
  98. if sn == string(f.StreamName) {
  99. found = true
  100. break
  101. }
  102. }
  103. if !found {
  104. walkErr = fmt.Errorf("stream %s not found", f.StreamName)
  105. return true
  106. }
  107. }
  108. walkErr = fieldsMap.bind(f)
  109. }
  110. return true
  111. })
  112. if walkErr != nil {
  113. return nil, nil, walkErr
  114. }
  115. walkErr = validate(s)
  116. // Collect all analytic function calls so that we can let them run firstly
  117. ast.WalkFunc(s, func(n ast.Node) bool {
  118. switch f := n.(type) {
  119. case ast.Fields:
  120. return false
  121. case *ast.Call:
  122. if function.IsAnalyticFunc(f.Name) {
  123. f.CachedField = fmt.Sprintf("%s_%s_%d", function.AnalyticPrefix, f.Name, f.FuncId)
  124. f.Cached = true
  125. analyticFuncs = append(analyticFuncs, &ast.Call{
  126. Name: f.Name,
  127. FuncId: f.FuncId,
  128. FuncType: f.FuncType,
  129. Args: f.Args,
  130. CachedField: f.CachedField,
  131. Partition: f.Partition,
  132. WhenExpr: f.WhenExpr,
  133. })
  134. }
  135. }
  136. return true
  137. })
  138. if walkErr != nil {
  139. return nil, nil, walkErr
  140. }
  141. // walk sources at last to let them run firstly
  142. // because other clause may depend on the alias defined here
  143. ast.WalkFunc(s.Fields, func(n ast.Node) bool {
  144. switch f := n.(type) {
  145. case *ast.Call:
  146. if function.IsAnalyticFunc(f.Name) {
  147. f.CachedField = fmt.Sprintf("%s_%s_%d", function.AnalyticPrefix, f.Name, f.FuncId)
  148. f.Cached = true
  149. analyticFuncs = append(analyticFuncs, &ast.Call{
  150. Name: f.Name,
  151. FuncId: f.FuncId,
  152. FuncType: f.FuncType,
  153. Args: f.Args,
  154. CachedField: f.CachedField,
  155. Partition: f.Partition,
  156. WhenExpr: f.WhenExpr,
  157. })
  158. }
  159. }
  160. return true
  161. })
  162. if walkErr != nil {
  163. return nil, nil, walkErr
  164. }
  165. return streamStmts, analyticFuncs, walkErr
  166. }
  167. func validate(s *ast.SelectStatement) (err error) {
  168. if xsql.IsAggregate(s.Condition) {
  169. return fmt.Errorf("Not allowed to call aggregate functions in WHERE clause.")
  170. }
  171. if !allAggregate(s.Having) {
  172. return fmt.Errorf("Not allowed to call non-aggregate functions in HAVING clause.")
  173. }
  174. for _, d := range s.Dimensions {
  175. if xsql.IsAggregate(d.Expr) {
  176. return fmt.Errorf("Not allowed to call aggregate functions in GROUP BY clause.")
  177. }
  178. }
  179. ast.WalkFunc(s, func(n ast.Node) bool {
  180. switch f := n.(type) {
  181. case *ast.Call:
  182. // aggregate call should not have any aggregate arg
  183. if function.IsAggFunc(f.Name) {
  184. for _, arg := range f.Args {
  185. tr := xsql.IsAggregate(arg)
  186. if tr {
  187. err = fmt.Errorf("invalid argument for func %s: aggregate argument is not allowed", f.Name)
  188. return false
  189. }
  190. }
  191. }
  192. }
  193. return true
  194. })
  195. return
  196. }
  197. // file-private functions below
  198. // allAggregate checks if all expressions of binary expression are aggregate
  199. func allAggregate(expr ast.Expr) (r bool) {
  200. r = true
  201. ast.WalkFunc(expr, func(n ast.Node) bool {
  202. switch f := expr.(type) {
  203. case *ast.BinaryExpr:
  204. switch f.OP {
  205. case ast.SUBSET, ast.ARROW:
  206. // do nothing
  207. default:
  208. r = allAggregate(f.LHS) && allAggregate(f.RHS)
  209. return false
  210. }
  211. case *ast.Call, *ast.FieldRef:
  212. if !xsql.IsAggregate(f) {
  213. r = false
  214. return false
  215. }
  216. }
  217. return true
  218. })
  219. return
  220. }
  221. type fieldsMap struct {
  222. content map[string]streamFieldStore
  223. isSchemaless bool
  224. defaultStream ast.StreamName
  225. }
  226. func newFieldsMap(isSchemaless bool, defaultStream ast.StreamName) *fieldsMap {
  227. return &fieldsMap{content: make(map[string]streamFieldStore), isSchemaless: isSchemaless, defaultStream: defaultStream}
  228. }
  229. func (f *fieldsMap) reserve(fieldName string, streamName ast.StreamName) {
  230. lname := strings.ToLower(fieldName)
  231. if fm, ok := f.content[lname]; ok {
  232. fm.add(streamName)
  233. } else {
  234. fm := newStreamFieldStore(f.isSchemaless, f.defaultStream)
  235. fm.add(streamName)
  236. f.content[lname] = fm
  237. }
  238. }
  239. func (f *fieldsMap) save(fieldName string, streamName ast.StreamName, field *ast.AliasRef) error {
  240. lname := strings.ToLower(fieldName)
  241. fm, ok := f.content[lname]
  242. if !ok {
  243. if streamName == ast.AliasStream || f.isSchemaless {
  244. fm = newStreamFieldStore(f.isSchemaless, f.defaultStream)
  245. f.content[lname] = fm
  246. } else {
  247. return fmt.Errorf("unknown field %s", fieldName)
  248. }
  249. }
  250. err := fm.ref(streamName, field)
  251. if err != nil {
  252. return fmt.Errorf("%s%s", err, fieldName)
  253. }
  254. return nil
  255. }
  256. func (f *fieldsMap) bind(fr *ast.FieldRef) error {
  257. lname := strings.ToLower(fr.Name)
  258. fm, ok := f.content[lname]
  259. if !ok {
  260. if f.isSchemaless && fr.Name != "" {
  261. fm = newStreamFieldStore(f.isSchemaless, f.defaultStream)
  262. f.content[lname] = fm
  263. } else {
  264. return fmt.Errorf("unknown field %s", fr.Name)
  265. }
  266. }
  267. err := fm.bindRef(fr)
  268. if err != nil {
  269. return fmt.Errorf("%s%s", err, fr.Name)
  270. }
  271. return nil
  272. }
  273. type streamFieldStore interface {
  274. add(k ast.StreamName)
  275. ref(k ast.StreamName, v *ast.AliasRef) error
  276. bindRef(f *ast.FieldRef) error
  277. }
  278. func newStreamFieldStore(isSchemaless bool, defaultStream ast.StreamName) streamFieldStore {
  279. if !isSchemaless {
  280. return &streamFieldMap{content: make(map[ast.StreamName]*ast.AliasRef)}
  281. } else {
  282. return &streamFieldMapSchemaless{content: make(map[ast.StreamName]*ast.AliasRef), defaultStream: defaultStream}
  283. }
  284. }
  285. type streamFieldMap struct {
  286. content map[ast.StreamName]*ast.AliasRef
  287. }
  288. // add the stream name must not be default.
  289. // This is used when traversing stream schema
  290. func (s *streamFieldMap) add(k ast.StreamName) {
  291. s.content[k] = nil
  292. }
  293. //bind for schema field, all keys must be created before running bind
  294. // can bind alias & col. For alias, the stream name must be empty; For col, the field must be a col
  295. func (s *streamFieldMap) ref(k ast.StreamName, v *ast.AliasRef) error {
  296. if k == ast.AliasStream { // must not exist, save alias ref for alias
  297. _, ok := s.content[k]
  298. if ok {
  299. return fmt.Errorf("duplicate alias ")
  300. }
  301. s.content[k] = v
  302. } else { // the key must exist after the schema travers, do validation
  303. if k == ast.DefaultStream { // In schema mode, default stream won't be a key
  304. l := len(s.content)
  305. if l == 0 {
  306. return fmt.Errorf("unknow field ")
  307. } else if l == 1 {
  308. // valid, do nothing
  309. } else {
  310. return fmt.Errorf("ambiguous field ")
  311. }
  312. } else {
  313. _, ok := s.content[k]
  314. if !ok {
  315. return fmt.Errorf("unknow field %s.", k)
  316. }
  317. }
  318. }
  319. return nil
  320. }
  321. func (s *streamFieldMap) bindRef(fr *ast.FieldRef) error {
  322. l := len(s.content)
  323. if fr.StreamName == "" {
  324. fr.StreamName = ast.DefaultStream
  325. }
  326. k := fr.StreamName
  327. if k == ast.DefaultStream {
  328. switch l {
  329. case 0:
  330. return fmt.Errorf("unknown field ")
  331. case 1: // if alias, return this
  332. for sk, sv := range s.content {
  333. fr.RefSelection(sv)
  334. fr.StreamName = sk
  335. }
  336. return nil
  337. default:
  338. r, ok := s.content[ast.AliasStream] // if alias exists
  339. if ok {
  340. fr.RefSelection(r)
  341. fr.StreamName = ast.AliasStream
  342. return nil
  343. } else {
  344. return fmt.Errorf("ambiguous field ")
  345. }
  346. }
  347. } else {
  348. r, ok := s.content[k]
  349. if ok {
  350. fr.RefSelection(r)
  351. return nil
  352. } else {
  353. return fmt.Errorf("unknown field %s.", k)
  354. }
  355. }
  356. }
  357. type streamFieldMapSchemaless struct {
  358. content map[ast.StreamName]*ast.AliasRef
  359. defaultStream ast.StreamName
  360. }
  361. // add this should not be called for schemaless
  362. func (s *streamFieldMapSchemaless) add(k ast.StreamName) {
  363. s.content[k] = nil
  364. }
  365. //bind for schemaless field, create column if not exist
  366. // can bind alias & col. For alias, the stream name must be empty; For col, the field must be a col
  367. func (s *streamFieldMapSchemaless) ref(k ast.StreamName, v *ast.AliasRef) error {
  368. if k == ast.AliasStream { // must not exist
  369. _, ok := s.content[k]
  370. if ok {
  371. return fmt.Errorf("duplicate alias ")
  372. }
  373. s.content[k] = v
  374. } else { // the key may or may not exist. But always have only one default stream field.
  375. // Replace with stream name if another stream found. The key can be duplicate
  376. l := len(s.content)
  377. if k == ast.DefaultStream { // In schemaless mode, default stream can only exist when length is 1
  378. if l < 1 {
  379. // valid, do nothing
  380. } else {
  381. return fmt.Errorf("ambiguous field ")
  382. }
  383. } else {
  384. if l == 1 {
  385. for sk := range s.content {
  386. if sk == ast.DefaultStream {
  387. delete(s.content, k)
  388. }
  389. }
  390. }
  391. }
  392. }
  393. return nil
  394. }
  395. func (s *streamFieldMapSchemaless) bindRef(fr *ast.FieldRef) error {
  396. l := len(s.content)
  397. if fr.StreamName == "" || fr.StreamName == ast.DefaultStream {
  398. if l == 1 {
  399. for sk := range s.content {
  400. fr.StreamName = sk
  401. }
  402. }
  403. }
  404. k := fr.StreamName
  405. if k == ast.DefaultStream {
  406. switch l {
  407. case 0: // must be a column because alias are fields and have been traversed
  408. // reserve a hole and do nothing
  409. fr.StreamName = s.defaultStream
  410. s.content[s.defaultStream] = nil
  411. return nil
  412. case 1: // if alias or single col, return this
  413. for sk, sv := range s.content {
  414. fr.RefSelection(sv)
  415. fr.StreamName = sk
  416. }
  417. return nil
  418. default:
  419. r, ok := s.content[ast.AliasStream] // if alias exists
  420. if ok {
  421. fr.RefSelection(r)
  422. fr.StreamName = ast.AliasStream
  423. return nil
  424. } else {
  425. fr.StreamName = s.defaultStream
  426. }
  427. }
  428. }
  429. if fr.StreamName != ast.DefaultStream {
  430. r, ok := s.content[k]
  431. if !ok { // reserver a hole
  432. s.content[k] = nil
  433. } else {
  434. fr.RefSelection(r)
  435. }
  436. return nil
  437. }
  438. return fmt.Errorf("ambiguous field ")
  439. }