funcs_analytic.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 function
  15. import (
  16. "fmt"
  17. "math"
  18. "reflect"
  19. "strconv"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. "github.com/lf-edge/ekuiper/pkg/ast"
  22. "github.com/lf-edge/ekuiper/pkg/cast"
  23. )
  24. // registerAnalyticFunc registers the analytic functions
  25. // The last parameter of the function is always the partition key
  26. func registerAnalyticFunc() {
  27. builtins["changed_col"] = builtinFunc{
  28. fType: ast.FuncTypeScalar,
  29. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  30. ignoreNull, ok := args[0].(bool)
  31. if !ok {
  32. return fmt.Errorf("first arg is not a bool but got %v", args[0]), false
  33. }
  34. if ignoreNull && args[1] == nil {
  35. return nil, true
  36. }
  37. validData, ok := args[len(args)-2].(bool)
  38. if !ok {
  39. return fmt.Errorf("when arg is not a bool but got %v", args[len(args)-2]), false
  40. }
  41. if !validData {
  42. return nil, true
  43. }
  44. key := args[len(args)-1].(string)
  45. lv, err := ctx.GetState(key)
  46. if err != nil {
  47. return err, false
  48. }
  49. if !reflect.DeepEqual(args[1], lv) {
  50. err := ctx.PutState(key, args[1])
  51. if err != nil {
  52. return err, false
  53. }
  54. return args[1], true
  55. }
  56. return nil, true
  57. },
  58. val: func(_ api.FunctionContext, args []ast.Expr) error {
  59. if err := ValidateLen(2, len(args)); err != nil {
  60. return err
  61. }
  62. if ast.IsNumericArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsStringArg(args[0]) {
  63. return ProduceErrInfo(0, "boolean")
  64. }
  65. return nil
  66. },
  67. }
  68. builtins["had_changed"] = builtinFunc{
  69. fType: ast.FuncTypeScalar,
  70. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  71. l := len(args) - 2
  72. if l <= 1 {
  73. return fmt.Errorf("expect more than one arg but got %d", len(args)), false
  74. }
  75. validData, ok := args[len(args)-2].(bool)
  76. if !ok {
  77. return fmt.Errorf("when arg is not a bool but got %v", args[len(args)-2]), false
  78. }
  79. if !validData {
  80. return false, true
  81. }
  82. ignoreNull, ok := args[0].(bool)
  83. if !ok {
  84. return fmt.Errorf("first arg is not a bool but got %v", args[0]), false
  85. }
  86. key := args[len(args)-1].(string)
  87. paraLen := len(args) - 2
  88. result := false
  89. for i := 1; i < paraLen; i++ {
  90. v := args[i]
  91. k := key + strconv.Itoa(i)
  92. if ignoreNull && v == nil {
  93. continue
  94. }
  95. lv, err := ctx.GetState(k)
  96. if err != nil {
  97. return fmt.Errorf("error getting state for %s: %v", k, err), false
  98. }
  99. if !reflect.DeepEqual(v, lv) {
  100. result = true
  101. err := ctx.PutState(k, v)
  102. if err != nil {
  103. return fmt.Errorf("error setting state for %s: %v", k, err), false
  104. }
  105. }
  106. }
  107. return result, true
  108. },
  109. val: func(_ api.FunctionContext, args []ast.Expr) error {
  110. if len(args) <= 1 {
  111. return fmt.Errorf("expect more than one arg but got %d", len(args))
  112. }
  113. if ast.IsNumericArg(args[0]) || ast.IsTimeArg(args[0]) || ast.IsStringArg(args[0]) {
  114. return ProduceErrInfo(0, "bool")
  115. }
  116. return nil
  117. },
  118. }
  119. builtins["lag"] = builtinFunc{
  120. fType: ast.FuncTypeScalar,
  121. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  122. l := len(args) - 2
  123. if l != 1 && l != 2 && l != 3 {
  124. return fmt.Errorf("expect one two or three args but got %d", l), false
  125. }
  126. key := args[len(args)-1].(string)
  127. v, err := ctx.GetState(key)
  128. if err != nil {
  129. return fmt.Errorf("error getting state for %s: %v", key, err), false
  130. }
  131. validData, ok := args[len(args)-2].(bool)
  132. if !ok {
  133. return fmt.Errorf("when arg is not a bool but got %v", args[len(args)-2]), false
  134. }
  135. paraLen := len(args) - 2
  136. var rq *ringqueue = nil
  137. var rtnVal interface{} = nil
  138. // first time call, need create state for lag
  139. if v == nil {
  140. size := 0
  141. var dftVal interface{} = nil
  142. if paraLen == 3 {
  143. dftVal = args[2]
  144. }
  145. if paraLen == 1 {
  146. size = 1
  147. } else {
  148. size, err = cast.ToInt(args[1], cast.STRICT)
  149. if err != nil {
  150. return fmt.Errorf("error converting second arg %v to int: %v", args[1], err), false
  151. }
  152. }
  153. rq = newRingqueue(size)
  154. rq.fill(dftVal)
  155. err := ctx.PutState(key, rq)
  156. if err != nil {
  157. return fmt.Errorf("error setting state for %s: %v", key, err), false
  158. }
  159. } else {
  160. rq, _ = v.(*ringqueue)
  161. }
  162. if validData {
  163. rtnVal, _ = rq.fetch()
  164. rq.append(args[0])
  165. err := ctx.PutState(key, rq)
  166. if err != nil {
  167. return fmt.Errorf("error setting state for %s: %v", key, err), false
  168. }
  169. } else {
  170. rtnVal, _ = rq.peek()
  171. }
  172. return rtnVal, true
  173. },
  174. val: func(_ api.FunctionContext, args []ast.Expr) error {
  175. l := len(args)
  176. if l != 1 && l != 2 && l != 3 {
  177. return fmt.Errorf("expect one two or three args but got %d", l)
  178. }
  179. if l >= 2 {
  180. if ast.IsFloatArg(args[1]) || ast.IsTimeArg(args[1]) || ast.IsBooleanArg(args[1]) || ast.IsStringArg(args[1]) || ast.IsFieldRefArg(args[1]) {
  181. return ProduceErrInfo(1, "int")
  182. }
  183. if s, ok := args[1].(*ast.IntegerLiteral); ok {
  184. if s.Val < 0 {
  185. return fmt.Errorf("the index should not be a nagtive integer")
  186. }
  187. }
  188. }
  189. return nil
  190. },
  191. }
  192. builtins["latest"] = builtinFunc{
  193. fType: ast.FuncTypeScalar,
  194. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  195. l := len(args) - 2
  196. if l != 1 && l != 2 {
  197. return fmt.Errorf("expect one or two args but got %d", l), false
  198. }
  199. paraLen := len(args) - 2
  200. key := args[len(args)-1].(string)
  201. validData, ok := args[len(args)-2].(bool)
  202. if !ok {
  203. return fmt.Errorf("when arg is not a bool but got %v", args[len(args)-2]), false
  204. }
  205. // notice nil is ignored in latest
  206. if validData && args[0] != nil {
  207. ctx.PutState(key, args[0])
  208. return args[0], true
  209. } else {
  210. v, err := ctx.GetState(key)
  211. if err != nil {
  212. return fmt.Errorf("error getting state for %s: %v", key, err), false
  213. }
  214. if v == nil {
  215. if paraLen == 2 {
  216. return args[1], true
  217. } else {
  218. return nil, true
  219. }
  220. } else {
  221. return v, true
  222. }
  223. }
  224. },
  225. val: func(_ api.FunctionContext, args []ast.Expr) error {
  226. l := len(args)
  227. if l != 1 && l != 2 {
  228. return fmt.Errorf("expect one or two args but got %d", l)
  229. }
  230. return nil
  231. },
  232. }
  233. }
  234. func registerGlobalAggFunc() {
  235. builtins["acc_avg"] = builtinFunc{
  236. fType: ast.FuncTypeScalar,
  237. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  238. key := args[len(args)-1].(string)
  239. keyCount := fmt.Sprintf("%s_count", key)
  240. keySum := fmt.Sprintf("%s_sum", key)
  241. v1, err := ctx.GetState(keyCount)
  242. if err != nil {
  243. return err, false
  244. }
  245. v2, err := ctx.GetState(keySum)
  246. if err != nil {
  247. return err, false
  248. }
  249. validData, ok := args[len(args)-2].(bool)
  250. if !ok {
  251. return fmt.Errorf("when arg is not a bool but got %v", args[len(args)-2]), false
  252. }
  253. if v1 == nil && v2 == nil {
  254. if args[0] == nil || !validData {
  255. return 0, true
  256. }
  257. v1 = float64(0)
  258. v2 = float64(0)
  259. } else {
  260. if args[0] == nil || !validData {
  261. count := v1.(float64)
  262. sum := v2.(float64)
  263. return sum / count, true
  264. }
  265. }
  266. count := v1.(float64)
  267. sum := v2.(float64)
  268. count = count + 1
  269. switch v := args[0].(type) {
  270. case int:
  271. sum += float64(v)
  272. case int32:
  273. sum += float64(v)
  274. case int64:
  275. sum += float64(v)
  276. case float32:
  277. sum += float64(v)
  278. case float64:
  279. sum += v
  280. default:
  281. return fmt.Errorf("the value should be number"), false
  282. }
  283. if err := ctx.PutState(keyCount, count); err != nil {
  284. return err, false
  285. }
  286. if err := ctx.PutState(keySum, sum); err != nil {
  287. return err, false
  288. }
  289. return sum / count, true
  290. },
  291. val: func(ctx api.FunctionContext, args []ast.Expr) error {
  292. return nil
  293. },
  294. }
  295. builtins["acc_max"] = builtinFunc{
  296. fType: ast.FuncTypeScalar,
  297. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  298. key := args[len(args)-1].(string)
  299. val, err := ctx.GetState(key)
  300. if err != nil {
  301. return err, false
  302. }
  303. validData, ok := args[len(args)-2].(bool)
  304. if !ok {
  305. return fmt.Errorf("when arg is not a bool but got %v", args[len(args)-2]), false
  306. }
  307. if val == nil {
  308. if !validData {
  309. return nil, false
  310. }
  311. val = float64(math.MinInt64)
  312. }
  313. m := val.(float64)
  314. if !validData {
  315. return m, true
  316. }
  317. switch v := args[0].(type) {
  318. case int:
  319. v1 := float64(v)
  320. m = getMax(m, v1)
  321. case int32:
  322. v1 := float64(v)
  323. m = getMax(m, v1)
  324. case int64:
  325. v1 := float64(v)
  326. m = getMax(m, v1)
  327. case float32:
  328. v1 := float64(v)
  329. m = getMax(m, v1)
  330. case float64:
  331. m = getMax(m, v)
  332. default:
  333. return fmt.Errorf("the value should be number"), false
  334. }
  335. if err := ctx.PutState(key, m); err != nil {
  336. return err, false
  337. }
  338. return m, true
  339. },
  340. val: func(ctx api.FunctionContext, args []ast.Expr) error {
  341. return ValidateLen(1, len(args))
  342. },
  343. }
  344. builtins["acc_min"] = builtinFunc{
  345. fType: ast.FuncTypeScalar,
  346. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  347. key := args[len(args)-1].(string)
  348. val, err := ctx.GetState(key)
  349. if err != nil {
  350. return err, false
  351. }
  352. validData, ok := args[len(args)-2].(bool)
  353. if !ok {
  354. return fmt.Errorf("when arg is not a bool but got %v", args[len(args)-2]), false
  355. }
  356. if val == nil {
  357. if !validData {
  358. return nil, false
  359. }
  360. val = float64(math.MaxInt64)
  361. }
  362. m := val.(float64)
  363. if !validData {
  364. return m, true
  365. }
  366. switch v := args[0].(type) {
  367. case int:
  368. v1 := float64(v)
  369. m = getMin(m, v1)
  370. case int32:
  371. v1 := float64(v)
  372. m = getMin(m, v1)
  373. case int64:
  374. v1 := float64(v)
  375. m = getMin(m, v1)
  376. case float32:
  377. v1 := float64(v)
  378. m = getMin(m, v1)
  379. case float64:
  380. m = getMin(m, v)
  381. default:
  382. return fmt.Errorf("the value should be number"), false
  383. }
  384. if err := ctx.PutState(key, m); err != nil {
  385. return err, false
  386. }
  387. return m, true
  388. },
  389. val: func(ctx api.FunctionContext, args []ast.Expr) error {
  390. return ValidateLen(1, len(args))
  391. },
  392. }
  393. builtins["acc_sum"] = builtinFunc{
  394. fType: ast.FuncTypeScalar,
  395. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  396. key := args[len(args)-1].(string)
  397. val, err := ctx.GetState(key)
  398. if err != nil {
  399. return err, false
  400. }
  401. validData, ok := args[len(args)-2].(bool)
  402. if !ok {
  403. return fmt.Errorf("when arg is not a bool but got %v", args[len(args)-2]), false
  404. }
  405. if val == nil {
  406. if !validData {
  407. return nil, false
  408. }
  409. val = float64(0)
  410. }
  411. accu := val.(float64)
  412. if !validData {
  413. return accu, true
  414. }
  415. switch sumValue := args[0].(type) {
  416. case int:
  417. accu += float64(sumValue)
  418. case int32:
  419. accu += float64(sumValue)
  420. case int64:
  421. accu += float64(sumValue)
  422. case float32:
  423. accu += float64(sumValue)
  424. case float64:
  425. accu += sumValue
  426. default:
  427. return fmt.Errorf("the value should be number"), false
  428. }
  429. if err := ctx.PutState(key, accu); err != nil {
  430. return err, false
  431. }
  432. return accu, true
  433. },
  434. val: func(ctx api.FunctionContext, args []ast.Expr) error {
  435. return ValidateLen(1, len(args))
  436. },
  437. }
  438. builtins["acc_count"] = builtinFunc{
  439. fType: ast.FuncTypeScalar,
  440. exec: func(ctx api.FunctionContext, args []interface{}) (interface{}, bool) {
  441. key := args[len(args)-1].(string)
  442. val, err := ctx.GetState(key)
  443. if err != nil {
  444. return err, false
  445. }
  446. validData, ok := args[len(args)-2].(bool)
  447. if !ok {
  448. return fmt.Errorf("when arg is not a bool but got %v", args[len(args)-2]), false
  449. }
  450. if val == nil {
  451. if !validData {
  452. return nil, false
  453. }
  454. val = 0
  455. }
  456. cnt := val.(int)
  457. if !validData {
  458. return cnt, true
  459. }
  460. if args[0] != nil {
  461. cnt = cnt + 1
  462. }
  463. if err := ctx.PutState(key, cnt); err != nil {
  464. return err, false
  465. }
  466. return cnt, true
  467. },
  468. val: func(ctx api.FunctionContext, args []ast.Expr) error {
  469. return ValidateLen(1, len(args))
  470. },
  471. }
  472. }
  473. func getMax(a, b float64) float64 {
  474. if a > b {
  475. return a
  476. }
  477. return b
  478. }
  479. func getMin(a, b float64) float64 {
  480. if a < b {
  481. return a
  482. }
  483. return b
  484. }