analyzer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. lname := strings.ToLower(fieldName)
  172. if fm, ok := f.content[lname]; ok {
  173. fm.add(streamName)
  174. } else {
  175. fm := newStreamFieldStore(f.isSchemaless, f.defaultStream)
  176. fm.add(streamName)
  177. f.content[lname] = fm
  178. }
  179. }
  180. func (f *fieldsMap) save(fieldName string, streamName ast.StreamName, field *ast.AliasRef) error {
  181. lname := strings.ToLower(fieldName)
  182. fm, ok := f.content[lname]
  183. if !ok {
  184. if streamName == ast.AliasStream || f.isSchemaless {
  185. fm = newStreamFieldStore(f.isSchemaless, f.defaultStream)
  186. f.content[lname] = fm
  187. } else {
  188. return fmt.Errorf("unknown field %s", fieldName)
  189. }
  190. }
  191. err := fm.ref(streamName, field)
  192. if err != nil {
  193. return fmt.Errorf("%s%s", err, fieldName)
  194. }
  195. return nil
  196. }
  197. func (f *fieldsMap) bind(fr *ast.FieldRef) error {
  198. lname := strings.ToLower(fr.Name)
  199. fm, ok := f.content[lname]
  200. if !ok {
  201. if f.isSchemaless && fr.Name != "" {
  202. fm = newStreamFieldStore(f.isSchemaless, f.defaultStream)
  203. f.content[lname] = fm
  204. } else {
  205. return fmt.Errorf("unknown field %s", fr.Name)
  206. }
  207. }
  208. err := fm.bindRef(fr)
  209. if err != nil {
  210. return fmt.Errorf("%s%s", err, fr.Name)
  211. }
  212. return nil
  213. }
  214. func (f *fieldsMap) getDefaultName() string {
  215. for i := 0; i < 2048; i++ {
  216. key := xsql.DEFAULT_FIELD_NAME_PREFIX + strconv.Itoa(i)
  217. if _, ok := f.content[key]; !ok {
  218. return key
  219. }
  220. }
  221. return ""
  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. }