sqlValidator.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. // Copyright 2021-2023 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 xsql
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/pkg/ast"
  18. )
  19. // Validate select statement without context.
  20. // This is the pre-validation. In planner, there will be a more comprehensive validation after binding
  21. func Validate(stmt *ast.SelectStatement) error {
  22. if HasAggFuncs(stmt.Condition) {
  23. return fmt.Errorf("Not allowed to call aggregate functions in WHERE clause.")
  24. }
  25. for _, d := range stmt.Dimensions {
  26. if HasAggFuncs(d.Expr) {
  27. return fmt.Errorf("Not allowed to call aggregate functions in GROUP BY clause.")
  28. }
  29. }
  30. if err := validateSRFNestedForbidden("select", stmt.Fields); err != nil {
  31. return err
  32. }
  33. if err := validateMultiSRFForbidden("select", stmt.Fields); err != nil {
  34. return err
  35. }
  36. if err := validateWindowFunction(stmt); err != nil {
  37. return err
  38. }
  39. return validateSRFForbidden(stmt)
  40. }
  41. func validateWindowFunction(stmt *ast.SelectStatement) error {
  42. if exists := isWindowFunctionExists(stmt); exists {
  43. return fmt.Errorf("window functions can only be in select fields")
  44. }
  45. return nil
  46. }
  47. func validateSRFNestedForbidden(clause string, node ast.Node) error {
  48. if isSRFNested(node) {
  49. return fmt.Errorf("%s clause shouldn't has nested set-returning-functions", clause)
  50. }
  51. return nil
  52. }
  53. func validateMultiSRFForbidden(clause string, node ast.Node) error {
  54. firstSRF := false
  55. nextSRF := false
  56. ast.WalkFunc(node, func(n ast.Node) bool {
  57. switch f := n.(type) {
  58. case *ast.Call:
  59. if f.FuncType == ast.FuncTypeSrf {
  60. if !firstSRF {
  61. firstSRF = true
  62. } else {
  63. nextSRF = true
  64. return false
  65. }
  66. }
  67. }
  68. return true
  69. })
  70. if nextSRF {
  71. return fmt.Errorf("%s clause shouldn't has multi set-returning-functions", clause)
  72. }
  73. return nil
  74. }
  75. func validateSRFForbidden(node ast.Node) error {
  76. if isSRFExists(node) {
  77. return fmt.Errorf("select statement shouldn't has srf except fields")
  78. }
  79. return nil
  80. }
  81. func isSRFNested(node ast.Node) bool {
  82. srfNested := false
  83. ast.WalkFunc(node, func(n ast.Node) bool {
  84. switch f := n.(type) {
  85. case *ast.Call:
  86. for _, arg := range f.Args {
  87. exists := isSRFExists(arg)
  88. if exists {
  89. srfNested = true
  90. return false
  91. }
  92. }
  93. return true
  94. }
  95. return true
  96. })
  97. return srfNested
  98. }
  99. func isWindowFunctionExists(node ast.Node) bool {
  100. exists := false
  101. ast.WalkFunc(node, func(n ast.Node) bool {
  102. switch f := n.(type) {
  103. // skip checking Fields
  104. // TODO: support window functions in order by clause lately
  105. case ast.Fields:
  106. return false
  107. case *ast.Call:
  108. if f.FuncType == ast.FuncTypeWindow {
  109. exists = true
  110. return false
  111. }
  112. }
  113. return true
  114. })
  115. return exists
  116. }
  117. func isSRFExists(node ast.Node) bool {
  118. exists := false
  119. ast.WalkFunc(node, func(n ast.Node) bool {
  120. switch f := n.(type) {
  121. // skip checking Fields
  122. case ast.Fields:
  123. return false
  124. case *ast.Call:
  125. if f.FuncType == ast.FuncTypeSrf {
  126. exists = true
  127. return false
  128. }
  129. }
  130. return true
  131. })
  132. return exists
  133. }
  134. func validateFields(stmt *ast.SelectStatement, streamNames []string) {
  135. for i, field := range stmt.Fields {
  136. stmt.Fields[i].Expr = validateExpr(field.Expr, streamNames)
  137. }
  138. for i, join := range stmt.Joins {
  139. stmt.Joins[i].Expr = validateExpr(join.Expr, streamNames)
  140. }
  141. }
  142. // validateExpr checks if the streamName of a fieldRef is existed and covert it to json filed if not exist.
  143. // The expr is the expression to be validated, and streamName is the stream name of the current select statement.
  144. // The expr only contains the expression which is possible to be used in fields and join conditions
  145. func validateExpr(expr ast.Expr, streamName []string) ast.Expr {
  146. switch e := expr.(type) {
  147. case *ast.ParenExpr:
  148. e.Expr = validateExpr(e.Expr, streamName)
  149. return e
  150. case *ast.ArrowExpr:
  151. e.Expr = validateExpr(e.Expr, streamName)
  152. return e
  153. case *ast.BracketExpr:
  154. e.Expr = validateExpr(e.Expr, streamName)
  155. return e
  156. case *ast.ColonExpr:
  157. e.Start = validateExpr(e.Start, streamName)
  158. e.End = validateExpr(e.End, streamName)
  159. return e
  160. case *ast.IndexExpr:
  161. e.Index = validateExpr(e.Index, streamName)
  162. return e
  163. case *ast.Call:
  164. for i, arg := range e.Args {
  165. e.Args[i] = validateExpr(arg, streamName)
  166. }
  167. if e.Partition != nil {
  168. for i, p := range e.Partition.Exprs {
  169. e.Partition.Exprs[i] = validateExpr(p, streamName)
  170. }
  171. }
  172. if e.WhenExpr != nil {
  173. e.WhenExpr = validateExpr(e.WhenExpr, streamName)
  174. }
  175. return e
  176. case *ast.BinaryExpr:
  177. exp := ast.BinaryExpr{}
  178. exp.OP = e.OP
  179. if e.OP == ast.DOT {
  180. exp.OP = ast.ARROW
  181. }
  182. exp.RHS = validateExpr(e.RHS, streamName)
  183. exp.LHS = validateExpr(e.LHS, streamName)
  184. return &exp
  185. case *ast.CaseExpr:
  186. e.Value = validateExpr(e.Value, streamName)
  187. e.ElseClause = validateExpr(e.ElseClause, streamName)
  188. for i, when := range e.WhenClauses {
  189. e.WhenClauses[i].Expr = validateExpr(when.Expr, streamName)
  190. e.WhenClauses[i].Result = validateExpr(when.Result, streamName)
  191. }
  192. return e
  193. case *ast.ValueSetExpr:
  194. e.ArrayExpr = validateExpr(e.ArrayExpr, streamName)
  195. for i, v := range e.LiteralExprs {
  196. e.LiteralExprs[i] = validateExpr(v, streamName)
  197. }
  198. return e
  199. case *ast.BetweenExpr:
  200. e.Higher = validateExpr(e.Higher, streamName)
  201. e.Lower = validateExpr(e.Lower, streamName)
  202. return e
  203. case *ast.LikePattern:
  204. e.Expr = validateExpr(e.Expr, streamName)
  205. return e
  206. case *ast.FieldRef:
  207. sn := string(expr.(*ast.FieldRef).StreamName)
  208. if sn != string(ast.DefaultStream) && !contains(streamName, sn) {
  209. return &ast.BinaryExpr{OP: ast.ARROW, LHS: &ast.FieldRef{Name: string(expr.(*ast.FieldRef).StreamName), StreamName: ast.DefaultStream}, RHS: &ast.JsonFieldRef{Name: expr.(*ast.FieldRef).Name}}
  210. }
  211. return expr
  212. case *ast.MetaRef:
  213. sn := string(expr.(*ast.MetaRef).StreamName)
  214. if sn != string(ast.DefaultStream) && !contains(streamName, sn) {
  215. return &ast.BinaryExpr{OP: ast.ARROW, LHS: &ast.MetaRef{Name: string(expr.(*ast.MetaRef).StreamName), StreamName: ast.DefaultStream}, RHS: &ast.JsonFieldRef{Name: expr.(*ast.MetaRef).Name}}
  216. }
  217. return expr
  218. case *ast.ColFuncField:
  219. e.Expr = validateExpr(e.Expr, streamName)
  220. return e
  221. case *ast.Wildcard:
  222. for i, replace := range e.Replace {
  223. e.Replace[i].Expr = validateExpr(replace.Expr, streamName)
  224. }
  225. return e
  226. default:
  227. return expr
  228. }
  229. }
  230. // Checks whether a slice contains an element
  231. func contains(s []string, n string) bool {
  232. for _, val := range s {
  233. if val == n {
  234. return true
  235. }
  236. }
  237. return false
  238. }
  239. func getStreamNames(stmt *ast.SelectStatement) (result []string) {
  240. if stmt == nil {
  241. return nil
  242. }
  243. for _, source := range stmt.Sources {
  244. if s, ok := source.(*ast.Table); ok {
  245. result = append(result, s.Name)
  246. if s.Alias != "" {
  247. result = append(result, s.Alias)
  248. }
  249. }
  250. }
  251. for _, join := range stmt.Joins {
  252. result = append(result, join.Name)
  253. if join.Alias != "" {
  254. result = append(result, join.Alias)
  255. }
  256. }
  257. return
  258. }