analyzer.go 11 KB

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