analyzer.go 11 KB

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