analyzer.go 11 KB

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