analyzer.go 12 KB

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