sqlValidator.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. return validateSRFForbidden(stmt)
  37. }
  38. func validateSRFNestedForbidden(clause string, node ast.Node) error {
  39. if isSRFNested(node) {
  40. return fmt.Errorf("%s clause shouldn't has nested set-returning-functions", clause)
  41. }
  42. return nil
  43. }
  44. func validateMultiSRFForbidden(clause string, node ast.Node) error {
  45. firstSRF := false
  46. nextSRF := false
  47. ast.WalkFunc(node, func(n ast.Node) bool {
  48. switch f := n.(type) {
  49. case *ast.Call:
  50. if f.FuncType == ast.FuncTypeSrf {
  51. if !firstSRF {
  52. firstSRF = true
  53. } else {
  54. nextSRF = true
  55. return false
  56. }
  57. }
  58. }
  59. return true
  60. })
  61. if nextSRF {
  62. return fmt.Errorf("%s clause shouldn't has multi set-returning-functions", clause)
  63. }
  64. return nil
  65. }
  66. func validateSRFForbidden(node ast.Node) error {
  67. if isSRFExists(node) {
  68. return fmt.Errorf("select statement shouldn't has srf except fields")
  69. }
  70. return nil
  71. }
  72. func isSRFNested(node ast.Node) bool {
  73. srfNested := false
  74. ast.WalkFunc(node, func(n ast.Node) bool {
  75. switch f := n.(type) {
  76. case *ast.Call:
  77. for _, arg := range f.Args {
  78. exists := isSRFExists(arg)
  79. if exists {
  80. srfNested = true
  81. return false
  82. }
  83. }
  84. return true
  85. }
  86. return true
  87. })
  88. return srfNested
  89. }
  90. func isSRFExists(node ast.Node) bool {
  91. exists := false
  92. ast.WalkFunc(node, func(n ast.Node) bool {
  93. switch f := n.(type) {
  94. // skip checking Fields
  95. case ast.Fields:
  96. return false
  97. case *ast.Call:
  98. if f.FuncType == ast.FuncTypeSrf {
  99. exists = true
  100. return false
  101. }
  102. }
  103. return true
  104. })
  105. return exists
  106. }
  107. func validateFields(stmt *ast.SelectStatement, streamNames []string) {
  108. for i, field := range stmt.Fields {
  109. stmt.Fields[i].Expr = validateExpr(field.Expr, streamNames)
  110. }
  111. for i, join := range stmt.Joins {
  112. stmt.Joins[i].Expr = validateExpr(join.Expr, streamNames)
  113. }
  114. }
  115. // validateExpr checks if the streamName of a fieldRef is existed and covert it to json filed if not exist.
  116. // The expr is the expression to be validated, and streamName is the stream name of the current select statement.
  117. // The expr only contains the expression which is possible to be used in fields and join conditions
  118. func validateExpr(expr ast.Expr, streamName []string) ast.Expr {
  119. switch e := expr.(type) {
  120. case *ast.ParenExpr:
  121. e.Expr = validateExpr(e.Expr, streamName)
  122. return e
  123. case *ast.ArrowExpr:
  124. e.Expr = validateExpr(e.Expr, streamName)
  125. return e
  126. case *ast.BracketExpr:
  127. e.Expr = validateExpr(e.Expr, streamName)
  128. return e
  129. case *ast.ColonExpr:
  130. e.Start = validateExpr(e.Start, streamName)
  131. e.End = validateExpr(e.End, streamName)
  132. return e
  133. case *ast.IndexExpr:
  134. e.Index = validateExpr(e.Index, streamName)
  135. return e
  136. case *ast.Call:
  137. for i, arg := range e.Args {
  138. e.Args[i] = validateExpr(arg, streamName)
  139. }
  140. if e.Partition != nil {
  141. for i, p := range e.Partition.Exprs {
  142. e.Partition.Exprs[i] = validateExpr(p, streamName)
  143. }
  144. }
  145. if e.WhenExpr != nil {
  146. e.WhenExpr = validateExpr(e.WhenExpr, streamName)
  147. }
  148. return e
  149. case *ast.BinaryExpr:
  150. exp := ast.BinaryExpr{}
  151. exp.OP = e.OP
  152. if e.OP == ast.DOT {
  153. exp.OP = ast.ARROW
  154. }
  155. exp.RHS = validateExpr(e.RHS, streamName)
  156. exp.LHS = validateExpr(e.LHS, streamName)
  157. return &exp
  158. case *ast.CaseExpr:
  159. e.Value = validateExpr(e.Value, streamName)
  160. e.ElseClause = validateExpr(e.ElseClause, streamName)
  161. for i, when := range e.WhenClauses {
  162. e.WhenClauses[i].Expr = validateExpr(when.Expr, streamName)
  163. e.WhenClauses[i].Result = validateExpr(when.Result, streamName)
  164. }
  165. return e
  166. case *ast.ValueSetExpr:
  167. e.ArrayExpr = validateExpr(e.ArrayExpr, streamName)
  168. for i, v := range e.LiteralExprs {
  169. e.LiteralExprs[i] = validateExpr(v, streamName)
  170. }
  171. return e
  172. case *ast.BetweenExpr:
  173. e.Higher = validateExpr(e.Higher, streamName)
  174. e.Lower = validateExpr(e.Lower, streamName)
  175. return e
  176. case *ast.LikePattern:
  177. e.Expr = validateExpr(e.Expr, streamName)
  178. return e
  179. case *ast.FieldRef:
  180. sn := string(expr.(*ast.FieldRef).StreamName)
  181. if sn != string(ast.DefaultStream) && !contains(streamName, sn) {
  182. 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}}
  183. }
  184. return expr
  185. case *ast.MetaRef:
  186. sn := string(expr.(*ast.MetaRef).StreamName)
  187. if sn != string(ast.DefaultStream) && !contains(streamName, sn) {
  188. 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}}
  189. }
  190. return expr
  191. case *ast.ColFuncField:
  192. e.Expr = validateExpr(e.Expr, streamName)
  193. return e
  194. case *ast.Wildcard:
  195. for i, replace := range e.Replace {
  196. e.Replace[i].Expr = validateExpr(replace.Expr, streamName)
  197. }
  198. return e
  199. default:
  200. return expr
  201. }
  202. }
  203. // Checks whether a slice contains an element
  204. func contains(s []string, n string) bool {
  205. for _, val := range s {
  206. if val == n {
  207. return true
  208. }
  209. }
  210. return false
  211. }
  212. func getStreamNames(stmt *ast.SelectStatement) (result []string) {
  213. if stmt == nil {
  214. return nil
  215. }
  216. for _, source := range stmt.Sources {
  217. if s, ok := source.(*ast.Table); ok {
  218. result = append(result, s.Name)
  219. if s.Alias != "" {
  220. result = append(result, s.Alias)
  221. }
  222. }
  223. }
  224. for _, join := range stmt.Joins {
  225. result = append(result, join.Name)
  226. if join.Alias != "" {
  227. result = append(result, join.Alias)
  228. }
  229. }
  230. return
  231. }