analyzer.go 11 KB

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