analyzer.go 13 KB

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