analyzer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. f.content[key] = nil
  233. return key
  234. }
  235. }
  236. return ""
  237. }
  238. type streamFieldStore interface {
  239. add(k ast.StreamName)
  240. ref(k ast.StreamName, v *ast.AliasRef) error
  241. bindRef(f *ast.FieldRef) error
  242. }
  243. func newStreamFieldStore(isSchemaless bool, defaultStream ast.StreamName) streamFieldStore {
  244. if !isSchemaless {
  245. return &streamFieldMap{content: make(map[ast.StreamName]*ast.AliasRef)}
  246. } else {
  247. return &streamFieldMapSchemaless{content: make(map[ast.StreamName]*ast.AliasRef), defaultStream: defaultStream}
  248. }
  249. }
  250. type streamFieldMap struct {
  251. content map[ast.StreamName]*ast.AliasRef
  252. }
  253. // add the stream name must not be default.
  254. // This is used when traversing stream schema
  255. func (s *streamFieldMap) add(k ast.StreamName) {
  256. s.content[k] = nil
  257. }
  258. //bind for schema field, all keys must be created before running bind
  259. // can bind alias & col. For alias, the stream name must be empty; For col, the field must be a col
  260. func (s *streamFieldMap) ref(k ast.StreamName, v *ast.AliasRef) error {
  261. if k == ast.AliasStream { // must not exist, save alias ref for alias
  262. _, ok := s.content[k]
  263. if ok {
  264. return fmt.Errorf("duplicate alias ")
  265. }
  266. s.content[k] = v
  267. } else { // the key must exist after the schema travers, do validation
  268. if k == ast.DefaultStream { // In schema mode, default stream won't be a key
  269. l := len(s.content)
  270. if l == 0 {
  271. return fmt.Errorf("unknow field ")
  272. } else if l == 1 {
  273. // valid, do nothing
  274. } else {
  275. return fmt.Errorf("ambiguous field ")
  276. }
  277. } else {
  278. _, ok := s.content[k]
  279. if !ok {
  280. return fmt.Errorf("unknow field %s.", k)
  281. }
  282. }
  283. }
  284. return nil
  285. }
  286. func (s *streamFieldMap) bindRef(fr *ast.FieldRef) error {
  287. l := len(s.content)
  288. if fr.StreamName == "" {
  289. fr.StreamName = ast.DefaultStream
  290. }
  291. k := fr.StreamName
  292. if k == ast.DefaultStream {
  293. switch l {
  294. case 0:
  295. return fmt.Errorf("unknown field ")
  296. case 1: // if alias, return this
  297. for sk, sv := range s.content {
  298. fr.RefSelection(sv)
  299. fr.StreamName = sk
  300. }
  301. return nil
  302. default:
  303. r, ok := s.content[ast.AliasStream] // if alias exists
  304. if ok {
  305. fr.RefSelection(r)
  306. fr.StreamName = ast.AliasStream
  307. return nil
  308. } else {
  309. return fmt.Errorf("ambiguous field ")
  310. }
  311. }
  312. } else {
  313. r, ok := s.content[k]
  314. if ok {
  315. fr.RefSelection(r)
  316. return nil
  317. } else {
  318. return fmt.Errorf("unknown field %s.", k)
  319. }
  320. }
  321. }
  322. type streamFieldMapSchemaless struct {
  323. content map[ast.StreamName]*ast.AliasRef
  324. defaultStream ast.StreamName
  325. }
  326. // add this should not be called for schemaless
  327. func (s *streamFieldMapSchemaless) add(k ast.StreamName) {
  328. s.content[k] = nil
  329. }
  330. //bind for schemaless field, create column if not exist
  331. // can bind alias & col. For alias, the stream name must be empty; For col, the field must be a col
  332. func (s *streamFieldMapSchemaless) ref(k ast.StreamName, v *ast.AliasRef) error {
  333. if k == ast.AliasStream { // must not exist
  334. _, ok := s.content[k]
  335. if ok {
  336. return fmt.Errorf("duplicate alias ")
  337. }
  338. s.content[k] = v
  339. } else { // the key may or may not exist. But always have only one default stream field.
  340. // Replace with stream name if another stream found. The key can be duplicate
  341. l := len(s.content)
  342. if k == ast.DefaultStream { // In schemaless mode, default stream can only exist when length is 1
  343. if l < 1 {
  344. // valid, do nothing
  345. } else {
  346. return fmt.Errorf("ambiguous field ")
  347. }
  348. } else {
  349. if l == 1 {
  350. for sk := range s.content {
  351. if sk == ast.DefaultStream {
  352. delete(s.content, k)
  353. }
  354. }
  355. }
  356. }
  357. }
  358. return nil
  359. }
  360. func (s *streamFieldMapSchemaless) bindRef(fr *ast.FieldRef) error {
  361. l := len(s.content)
  362. if fr.StreamName == "" || fr.StreamName == ast.DefaultStream {
  363. if l == 1 {
  364. for sk := range s.content {
  365. fr.StreamName = sk
  366. }
  367. }
  368. }
  369. k := fr.StreamName
  370. if k == ast.DefaultStream {
  371. switch l {
  372. case 0: // must be a column because alias are fields and have been traversed
  373. // reserve a hole and do nothing
  374. fr.StreamName = s.defaultStream
  375. s.content[s.defaultStream] = nil
  376. return nil
  377. case 1: // if alias or single col, return this
  378. for sk, sv := range s.content {
  379. fr.RefSelection(sv)
  380. fr.StreamName = sk
  381. }
  382. return nil
  383. default:
  384. r, ok := s.content[ast.AliasStream] // if alias exists
  385. if ok {
  386. fr.RefSelection(r)
  387. fr.StreamName = ast.AliasStream
  388. return nil
  389. } else {
  390. fr.StreamName = s.defaultStream
  391. }
  392. }
  393. }
  394. if fr.StreamName != ast.DefaultStream {
  395. r, ok := s.content[k]
  396. if !ok { // reserver a hole
  397. s.content[k] = nil
  398. } else {
  399. fr.RefSelection(r)
  400. }
  401. return nil
  402. }
  403. return fmt.Errorf("ambiguous field ")
  404. }