valuer.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. // Copyright 2022-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. "math"
  18. "reflect"
  19. "regexp"
  20. "time"
  21. "github.com/lf-edge/ekuiper/internal/binder/function"
  22. "github.com/lf-edge/ekuiper/pkg/ast"
  23. "github.com/lf-edge/ekuiper/pkg/cast"
  24. )
  25. var (
  26. // implicitValueFuncs is a set of functions that event implicitly passes the value.
  27. implicitValueFuncs = map[string]bool{
  28. "window_start": true,
  29. "window_end": true,
  30. "event_time": true,
  31. }
  32. // ImplicitStateFuncs is a set of functions that read/update global state implicitly.
  33. ImplicitStateFuncs = map[string]bool{
  34. "last_hit_time": true,
  35. "last_hit_count": true,
  36. "last_agg_hit_time": true,
  37. "last_agg_hit_count": true,
  38. }
  39. )
  40. /*
  41. * Valuer definitions
  42. */
  43. // Valuer is the interface that wraps the Value() method.
  44. type Valuer interface {
  45. // Value returns the value and existence flag for a given key.
  46. Value(key, table string) (interface{}, bool)
  47. Meta(key, table string) (interface{}, bool)
  48. }
  49. // AliasValuer is used to calculate and cache the alias value
  50. type AliasValuer interface {
  51. // AliasValue Get the value of alias
  52. AliasValue(name string) (interface{}, bool)
  53. // AppendAlias set the alias result
  54. AppendAlias(key string, value interface{}) bool
  55. }
  56. // CallValuer implements the Call method for evaluating function calls.
  57. type CallValuer interface {
  58. Valuer
  59. // Call is invoked to evaluate a function call (if possible).
  60. Call(name string, funcId int, args []interface{}) (interface{}, bool)
  61. }
  62. // FuncValuer can calculate function type value like window_start and window_end
  63. type FuncValuer interface {
  64. FuncValue(key string) (interface{}, bool)
  65. }
  66. type AggregateCallValuer interface {
  67. CallValuer
  68. GetAllTuples() AggregateData
  69. GetSingleCallValuer() CallValuer
  70. }
  71. type WildcardValuer struct {
  72. Data Wildcarder
  73. }
  74. func (wv *WildcardValuer) Value(key, table string) (interface{}, bool) {
  75. if key == "*" {
  76. return wv.Data.All(table)
  77. }
  78. return nil, false
  79. }
  80. func (wv *WildcardValuer) Meta(_, _ string) (interface{}, bool) {
  81. return nil, false
  82. }
  83. // MultiValuer returns a Valuer that iterates over multiple Valuer instances
  84. // to find a match.
  85. func MultiValuer(valuers ...Valuer) Valuer {
  86. return multiValuer(valuers)
  87. }
  88. type multiValuer []Valuer
  89. func (a multiValuer) Value(key, table string) (interface{}, bool) {
  90. for _, valuer := range a {
  91. if v, ok := valuer.Value(key, table); ok {
  92. return v, true
  93. }
  94. }
  95. return nil, false
  96. }
  97. func (a multiValuer) Meta(key, table string) (interface{}, bool) {
  98. for _, valuer := range a {
  99. if v, ok := valuer.Meta(key, table); ok {
  100. return v, true
  101. }
  102. }
  103. return nil, false
  104. }
  105. func (a multiValuer) AppendAlias(key string, value interface{}) bool {
  106. for _, valuer := range a {
  107. if vv, ok := valuer.(AliasValuer); ok {
  108. if ok := vv.AppendAlias(key, value); ok {
  109. return true
  110. }
  111. }
  112. }
  113. return false
  114. }
  115. func (a multiValuer) AliasValue(key string) (interface{}, bool) {
  116. for _, valuer := range a {
  117. if vv, ok := valuer.(AliasValuer); ok {
  118. return vv.AliasValue(key)
  119. }
  120. }
  121. return nil, false
  122. }
  123. func (a multiValuer) FuncValue(key string) (interface{}, bool) {
  124. for _, valuer := range a {
  125. if vv, ok := valuer.(FuncValuer); ok {
  126. if r, ok := vv.FuncValue(key); ok {
  127. return r, true
  128. }
  129. }
  130. }
  131. return nil, false
  132. }
  133. func (a multiValuer) Call(name string, funcId int, args []interface{}) (interface{}, bool) {
  134. for _, valuer := range a {
  135. if valuer, ok := valuer.(CallValuer); ok {
  136. if v, ok := valuer.Call(name, funcId, args); ok {
  137. return v, true
  138. } else {
  139. return fmt.Errorf("call func %s error: %v", name, v), false
  140. }
  141. }
  142. }
  143. return nil, false
  144. }
  145. type multiAggregateValuer struct {
  146. data AggregateData
  147. multiValuer
  148. singleCallValuer CallValuer
  149. }
  150. func MultiAggregateValuer(data AggregateData, singleCallValuer CallValuer, valuers ...Valuer) Valuer {
  151. return &multiAggregateValuer{
  152. data: data,
  153. multiValuer: valuers,
  154. singleCallValuer: singleCallValuer,
  155. }
  156. }
  157. func (a *multiAggregateValuer) Call(name string, funcId int, args []interface{}) (interface{}, bool) {
  158. // assume the aggFuncMap already cache the custom agg funcs in IsAggFunc()
  159. isAgg := function.IsAggFunc(name)
  160. for _, valuer := range a.multiValuer {
  161. if a, ok := valuer.(AggregateCallValuer); ok && isAgg {
  162. if v, ok := a.Call(name, funcId, args); ok {
  163. return v, true
  164. } else {
  165. return fmt.Errorf("call func %s error: %v", name, v), false
  166. }
  167. } else if c, ok := valuer.(CallValuer); ok && !isAgg {
  168. if v, ok := c.Call(name, funcId, args); ok {
  169. return v, true
  170. }
  171. }
  172. }
  173. return nil, false
  174. }
  175. func (a *multiAggregateValuer) GetAllTuples() AggregateData {
  176. return a.data
  177. }
  178. func (a *multiAggregateValuer) GetSingleCallValuer() CallValuer {
  179. return a.singleCallValuer
  180. }
  181. func (a *multiAggregateValuer) AppendAlias(key string, value interface{}) bool {
  182. if vv, ok := a.data.(AliasValuer); ok {
  183. if ok := vv.AppendAlias(key, value); ok {
  184. return true
  185. }
  186. return false
  187. } else {
  188. return a.multiValuer.AppendAlias(key, value)
  189. }
  190. }
  191. func (a *multiAggregateValuer) AliasValue(key string) (interface{}, bool) {
  192. if vv, ok := a.data.(AliasValuer); ok {
  193. return vv.AliasValue(key)
  194. } else {
  195. return a.multiValuer.AliasValue(key)
  196. }
  197. }
  198. /*
  199. * Eval Logics
  200. */
  201. // Eval evaluates expr against a map.
  202. func Eval(expr ast.Expr, m Valuer) interface{} {
  203. eval := ValuerEval{Valuer: m}
  204. return eval.Eval(expr)
  205. }
  206. // ValuerEval will evaluate an expression using the Valuer.
  207. type ValuerEval struct {
  208. Valuer Valuer
  209. // IntegerFloatDivision will set the eval system to treat
  210. // a division between two integers as a floating point division.
  211. IntegerFloatDivision bool
  212. }
  213. // Eval evaluates an expression and returns a value.
  214. // map the expression to the correct valuer
  215. func (v *ValuerEval) Eval(expr ast.Expr) interface{} {
  216. if expr == nil {
  217. return nil
  218. }
  219. switch expr := expr.(type) {
  220. case *ast.BinaryExpr:
  221. return v.evalBinaryExpr(expr)
  222. case *ast.IntegerLiteral:
  223. return expr.Val
  224. case *ast.NumberLiteral:
  225. return expr.Val
  226. case *ast.ParenExpr:
  227. return v.Eval(expr.Expr)
  228. case *ast.StringLiteral:
  229. return expr.Val
  230. case *ast.BooleanLiteral:
  231. return expr.Val
  232. case *ast.ColonExpr:
  233. s, e := v.Eval(expr.Start), v.Eval(expr.End)
  234. si, err := cast.ToInt(s, cast.CONVERT_SAMEKIND)
  235. if err != nil {
  236. return fmt.Errorf("colon start %v is not int: %v", expr.Start, err)
  237. }
  238. ei, err := cast.ToInt(e, cast.CONVERT_SAMEKIND)
  239. if err != nil {
  240. return fmt.Errorf("colon end %v is not int: %v", expr.End, err)
  241. }
  242. return &BracketEvalResult{Start: si, End: ei}
  243. case *ast.IndexExpr:
  244. i := v.Eval(expr.Index)
  245. ii, err := cast.ToInt(i, cast.CONVERT_SAMEKIND)
  246. if err != nil {
  247. return fmt.Errorf("index %v is not int: %v", expr.Index, err)
  248. }
  249. return &BracketEvalResult{Start: ii, End: ii}
  250. case *ast.Call:
  251. // The analytic functions are calculated prior to all ops, so just get the cached field value
  252. if expr.Cached && expr.CachedField != "" {
  253. val, ok := v.Valuer.Value(expr.CachedField, "")
  254. if ok {
  255. return val
  256. } else {
  257. return fmt.Errorf("call %s error: %v", expr.Name, val)
  258. }
  259. }
  260. if _, ok := implicitValueFuncs[expr.Name]; ok {
  261. if vv, ok := v.Valuer.(FuncValuer); ok {
  262. val, ok := vv.FuncValue(expr.Name)
  263. if ok {
  264. return val
  265. }
  266. }
  267. } else {
  268. if valuer, ok := v.Valuer.(CallValuer); ok {
  269. var (
  270. args []interface{}
  271. ft = expr.FuncType
  272. )
  273. if _, ok := ImplicitStateFuncs[expr.Name]; ok {
  274. args = make([]interface{}, 1)
  275. // This is the implicit arg set by the filter planner
  276. // If set, it will only return the value, no updating the value
  277. if expr.Cached {
  278. args[0] = false
  279. } else {
  280. args[0] = true
  281. }
  282. if expr.Name == "last_hit_time" || expr.Name == "last_agg_hit_time" {
  283. if vv, ok := v.Valuer.(FuncValuer); ok {
  284. val, ok := vv.FuncValue("event_time")
  285. if ok {
  286. args = append(args, val)
  287. } else {
  288. return fmt.Errorf("call %s error: %v", expr.Name, val)
  289. }
  290. } else {
  291. return fmt.Errorf("call %s error: %v", expr.Name, "cannot get current time")
  292. }
  293. }
  294. val, _ := valuer.Call(expr.Name, expr.FuncId, args)
  295. return val
  296. }
  297. if len(expr.Args) > 0 {
  298. switch ft {
  299. case ast.FuncTypeAgg:
  300. args = make([]interface{}, len(expr.Args))
  301. for i, arg := range expr.Args {
  302. if aggreValuer, ok := valuer.(AggregateCallValuer); ok {
  303. args[i] = aggreValuer.GetAllTuples().AggregateEval(arg, aggreValuer.GetSingleCallValuer())
  304. } else {
  305. args[i] = v.Eval(arg)
  306. if _, ok := args[i].(error); ok {
  307. return args[i]
  308. }
  309. }
  310. }
  311. case ast.FuncTypeScalar, ast.FuncTypeSrf:
  312. args = make([]interface{}, len(expr.Args))
  313. for i, arg := range expr.Args {
  314. args[i] = v.Eval(arg)
  315. if _, ok := args[i].(error); ok {
  316. return args[i]
  317. }
  318. }
  319. case ast.FuncTypeCols:
  320. var keys []string
  321. for _, arg := range expr.Args { // In the parser, the col func arguments must be ColField
  322. cf, ok := arg.(*ast.ColFuncField)
  323. if !ok {
  324. // won't happen
  325. return fmt.Errorf("expect colFuncField but got %v", arg)
  326. }
  327. temp := v.Eval(cf.Expr)
  328. if _, ok := temp.(error); ok {
  329. return temp
  330. }
  331. switch cf.Expr.(type) {
  332. case *ast.Wildcard:
  333. m, ok := temp.(map[string]interface{})
  334. if !ok {
  335. return fmt.Errorf("wildcarder return non map result")
  336. }
  337. for kk, vv := range m {
  338. args = append(args, vv)
  339. keys = append(keys, kk)
  340. }
  341. default:
  342. args = append(args, temp)
  343. keys = append(keys, cf.Name)
  344. }
  345. }
  346. args = append(args, keys)
  347. default:
  348. // won't happen
  349. return fmt.Errorf("unknown function type")
  350. }
  351. }
  352. if function.IsAnalyticFunc(expr.Name) {
  353. // this data should be recorded or not ? default answer is yes
  354. if expr.WhenExpr != nil {
  355. validData := true
  356. temp := v.Eval(expr.WhenExpr)
  357. whenExprVal, ok := temp.(bool)
  358. if ok {
  359. validData = whenExprVal
  360. }
  361. args = append(args, validData)
  362. } else {
  363. args = append(args, true)
  364. }
  365. // analytic func must put the partition key into the args
  366. if expr.Partition != nil && len(expr.Partition.Exprs) > 0 {
  367. pk := ""
  368. for _, pe := range expr.Partition.Exprs {
  369. temp := v.Eval(pe)
  370. if _, ok := temp.(error); ok {
  371. return temp
  372. }
  373. pk += fmt.Sprintf("%v", temp)
  374. }
  375. args = append(args, pk)
  376. } else {
  377. args = append(args, "self")
  378. }
  379. }
  380. val, _ := valuer.Call(expr.Name, expr.FuncId, args)
  381. return val
  382. }
  383. }
  384. return nil
  385. case *ast.FieldRef:
  386. var t, n string
  387. if expr.IsAlias() {
  388. if valuer, ok := v.Valuer.(AliasValuer); ok {
  389. val, ok := valuer.AliasValue(expr.Name)
  390. if ok {
  391. return val
  392. } else {
  393. r := v.Eval(expr.Expression)
  394. // TODO possible performance elevation to eliminate this cal
  395. valuer.AppendAlias(expr.Name, r)
  396. return r
  397. }
  398. }
  399. } else if expr.StreamName == ast.DefaultStream {
  400. n = expr.Name
  401. } else {
  402. t = string(expr.StreamName)
  403. n = expr.Name
  404. }
  405. if n != "" {
  406. val, ok := v.Valuer.Value(n, t)
  407. if ok {
  408. return val
  409. }
  410. }
  411. return nil
  412. case *ast.MetaRef:
  413. if expr.StreamName == "" || expr.StreamName == ast.DefaultStream {
  414. val, _ := v.Valuer.Meta(expr.Name, "")
  415. return val
  416. } else {
  417. // The field specified with stream source
  418. val, _ := v.Valuer.Meta(expr.Name, string(expr.StreamName))
  419. return val
  420. }
  421. case *ast.JsonFieldRef:
  422. val, ok := v.Valuer.Value(expr.Name, "")
  423. if ok {
  424. return val
  425. } else {
  426. return nil
  427. }
  428. case *ast.Wildcard:
  429. // TODO: optimize this to avoid copy twice
  430. all, _ := v.Valuer.Value("*", "")
  431. al, ok := all.(map[string]interface{})
  432. if !ok {
  433. return fmt.Errorf("unexpected wildcard value %v", all)
  434. }
  435. val := make(map[string]interface{})
  436. for k, v := range al {
  437. if !contains(expr.Except, k) {
  438. val[k] = v
  439. }
  440. }
  441. for _, field := range expr.Replace {
  442. vi := v.Eval(field.Expr)
  443. if e, ok := vi.(error); ok {
  444. return e
  445. }
  446. val[field.AName] = vi
  447. }
  448. return val
  449. case *ast.CaseExpr:
  450. return v.evalCase(expr)
  451. case *ast.ValueSetExpr:
  452. return v.evalValueSet(expr)
  453. case *ast.BetweenExpr:
  454. return []interface{}{
  455. v.Eval(expr.Lower), v.Eval(expr.Higher),
  456. }
  457. case *ast.LikePattern:
  458. if expr.Pattern != nil {
  459. return expr.Pattern
  460. }
  461. v := v.Eval(expr.Expr)
  462. str, ok := v.(string)
  463. if !ok {
  464. return fmt.Errorf("invalid LIKE pattern, must be a string but got %v", v)
  465. }
  466. re, err := expr.Compile(str)
  467. if err != nil {
  468. return err
  469. }
  470. return re
  471. default:
  472. return nil
  473. }
  474. }
  475. func (v *ValuerEval) evalBinaryExpr(expr *ast.BinaryExpr) interface{} {
  476. lhs := v.Eval(expr.LHS)
  477. switch val := lhs.(type) {
  478. case map[string]interface{}:
  479. return v.evalJsonExpr(val, expr.OP, expr.RHS)
  480. case Message:
  481. return v.evalJsonExpr(map[string]interface{}(val), expr.OP, expr.RHS)
  482. case error:
  483. return val
  484. }
  485. // shortcut for bool
  486. switch expr.OP {
  487. case ast.AND:
  488. if bv, ok := lhs.(bool); ok && !bv {
  489. return false
  490. }
  491. case ast.OR:
  492. if bv, ok := lhs.(bool); ok && bv {
  493. return true
  494. }
  495. }
  496. if isSliceOrArray(lhs) {
  497. return v.evalJsonExpr(lhs, expr.OP, expr.RHS)
  498. }
  499. rhs := v.Eval(expr.RHS)
  500. if _, ok := rhs.(error); ok {
  501. return rhs
  502. }
  503. if isSetOperator(expr.OP) {
  504. return v.evalSetsExpr(lhs, expr.OP, rhs)
  505. }
  506. switch expr.OP {
  507. case ast.BETWEEN, ast.NOTBETWEEN:
  508. arr, ok := rhs.([]interface{})
  509. if !ok {
  510. return fmt.Errorf("between operator expects two arguments, but found %v", rhs)
  511. }
  512. andLeft := v.simpleDataEval(lhs, arr[0], ast.GTE)
  513. switch andLeft.(type) {
  514. case error:
  515. return fmt.Errorf("between operator cannot compare %[1]T(%[1]v) and %[2]T(%[2]v)", lhs, arr[0])
  516. }
  517. andRight := v.simpleDataEval(lhs, arr[1], ast.LTE)
  518. switch andRight.(type) {
  519. case error:
  520. return fmt.Errorf("between operator cannot compare %[1]T(%[1]v) and %[2]T(%[2]v)", lhs, arr[1])
  521. }
  522. r := v.simpleDataEval(andLeft, andRight, ast.AND)
  523. br, ok := r.(bool)
  524. if expr.OP == ast.NOTBETWEEN && ok {
  525. return !br
  526. } else {
  527. return r
  528. }
  529. case ast.LIKE, ast.NOTLIKE:
  530. ls, ok := lhs.(string)
  531. if !ok {
  532. return fmt.Errorf("LIKE operator left operand expects string, but found %v", lhs)
  533. }
  534. var result bool
  535. rs, ok := rhs.(*regexp.Regexp)
  536. if !ok {
  537. return fmt.Errorf("LIKE operator right operand expects string, but found %v", rhs)
  538. }
  539. result = rs.MatchString(ls)
  540. if expr.OP == ast.NOTLIKE {
  541. result = !result
  542. }
  543. return result
  544. default:
  545. return v.simpleDataEval(lhs, rhs, expr.OP)
  546. }
  547. }
  548. func (v *ValuerEval) evalCase(expr *ast.CaseExpr) interface{} {
  549. if expr.Value != nil { // compare value to all when clause
  550. ev := v.Eval(expr.Value)
  551. for _, w := range expr.WhenClauses {
  552. wv := v.Eval(w.Expr)
  553. switch r := v.simpleDataEval(ev, wv, ast.EQ).(type) {
  554. case error:
  555. return fmt.Errorf("evaluate case expression error: %s", r)
  556. case bool:
  557. if r {
  558. return v.Eval(w.Result)
  559. }
  560. }
  561. }
  562. } else {
  563. for _, w := range expr.WhenClauses {
  564. switch r := v.Eval(w.Expr).(type) {
  565. case error:
  566. return fmt.Errorf("evaluate case expression error: %s", r)
  567. case bool:
  568. if r {
  569. return v.Eval(w.Result)
  570. }
  571. }
  572. }
  573. }
  574. if expr.ElseClause != nil {
  575. return v.Eval(expr.ElseClause)
  576. }
  577. return nil
  578. }
  579. func (v *ValuerEval) evalValueSet(expr *ast.ValueSetExpr) interface{} {
  580. var valueSet []interface{}
  581. if expr.LiteralExprs != nil {
  582. for _, exp := range expr.LiteralExprs {
  583. valueSet = append(valueSet, v.Eval(exp))
  584. }
  585. return valueSet
  586. }
  587. value := v.Eval(expr.ArrayExpr)
  588. if isSliceOrArray(value) {
  589. return value
  590. }
  591. return nil
  592. }
  593. func (v *ValuerEval) evalSetsExpr(lhs interface{}, op ast.Token, rhsSet interface{}) interface{} {
  594. switch op {
  595. /*Semantic rules
  596. When using the IN operator, the following semantics apply in this order:
  597. Returns FALSE if value_set is empty.
  598. Returns NULL if search_value is NULL.
  599. Returns TRUE if value_set contains a value equal to search_value.
  600. Returns NULL if value_set contains a NULL.
  601. Returns FALSE.
  602. When using the NOT IN operator, the following semantics apply in this order:
  603. Returns TRUE if value_set is empty.
  604. Returns NULL if search_value is NULL.
  605. Returns FALSE if value_set contains a value equal to search_value.
  606. Returns NULL if value_set contains a NULL.
  607. Returns TRUE.
  608. */
  609. case ast.IN, ast.NOTIN:
  610. if rhsSet == nil {
  611. if op == ast.IN {
  612. return false
  613. } else {
  614. return true
  615. }
  616. }
  617. if lhs == nil {
  618. return nil
  619. }
  620. rhsSetVals := reflect.ValueOf(rhsSet)
  621. for i := 0; i < rhsSetVals.Len(); i++ {
  622. switch r := v.simpleDataEval(lhs, rhsSetVals.Index(i).Interface(), ast.EQ).(type) {
  623. case error:
  624. return fmt.Errorf("evaluate in expression error: %s", r)
  625. case bool:
  626. if r {
  627. if op == ast.IN {
  628. return true
  629. } else {
  630. return false
  631. }
  632. }
  633. }
  634. }
  635. if op == ast.IN {
  636. return false
  637. } else {
  638. return true
  639. }
  640. default:
  641. return fmt.Errorf("%v is an invalid operation for %T", op, lhs)
  642. }
  643. }
  644. func (v *ValuerEval) evalJsonExpr(result interface{}, op ast.Token, expr ast.Expr) interface{} {
  645. switch op {
  646. case ast.ARROW:
  647. if val, ok := result.(map[string]interface{}); ok {
  648. switch e := expr.(type) {
  649. case *ast.JsonFieldRef:
  650. ve := &ValuerEval{Valuer: Message(val)}
  651. return ve.Eval(e)
  652. default:
  653. return fmt.Errorf("the right expression is not a field reference node")
  654. }
  655. } else {
  656. return fmt.Errorf("the result %v is not a type of map[string]interface{}", result)
  657. }
  658. case ast.SUBSET:
  659. if isSliceOrArray(result) {
  660. return v.subset(result, expr)
  661. } else {
  662. return fmt.Errorf("%v is an invalid operation for %T", op, result)
  663. }
  664. default:
  665. return fmt.Errorf("%v is an invalid operation for %T", op, result)
  666. }
  667. }
  668. func (v *ValuerEval) subset(result interface{}, expr ast.Expr) interface{} {
  669. val := reflect.ValueOf(result)
  670. ber := v.Eval(expr)
  671. if berVal, ok1 := ber.(*BracketEvalResult); ok1 {
  672. if berVal.isIndex() {
  673. if 0 > berVal.Start {
  674. if 0 > berVal.Start+val.Len() {
  675. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  676. }
  677. berVal.Start += val.Len()
  678. } else if berVal.Start >= val.Len() {
  679. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  680. }
  681. return val.Index(berVal.Start).Interface()
  682. } else {
  683. if 0 > berVal.Start {
  684. if 0 > berVal.Start+val.Len() {
  685. return fmt.Errorf("out of index: %d of %d", berVal.Start, val.Len())
  686. }
  687. berVal.Start += val.Len()
  688. } else if berVal.Start >= val.Len() {
  689. return fmt.Errorf("start value is out of index: %d of %d", berVal.Start, val.Len())
  690. }
  691. if math.MinInt32 == berVal.End {
  692. berVal.End = val.Len()
  693. } else if 0 > berVal.End {
  694. if 0 > berVal.End+val.Len() {
  695. return fmt.Errorf("out of index: %d of %d", berVal.End, val.Len())
  696. }
  697. berVal.End += val.Len()
  698. } else if berVal.End > val.Len() {
  699. return fmt.Errorf("end value is out of index: %d of %d", berVal.End, val.Len())
  700. } else if berVal.Start >= berVal.End {
  701. return fmt.Errorf("start cannot be greater than end. start:%d end:%d", berVal.Start, berVal.End)
  702. }
  703. return val.Slice(berVal.Start, berVal.End).Interface()
  704. }
  705. } else {
  706. return fmt.Errorf("invalid evaluation result - %v", berVal)
  707. }
  708. }
  709. // lhs and rhs are non-nil
  710. func (v *ValuerEval) simpleDataEval(lhs, rhs interface{}, op ast.Token) interface{} {
  711. if lhs == nil || rhs == nil {
  712. switch op {
  713. case ast.EQ, ast.LTE, ast.GTE:
  714. if lhs == nil && rhs == nil {
  715. return true
  716. } else {
  717. return false
  718. }
  719. case ast.NEQ:
  720. if lhs == nil && rhs == nil {
  721. return false
  722. } else {
  723. return true
  724. }
  725. case ast.LT, ast.GT:
  726. return false
  727. default:
  728. return nil
  729. }
  730. }
  731. lhs = convertNum(lhs)
  732. rhs = convertNum(rhs)
  733. // Evaluate if both sides are simple types.
  734. switch lhs := lhs.(type) {
  735. case bool:
  736. rhs, ok := rhs.(bool)
  737. if !ok {
  738. return invalidOpError(lhs, op, rhs)
  739. }
  740. switch op {
  741. case ast.AND:
  742. return lhs && rhs
  743. case ast.OR:
  744. return lhs || rhs
  745. case ast.BITWISE_AND:
  746. return lhs && rhs
  747. case ast.BITWISE_OR:
  748. return lhs || rhs
  749. case ast.BITWISE_XOR:
  750. return lhs != rhs
  751. case ast.EQ:
  752. return lhs == rhs
  753. case ast.NEQ:
  754. return lhs != rhs
  755. default:
  756. return invalidOpError(lhs, op, rhs)
  757. }
  758. case float64:
  759. // Try the rhs as a float64, int64, or uint64
  760. rhsf, ok := rhs.(float64)
  761. if !ok {
  762. switch val := rhs.(type) {
  763. case int64:
  764. rhsf, ok = float64(val), true
  765. case uint64:
  766. rhsf, ok = float64(val), true
  767. }
  768. }
  769. if !ok {
  770. return invalidOpError(lhs, op, rhs)
  771. }
  772. rhs := rhsf
  773. switch op {
  774. case ast.EQ:
  775. return lhs == rhs
  776. case ast.NEQ:
  777. return lhs != rhs
  778. case ast.LT:
  779. return lhs < rhs
  780. case ast.LTE:
  781. return lhs <= rhs
  782. case ast.GT:
  783. return lhs > rhs
  784. case ast.GTE:
  785. return lhs >= rhs
  786. case ast.ADD:
  787. return lhs + rhs
  788. case ast.SUB:
  789. return lhs - rhs
  790. case ast.MUL:
  791. return lhs * rhs
  792. case ast.DIV:
  793. if rhs == 0 {
  794. return fmt.Errorf("divided by zero")
  795. }
  796. return lhs / rhs
  797. case ast.MOD:
  798. if rhs == 0 {
  799. return fmt.Errorf("divided by zero")
  800. }
  801. return math.Mod(lhs, rhs)
  802. default:
  803. return invalidOpError(lhs, op, rhs)
  804. }
  805. case int64:
  806. // Try as a float64 to see if a float cast is required.
  807. switch rhs := rhs.(type) {
  808. case float64:
  809. lhs := float64(lhs)
  810. switch op {
  811. case ast.EQ:
  812. return lhs == rhs
  813. case ast.NEQ:
  814. return lhs != rhs
  815. case ast.LT:
  816. return lhs < rhs
  817. case ast.LTE:
  818. return lhs <= rhs
  819. case ast.GT:
  820. return lhs > rhs
  821. case ast.GTE:
  822. return lhs >= rhs
  823. case ast.ADD:
  824. return lhs + rhs
  825. case ast.SUB:
  826. return lhs - rhs
  827. case ast.MUL:
  828. return lhs * rhs
  829. case ast.DIV:
  830. if rhs == 0 {
  831. return fmt.Errorf("divided by zero")
  832. }
  833. return lhs / rhs
  834. case ast.MOD:
  835. if rhs == 0 {
  836. return fmt.Errorf("divided by zero")
  837. }
  838. return math.Mod(lhs, rhs)
  839. default:
  840. return invalidOpError(lhs, op, rhs)
  841. }
  842. case int64:
  843. switch op {
  844. case ast.EQ:
  845. return lhs == rhs
  846. case ast.NEQ:
  847. return lhs != rhs
  848. case ast.LT:
  849. return lhs < rhs
  850. case ast.LTE:
  851. return lhs <= rhs
  852. case ast.GT:
  853. return lhs > rhs
  854. case ast.GTE:
  855. return lhs >= rhs
  856. case ast.ADD:
  857. return lhs + rhs
  858. case ast.SUB:
  859. return lhs - rhs
  860. case ast.MUL:
  861. return lhs * rhs
  862. case ast.DIV:
  863. if v.IntegerFloatDivision {
  864. if rhs == 0 {
  865. return fmt.Errorf("divided by zero")
  866. }
  867. return float64(lhs) / float64(rhs)
  868. }
  869. if rhs == 0 {
  870. return fmt.Errorf("divided by zero")
  871. }
  872. return lhs / rhs
  873. case ast.MOD:
  874. if rhs == 0 {
  875. return fmt.Errorf("divided by zero")
  876. }
  877. return lhs % rhs
  878. case ast.BITWISE_AND:
  879. return lhs & rhs
  880. case ast.BITWISE_OR:
  881. return lhs | rhs
  882. case ast.BITWISE_XOR:
  883. return lhs ^ rhs
  884. default:
  885. return invalidOpError(lhs, op, rhs)
  886. }
  887. case uint64:
  888. switch op {
  889. case ast.EQ:
  890. return uint64(lhs) == rhs
  891. case ast.NEQ:
  892. return uint64(lhs) != rhs
  893. case ast.LT:
  894. if lhs < 0 {
  895. return true
  896. }
  897. return uint64(lhs) < rhs
  898. case ast.LTE:
  899. if lhs < 0 {
  900. return true
  901. }
  902. return uint64(lhs) <= rhs
  903. case ast.GT:
  904. if lhs < 0 {
  905. return false
  906. }
  907. return uint64(lhs) > rhs
  908. case ast.GTE:
  909. if lhs < 0 {
  910. return false
  911. }
  912. return uint64(lhs) >= rhs
  913. case ast.ADD:
  914. return uint64(lhs) + rhs
  915. case ast.SUB:
  916. return uint64(lhs) - rhs
  917. case ast.MUL:
  918. return uint64(lhs) * rhs
  919. case ast.DIV:
  920. if rhs == 0 {
  921. return fmt.Errorf("divided by zero")
  922. }
  923. return uint64(lhs) / rhs
  924. case ast.MOD:
  925. if rhs == 0 {
  926. return fmt.Errorf("divided by zero")
  927. }
  928. return uint64(lhs) % rhs
  929. case ast.BITWISE_AND:
  930. return uint64(lhs) & rhs
  931. case ast.BITWISE_OR:
  932. return uint64(lhs) | rhs
  933. case ast.BITWISE_XOR:
  934. return uint64(lhs) ^ rhs
  935. default:
  936. return invalidOpError(lhs, op, rhs)
  937. }
  938. default:
  939. return invalidOpError(lhs, op, rhs)
  940. }
  941. case uint64:
  942. // Try as a float64 to see if a float cast is required.
  943. switch rhs := rhs.(type) {
  944. case float64:
  945. lhs := float64(lhs)
  946. switch op {
  947. case ast.EQ:
  948. return lhs == rhs
  949. case ast.NEQ:
  950. return lhs != rhs
  951. case ast.LT:
  952. return lhs < rhs
  953. case ast.LTE:
  954. return lhs <= rhs
  955. case ast.GT:
  956. return lhs > rhs
  957. case ast.GTE:
  958. return lhs >= rhs
  959. case ast.ADD:
  960. return lhs + rhs
  961. case ast.SUB:
  962. return lhs - rhs
  963. case ast.MUL:
  964. return lhs * rhs
  965. case ast.DIV:
  966. if rhs == 0 {
  967. return fmt.Errorf("divided by zero")
  968. }
  969. return lhs / rhs
  970. case ast.MOD:
  971. if rhs == 0 {
  972. return fmt.Errorf("divided by zero")
  973. }
  974. return math.Mod(lhs, rhs)
  975. default:
  976. return invalidOpError(lhs, op, rhs)
  977. }
  978. case int64:
  979. switch op {
  980. case ast.EQ:
  981. return lhs == uint64(rhs)
  982. case ast.NEQ:
  983. return lhs != uint64(rhs)
  984. case ast.LT:
  985. if rhs < 0 {
  986. return false
  987. }
  988. return lhs < uint64(rhs)
  989. case ast.LTE:
  990. if rhs < 0 {
  991. return false
  992. }
  993. return lhs <= uint64(rhs)
  994. case ast.GT:
  995. if rhs < 0 {
  996. return true
  997. }
  998. return lhs > uint64(rhs)
  999. case ast.GTE:
  1000. if rhs < 0 {
  1001. return true
  1002. }
  1003. return lhs >= uint64(rhs)
  1004. case ast.ADD:
  1005. return lhs + uint64(rhs)
  1006. case ast.SUB:
  1007. return lhs - uint64(rhs)
  1008. case ast.MUL:
  1009. return lhs * uint64(rhs)
  1010. case ast.DIV:
  1011. if rhs == 0 {
  1012. return fmt.Errorf("divided by zero")
  1013. }
  1014. return lhs / uint64(rhs)
  1015. case ast.MOD:
  1016. if rhs == 0 {
  1017. return fmt.Errorf("divided by zero")
  1018. }
  1019. return lhs % uint64(rhs)
  1020. case ast.BITWISE_AND:
  1021. return lhs & uint64(rhs)
  1022. case ast.BITWISE_OR:
  1023. return lhs | uint64(rhs)
  1024. case ast.BITWISE_XOR:
  1025. return lhs ^ uint64(rhs)
  1026. default:
  1027. return invalidOpError(lhs, op, rhs)
  1028. }
  1029. case uint64:
  1030. switch op {
  1031. case ast.EQ:
  1032. return lhs == rhs
  1033. case ast.NEQ:
  1034. return lhs != rhs
  1035. case ast.LT:
  1036. return lhs < rhs
  1037. case ast.LTE:
  1038. return lhs <= rhs
  1039. case ast.GT:
  1040. return lhs > rhs
  1041. case ast.GTE:
  1042. return lhs >= rhs
  1043. case ast.ADD:
  1044. return lhs + rhs
  1045. case ast.SUB:
  1046. return lhs - rhs
  1047. case ast.MUL:
  1048. return lhs * rhs
  1049. case ast.DIV:
  1050. if rhs == 0 {
  1051. return fmt.Errorf("divided by zero")
  1052. }
  1053. return lhs / rhs
  1054. case ast.MOD:
  1055. if rhs == 0 {
  1056. return fmt.Errorf("divided by zero")
  1057. }
  1058. return lhs % rhs
  1059. case ast.BITWISE_AND:
  1060. return lhs & rhs
  1061. case ast.BITWISE_OR:
  1062. return lhs | rhs
  1063. case ast.BITWISE_XOR:
  1064. return lhs ^ rhs
  1065. default:
  1066. return invalidOpError(lhs, op, rhs)
  1067. }
  1068. default:
  1069. return invalidOpError(lhs, op, rhs)
  1070. }
  1071. case string:
  1072. rhss, ok := rhs.(string)
  1073. if !ok {
  1074. return invalidOpError(lhs, op, rhs)
  1075. }
  1076. switch op {
  1077. case ast.EQ:
  1078. return lhs == rhss
  1079. case ast.NEQ:
  1080. return lhs != rhss
  1081. case ast.LT:
  1082. return lhs < rhss
  1083. case ast.LTE:
  1084. return lhs <= rhss
  1085. case ast.GT:
  1086. return lhs > rhss
  1087. case ast.GTE:
  1088. return lhs >= rhss
  1089. default:
  1090. return invalidOpError(lhs, op, rhs)
  1091. }
  1092. case time.Time:
  1093. rt, err := cast.InterfaceToTime(rhs, "")
  1094. if err != nil {
  1095. return invalidOpError(lhs, op, rhs)
  1096. }
  1097. switch op {
  1098. case ast.EQ:
  1099. return lhs.Equal(rt)
  1100. case ast.NEQ:
  1101. return !lhs.Equal(rt)
  1102. case ast.LT:
  1103. return lhs.Before(rt)
  1104. case ast.LTE:
  1105. return lhs.Before(rt) || lhs.Equal(rt)
  1106. case ast.GT:
  1107. return lhs.After(rt)
  1108. case ast.GTE:
  1109. return lhs.After(rt) || lhs.Equal(rt)
  1110. default:
  1111. return invalidOpError(lhs, op, rhs)
  1112. }
  1113. default:
  1114. return invalidOpError(lhs, op, rhs)
  1115. }
  1116. }
  1117. /*
  1118. * Helper functions
  1119. */
  1120. type BracketEvalResult struct {
  1121. Start, End int
  1122. }
  1123. func (ber *BracketEvalResult) isIndex() bool {
  1124. return ber.Start == ber.End
  1125. }
  1126. func isSliceOrArray(v interface{}) bool {
  1127. kind := reflect.ValueOf(v).Kind()
  1128. return kind == reflect.Array || kind == reflect.Slice
  1129. }
  1130. func isSetOperator(op ast.Token) bool {
  1131. return op == ast.IN || op == ast.NOTIN
  1132. }
  1133. func invalidOpError(lhs interface{}, op ast.Token, rhs interface{}) error {
  1134. return fmt.Errorf("invalid operation %[1]T(%[1]v) %s %[3]T(%[3]v)", lhs, ast.Tokens[op], rhs)
  1135. }
  1136. func convertNum(para interface{}) interface{} {
  1137. if isInt(para) {
  1138. para = toInt64(para)
  1139. } else if isFloat(para) {
  1140. para = toFloat64(para)
  1141. }
  1142. return para
  1143. }
  1144. func isInt(para interface{}) bool {
  1145. switch para.(type) {
  1146. case int:
  1147. return true
  1148. case int8:
  1149. return true
  1150. case int16:
  1151. return true
  1152. case int32:
  1153. return true
  1154. case int64:
  1155. return true
  1156. }
  1157. return false
  1158. }
  1159. func toInt64(para interface{}) int64 {
  1160. if v, ok := para.(int); ok {
  1161. return int64(v)
  1162. } else if v, ok := para.(int8); ok {
  1163. return int64(v)
  1164. } else if v, ok := para.(int16); ok {
  1165. return int64(v)
  1166. } else if v, ok := para.(int32); ok {
  1167. return int64(v)
  1168. } else if v, ok := para.(int64); ok {
  1169. return v
  1170. }
  1171. return 0
  1172. }
  1173. func isFloat(para interface{}) bool {
  1174. switch para.(type) {
  1175. case float32:
  1176. return true
  1177. case float64:
  1178. return true
  1179. }
  1180. return false
  1181. }
  1182. func toFloat64(para interface{}) float64 {
  1183. if v, ok := para.(float32); ok {
  1184. return float64(v)
  1185. } else if v, ok := para.(float64); ok {
  1186. return v
  1187. }
  1188. return 0
  1189. }