analyzer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. })
  133. }
  134. }
  135. return true
  136. })
  137. if walkErr != nil {
  138. return nil, nil, walkErr
  139. }
  140. // walk sources at last to let them run firstly
  141. // because other clause may depend on the alias defined here
  142. ast.WalkFunc(s.Fields, func(n ast.Node) bool {
  143. switch f := n.(type) {
  144. case *ast.Call:
  145. if function.IsAnalyticFunc(f.Name) {
  146. f.CachedField = fmt.Sprintf("%s_%s_%d", function.AnalyticPrefix, f.Name, f.FuncId)
  147. f.Cached = true
  148. analyticFuncs = append(analyticFuncs, &ast.Call{
  149. Name: f.Name,
  150. FuncId: f.FuncId,
  151. FuncType: f.FuncType,
  152. Args: f.Args,
  153. CachedField: f.CachedField,
  154. Partition: f.Partition,
  155. })
  156. }
  157. }
  158. return true
  159. })
  160. if walkErr != nil {
  161. return nil, nil, walkErr
  162. }
  163. return streamStmts, analyticFuncs, walkErr
  164. }
  165. func validate(s *ast.SelectStatement) (err error) {
  166. if xsql.IsAggregate(s.Condition) {
  167. return fmt.Errorf("Not allowed to call aggregate functions in WHERE clause.")
  168. }
  169. if !allAggregate(s.Having) {
  170. return fmt.Errorf("Not allowed to call non-aggregate functions in HAVING clause.")
  171. }
  172. for _, d := range s.Dimensions {
  173. if xsql.IsAggregate(d.Expr) {
  174. return fmt.Errorf("Not allowed to call aggregate functions in GROUP BY clause.")
  175. }
  176. }
  177. ast.WalkFunc(s, func(n ast.Node) bool {
  178. switch f := n.(type) {
  179. case *ast.Call:
  180. // aggregate call should not have any aggregate arg
  181. if function.IsAggFunc(f.Name) {
  182. for _, arg := range f.Args {
  183. tr := xsql.IsAggregate(arg)
  184. if tr {
  185. err = fmt.Errorf("invalid argument for func %s: aggregate argument is not allowed", f.Name)
  186. return false
  187. }
  188. }
  189. }
  190. }
  191. return true
  192. })
  193. return
  194. }
  195. // file-private functions below
  196. // allAggregate checks if all expressions of binary expression are aggregate
  197. func allAggregate(expr ast.Expr) (r bool) {
  198. r = true
  199. ast.WalkFunc(expr, func(n ast.Node) bool {
  200. switch f := expr.(type) {
  201. case *ast.BinaryExpr:
  202. switch f.OP {
  203. case ast.SUBSET, ast.ARROW:
  204. // do nothing
  205. default:
  206. r = allAggregate(f.LHS) && allAggregate(f.RHS)
  207. return false
  208. }
  209. case *ast.Call, *ast.FieldRef:
  210. if !xsql.IsAggregate(f) {
  211. r = false
  212. return false
  213. }
  214. }
  215. return true
  216. })
  217. return
  218. }
  219. type fieldsMap struct {
  220. content map[string]streamFieldStore
  221. isSchemaless bool
  222. defaultStream ast.StreamName
  223. }
  224. func newFieldsMap(isSchemaless bool, defaultStream ast.StreamName) *fieldsMap {
  225. return &fieldsMap{content: make(map[string]streamFieldStore), isSchemaless: isSchemaless, defaultStream: defaultStream}
  226. }
  227. func (f *fieldsMap) reserve(fieldName string, streamName ast.StreamName) {
  228. lname := strings.ToLower(fieldName)
  229. if fm, ok := f.content[lname]; ok {
  230. fm.add(streamName)
  231. } else {
  232. fm := newStreamFieldStore(f.isSchemaless, f.defaultStream)
  233. fm.add(streamName)
  234. f.content[lname] = fm
  235. }
  236. }
  237. func (f *fieldsMap) save(fieldName string, streamName ast.StreamName, field *ast.AliasRef) error {
  238. lname := strings.ToLower(fieldName)
  239. fm, ok := f.content[lname]
  240. if !ok {
  241. if streamName == ast.AliasStream || f.isSchemaless {
  242. fm = newStreamFieldStore(f.isSchemaless, f.defaultStream)
  243. f.content[lname] = fm
  244. } else {
  245. return fmt.Errorf("unknown field %s", fieldName)
  246. }
  247. }
  248. err := fm.ref(streamName, field)
  249. if err != nil {
  250. return fmt.Errorf("%s%s", err, fieldName)
  251. }
  252. return nil
  253. }
  254. func (f *fieldsMap) bind(fr *ast.FieldRef) error {
  255. lname := strings.ToLower(fr.Name)
  256. fm, ok := f.content[lname]
  257. if !ok {
  258. if f.isSchemaless && fr.Name != "" {
  259. fm = newStreamFieldStore(f.isSchemaless, f.defaultStream)
  260. f.content[lname] = fm
  261. } else {
  262. return fmt.Errorf("unknown field %s", fr.Name)
  263. }
  264. }
  265. err := fm.bindRef(fr)
  266. if err != nil {
  267. return fmt.Errorf("%s%s", err, fr.Name)
  268. }
  269. return nil
  270. }
  271. type streamFieldStore interface {
  272. add(k ast.StreamName)
  273. ref(k ast.StreamName, v *ast.AliasRef) error
  274. bindRef(f *ast.FieldRef) error
  275. }
  276. func newStreamFieldStore(isSchemaless bool, defaultStream ast.StreamName) streamFieldStore {
  277. if !isSchemaless {
  278. return &streamFieldMap{content: make(map[ast.StreamName]*ast.AliasRef)}
  279. } else {
  280. return &streamFieldMapSchemaless{content: make(map[ast.StreamName]*ast.AliasRef), defaultStream: defaultStream}
  281. }
  282. }
  283. type streamFieldMap struct {
  284. content map[ast.StreamName]*ast.AliasRef
  285. }
  286. // add the stream name must not be default.
  287. // This is used when traversing stream schema
  288. func (s *streamFieldMap) add(k ast.StreamName) {
  289. s.content[k] = nil
  290. }
  291. //bind for schema field, all keys must be created before running bind
  292. // can bind alias & col. For alias, the stream name must be empty; For col, the field must be a col
  293. func (s *streamFieldMap) ref(k ast.StreamName, v *ast.AliasRef) error {
  294. if k == ast.AliasStream { // must not exist, save alias ref for alias
  295. _, ok := s.content[k]
  296. if ok {
  297. return fmt.Errorf("duplicate alias ")
  298. }
  299. s.content[k] = v
  300. } else { // the key must exist after the schema travers, do validation
  301. if k == ast.DefaultStream { // In schema mode, default stream won't be a key
  302. l := len(s.content)
  303. if l == 0 {
  304. return fmt.Errorf("unknow field ")
  305. } else if l == 1 {
  306. // valid, do nothing
  307. } else {
  308. return fmt.Errorf("ambiguous field ")
  309. }
  310. } else {
  311. _, ok := s.content[k]
  312. if !ok {
  313. return fmt.Errorf("unknow field %s.", k)
  314. }
  315. }
  316. }
  317. return nil
  318. }
  319. func (s *streamFieldMap) bindRef(fr *ast.FieldRef) error {
  320. l := len(s.content)
  321. if fr.StreamName == "" {
  322. fr.StreamName = ast.DefaultStream
  323. }
  324. k := fr.StreamName
  325. if k == ast.DefaultStream {
  326. switch l {
  327. case 0:
  328. return fmt.Errorf("unknown field ")
  329. case 1: // if alias, return this
  330. for sk, sv := range s.content {
  331. fr.RefSelection(sv)
  332. fr.StreamName = sk
  333. }
  334. return nil
  335. default:
  336. r, ok := s.content[ast.AliasStream] // if alias exists
  337. if ok {
  338. fr.RefSelection(r)
  339. fr.StreamName = ast.AliasStream
  340. return nil
  341. } else {
  342. return fmt.Errorf("ambiguous field ")
  343. }
  344. }
  345. } else {
  346. r, ok := s.content[k]
  347. if ok {
  348. fr.RefSelection(r)
  349. return nil
  350. } else {
  351. return fmt.Errorf("unknown field %s.", k)
  352. }
  353. }
  354. }
  355. type streamFieldMapSchemaless struct {
  356. content map[ast.StreamName]*ast.AliasRef
  357. defaultStream ast.StreamName
  358. }
  359. // add this should not be called for schemaless
  360. func (s *streamFieldMapSchemaless) add(k ast.StreamName) {
  361. s.content[k] = nil
  362. }
  363. //bind for schemaless field, create column if not exist
  364. // can bind alias & col. For alias, the stream name must be empty; For col, the field must be a col
  365. func (s *streamFieldMapSchemaless) ref(k ast.StreamName, v *ast.AliasRef) error {
  366. if k == ast.AliasStream { // must not exist
  367. _, ok := s.content[k]
  368. if ok {
  369. return fmt.Errorf("duplicate alias ")
  370. }
  371. s.content[k] = v
  372. } else { // the key may or may not exist. But always have only one default stream field.
  373. // Replace with stream name if another stream found. The key can be duplicate
  374. l := len(s.content)
  375. if k == ast.DefaultStream { // In schemaless mode, default stream can only exist when length is 1
  376. if l < 1 {
  377. // valid, do nothing
  378. } else {
  379. return fmt.Errorf("ambiguous field ")
  380. }
  381. } else {
  382. if l == 1 {
  383. for sk := range s.content {
  384. if sk == ast.DefaultStream {
  385. delete(s.content, k)
  386. }
  387. }
  388. }
  389. }
  390. }
  391. return nil
  392. }
  393. func (s *streamFieldMapSchemaless) bindRef(fr *ast.FieldRef) error {
  394. l := len(s.content)
  395. if fr.StreamName == "" || fr.StreamName == ast.DefaultStream {
  396. if l == 1 {
  397. for sk := range s.content {
  398. fr.StreamName = sk
  399. }
  400. }
  401. }
  402. k := fr.StreamName
  403. if k == ast.DefaultStream {
  404. switch l {
  405. case 0: // must be a column because alias are fields and have been traversed
  406. // reserve a hole and do nothing
  407. fr.StreamName = s.defaultStream
  408. s.content[s.defaultStream] = nil
  409. return nil
  410. case 1: // if alias or single col, return this
  411. for sk, sv := range s.content {
  412. fr.RefSelection(sv)
  413. fr.StreamName = sk
  414. }
  415. return nil
  416. default:
  417. r, ok := s.content[ast.AliasStream] // if alias exists
  418. if ok {
  419. fr.RefSelection(r)
  420. fr.StreamName = ast.AliasStream
  421. return nil
  422. } else {
  423. fr.StreamName = s.defaultStream
  424. }
  425. }
  426. }
  427. if fr.StreamName != ast.DefaultStream {
  428. r, ok := s.content[k]
  429. if !ok { // reserver a hole
  430. s.content[k] = nil
  431. } else {
  432. fr.RefSelection(r)
  433. }
  434. return nil
  435. }
  436. return fmt.Errorf("ambiguous field ")
  437. }