analyzer.go 11 KB

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