preprocessor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. package plans
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/emqx/kuiper/common"
  6. "github.com/emqx/kuiper/xsql"
  7. "github.com/emqx/kuiper/xstream/api"
  8. "math"
  9. "reflect"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. type Preprocessor struct {
  15. streamStmt *xsql.StreamStmt
  16. aliasFields xsql.Fields
  17. isSelectAll bool
  18. isEventTime bool
  19. timestampField string
  20. timestampFormat string
  21. }
  22. func NewPreprocessor(s *xsql.StreamStmt, fs xsql.Fields, iet bool, isa bool) (*Preprocessor, error) {
  23. p := &Preprocessor{streamStmt: s, aliasFields: fs, isEventTime: iet, isSelectAll: isa}
  24. if iet {
  25. if tf, ok := s.Options["TIMESTAMP"]; ok {
  26. p.timestampField = tf
  27. } else {
  28. return nil, fmt.Errorf("preprocessor is set to be event time but stream option TIMESTAMP not found")
  29. }
  30. if ts, ok := s.Options["TIMESTAMP_FORMAT"]; ok {
  31. p.timestampFormat = ts
  32. }
  33. }
  34. return p, nil
  35. }
  36. /*
  37. * input: *xsql.Tuple
  38. * output: *xsql.Tuple
  39. */
  40. func (p *Preprocessor) Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, _ *xsql.AggregateFunctionValuer) interface{} {
  41. log := ctx.GetLogger()
  42. tuple, ok := data.(*xsql.Tuple)
  43. if !ok {
  44. return fmt.Errorf("expect tuple data type")
  45. }
  46. log.Debugf("preprocessor receive %s", tuple.Message)
  47. result := make(map[string]interface{})
  48. if p.streamStmt.StreamFields != nil {
  49. for _, f := range p.streamStmt.StreamFields {
  50. if e := p.addRecField(f.FieldType, result, tuple.Message, f.Name); e != nil {
  51. return fmt.Errorf("error in preprocessor: %s", e)
  52. }
  53. }
  54. } else {
  55. if p.isSelectAll {
  56. result = tuple.Message
  57. }
  58. }
  59. //If the field has alias name, then evaluate the alias field before transfer it to proceeding operators, and put it into result.
  60. //Otherwise, the GROUP BY, ORDER BY statement cannot get the value.
  61. for _, f := range p.aliasFields {
  62. ve := &xsql.ValuerEval{Valuer: xsql.MultiValuer(tuple, fv)}
  63. v := ve.Eval(f.Expr)
  64. if _, ok := v.(error); ok {
  65. return v
  66. } else {
  67. result[f.AName] = v
  68. }
  69. }
  70. tuple.Message = result
  71. if p.isEventTime {
  72. if t, ok := result[p.timestampField]; ok {
  73. if ts, err := common.InterfaceToUnixMilli(t, p.timestampFormat); err != nil {
  74. return fmt.Errorf("cannot convert timestamp field %s to timestamp with error %v", p.timestampField, err)
  75. } else {
  76. tuple.Timestamp = ts
  77. log.Debugf("preprocessor calculate timstamp %d", tuple.Timestamp)
  78. }
  79. } else {
  80. return fmt.Errorf("cannot find timestamp field %s in tuple %v", p.timestampField, result)
  81. }
  82. }
  83. return tuple
  84. }
  85. func (p *Preprocessor) parseTime(s string) (time.Time, error) {
  86. if f, ok := p.streamStmt.Options["TIMESTAMP_FORMAT"]; ok {
  87. return common.ParseTime(s, f)
  88. } else {
  89. return time.Parse(common.JSISO, s)
  90. }
  91. }
  92. func (p *Preprocessor) addRecField(ft xsql.FieldType, r map[string]interface{}, j xsql.Message, n string) error {
  93. if t, ok := j.Value(n); ok {
  94. v := reflect.ValueOf(t)
  95. jtype := v.Kind()
  96. switch st := ft.(type) {
  97. case *xsql.BasicType:
  98. switch st.Type {
  99. case xsql.UNKNOWN:
  100. return fmt.Errorf("invalid data type unknown defined for %s, please check the stream definition", t)
  101. case xsql.BIGINT:
  102. if jtype == reflect.Int {
  103. r[n] = t.(int)
  104. } else if jtype == reflect.Float64 {
  105. if tt, ok1 := t.(float64); ok1 {
  106. if tt > math.MaxInt64 {
  107. r[n] = uint64(tt)
  108. } else {
  109. r[n] = int(tt)
  110. }
  111. }
  112. } else if jtype == reflect.String {
  113. if i, err := strconv.Atoi(t.(string)); err != nil {
  114. return fmt.Errorf("invalid data type for %s, expect bigint but found %[2]T(%[2]v)", n, t)
  115. } else {
  116. r[n] = i
  117. }
  118. } else if jtype == reflect.Uint64 {
  119. r[n] = t.(uint64)
  120. } else {
  121. return fmt.Errorf("invalid data type for %s, expect bigint but found %[2]T(%[2]v)", n, t)
  122. }
  123. case xsql.FLOAT:
  124. if jtype == reflect.Float64 {
  125. r[n] = t.(float64)
  126. } else if jtype == reflect.String {
  127. if f, err := strconv.ParseFloat(t.(string), 64); err != nil {
  128. return fmt.Errorf("invalid data type for %s, expect float but found %[2]T(%[2]v)", n, t)
  129. } else {
  130. r[n] = f
  131. }
  132. } else {
  133. return fmt.Errorf("invalid data type for %s, expect float but found %[2]T(%[2]v)", n, t)
  134. }
  135. case xsql.STRINGS:
  136. if jtype == reflect.String {
  137. r[n] = t.(string)
  138. } else {
  139. return fmt.Errorf("invalid data type for %s, expect string but found %[2]T(%[2]v)", n, t)
  140. }
  141. case xsql.DATETIME:
  142. switch jtype {
  143. case reflect.Int:
  144. ai := t.(int64)
  145. r[n] = common.TimeFromUnixMilli(ai)
  146. case reflect.Float64:
  147. ai := int64(t.(float64))
  148. r[n] = common.TimeFromUnixMilli(ai)
  149. case reflect.String:
  150. if t, err := p.parseTime(t.(string)); err != nil {
  151. return fmt.Errorf("invalid data type for %s, cannot convert to datetime: %s", n, err)
  152. } else {
  153. r[n] = t
  154. }
  155. default:
  156. return fmt.Errorf("invalid data type for %s, expect datatime but find %[2]T(%[2]v)", n, t)
  157. }
  158. case xsql.BOOLEAN:
  159. if jtype == reflect.Bool {
  160. r[n] = t.(bool)
  161. } else if jtype == reflect.String {
  162. if i, err := strconv.ParseBool(t.(string)); err != nil {
  163. return fmt.Errorf("invalid data type for %s, expect boolean but found %[2]T(%[2]v)", n, t)
  164. } else {
  165. r[n] = i
  166. }
  167. } else {
  168. return fmt.Errorf("invalid data type for %s, expect boolean but found %[2]T(%[2]v)", n, t)
  169. }
  170. default:
  171. return fmt.Errorf("invalid data type for %s, it is not supported yet", st)
  172. }
  173. case *xsql.ArrayType:
  174. var s []interface{}
  175. if t == nil {
  176. s = nil
  177. } else if jtype == reflect.Slice {
  178. s = t.([]interface{})
  179. } else if jtype == reflect.String {
  180. err := json.Unmarshal([]byte(t.(string)), &s)
  181. if err != nil {
  182. return fmt.Errorf("invalid data type for %s, expect array but found %[2]T(%[2]v)", n, t)
  183. }
  184. } else {
  185. return fmt.Errorf("invalid data type for %s, expect array but found %[2]T(%[2]v)", n, t)
  186. }
  187. if tempArr, err := p.addArrayField(st, s); err != nil {
  188. return fmt.Errorf("fail to parse field %s: %s", n, err)
  189. } else {
  190. r[n] = tempArr
  191. }
  192. case *xsql.RecType:
  193. nextJ := make(map[string]interface{})
  194. if t == nil {
  195. nextJ = nil
  196. r[n] = nextJ
  197. return nil
  198. } else if jtype == reflect.Map {
  199. nextJ, ok = t.(map[string]interface{})
  200. if !ok {
  201. return fmt.Errorf("invalid data type for %s, expect map but found %[2]T(%[2]v)", n, t)
  202. }
  203. } else if jtype == reflect.String {
  204. err := json.Unmarshal([]byte(t.(string)), &nextJ)
  205. if err != nil {
  206. return fmt.Errorf("invalid data type for %s, expect map but found %[2]T(%[2]v)", n, t)
  207. }
  208. } else {
  209. return fmt.Errorf("invalid data type for %s, expect struct but found %[2]T(%[2]v)", n, t)
  210. }
  211. nextR := make(map[string]interface{})
  212. for _, nextF := range st.StreamFields {
  213. nextP := strings.ToLower(nextF.Name)
  214. if e := p.addRecField(nextF.FieldType, nextR, nextJ, nextP); e != nil {
  215. return e
  216. }
  217. }
  218. r[n] = nextR
  219. default:
  220. return fmt.Errorf("unsupported type %T", st)
  221. }
  222. return nil
  223. } else {
  224. return fmt.Errorf("invalid data %s, field %s not found", j, n)
  225. }
  226. }
  227. //ft must be xsql.ArrayType
  228. //side effect: r[p] will be set to the new array
  229. func (p *Preprocessor) addArrayField(ft *xsql.ArrayType, srcSlice []interface{}) (interface{}, error) {
  230. if ft.FieldType != nil { //complex type array or struct
  231. switch st := ft.FieldType.(type) { //Only two complex types supported here
  232. case *xsql.ArrayType: //TODO handle array of array. Now the type is treated as interface{}
  233. if srcSlice == nil {
  234. return [][]interface{}(nil), nil
  235. }
  236. var s []interface{}
  237. var tempSlice reflect.Value
  238. for i, t := range srcSlice {
  239. jtype := reflect.ValueOf(t).Kind()
  240. if t == nil {
  241. s = nil
  242. } else if jtype == reflect.Slice || jtype == reflect.Array {
  243. s = t.([]interface{})
  244. } else if jtype == reflect.String {
  245. err := json.Unmarshal([]byte(t.(string)), &s)
  246. if err != nil {
  247. return nil, fmt.Errorf("invalid data type for [%d], expect array but found %[2]T(%[2]v)", i, t)
  248. }
  249. } else {
  250. return nil, fmt.Errorf("invalid data type for [%d], expect array but found %[2]T(%[2]v)", i, t)
  251. }
  252. if tempArr, err := p.addArrayField(st, s); err != nil {
  253. return nil, err
  254. } else {
  255. if !tempSlice.IsValid() {
  256. s := reflect.TypeOf(tempArr)
  257. tempSlice = reflect.MakeSlice(reflect.SliceOf(s), 0, 0)
  258. }
  259. tempSlice = reflect.Append(tempSlice, reflect.ValueOf(tempArr))
  260. }
  261. }
  262. return tempSlice.Interface(), nil
  263. case *xsql.RecType:
  264. if srcSlice == nil {
  265. return []map[string]interface{}(nil), nil
  266. }
  267. tempSlice := make([]map[string]interface{}, 0)
  268. for i, t := range srcSlice {
  269. jtype := reflect.ValueOf(t).Kind()
  270. j := make(map[string]interface{})
  271. var ok bool
  272. if t == nil {
  273. j = nil
  274. tempSlice = append(tempSlice, j)
  275. continue
  276. } else if jtype == reflect.Map {
  277. j, ok = t.(map[string]interface{})
  278. if !ok {
  279. return nil, fmt.Errorf("invalid data type for [%d], expect map but found %[2]T(%[2]v)", i, t)
  280. }
  281. } else if jtype == reflect.String {
  282. err := json.Unmarshal([]byte(t.(string)), &j)
  283. if err != nil {
  284. return nil, fmt.Errorf("invalid data type for [%d], expect map but found %[2]T(%[2]v)", i, t)
  285. }
  286. } else {
  287. return nil, fmt.Errorf("invalid data type for [%d], expect map but found %[2]T(%[2]v)", i, t)
  288. }
  289. r := make(map[string]interface{})
  290. for _, f := range st.StreamFields {
  291. n := f.Name
  292. if e := p.addRecField(f.FieldType, r, j, n); e != nil {
  293. return nil, e
  294. }
  295. }
  296. tempSlice = append(tempSlice, r)
  297. }
  298. return tempSlice, nil
  299. default:
  300. return nil, fmt.Errorf("unsupported type %T", st)
  301. }
  302. } else { //basic type
  303. switch ft.Type {
  304. case xsql.UNKNOWN:
  305. return nil, fmt.Errorf("invalid data type unknown defined for %s, please checke the stream definition", srcSlice)
  306. case xsql.BIGINT:
  307. if srcSlice == nil {
  308. return []int(nil), nil
  309. }
  310. tempSlice := make([]int, 0)
  311. for i, t := range srcSlice {
  312. jtype := reflect.ValueOf(t).Kind()
  313. if jtype == reflect.Float64 {
  314. tempSlice = append(tempSlice, int(t.(float64)))
  315. } else if jtype == reflect.String {
  316. if v, err := strconv.Atoi(t.(string)); err != nil {
  317. return nil, fmt.Errorf("invalid data type for [%d], expect float but found %[2]T(%[2]v)", i, t)
  318. } else {
  319. tempSlice = append(tempSlice, v)
  320. }
  321. } else {
  322. return nil, fmt.Errorf("invalid data type for [%d], expect float but found %[2]T(%[2]v)", i, t)
  323. }
  324. }
  325. return tempSlice, nil
  326. case xsql.FLOAT:
  327. if srcSlice == nil {
  328. return []float64(nil), nil
  329. }
  330. tempSlice := make([]float64, 0)
  331. for i, t := range srcSlice {
  332. jtype := reflect.ValueOf(t).Kind()
  333. if jtype == reflect.Float64 {
  334. tempSlice = append(tempSlice, t.(float64))
  335. } else if jtype == reflect.String {
  336. if f, err := strconv.ParseFloat(t.(string), 64); err != nil {
  337. return nil, fmt.Errorf("invalid data type for [%d], expect float but found %[2]T(%[2]v)", i, t)
  338. } else {
  339. tempSlice = append(tempSlice, f)
  340. }
  341. } else {
  342. return nil, fmt.Errorf("invalid data type for [%d], expect float but found %[2]T(%[2]v)", i, t)
  343. }
  344. }
  345. return tempSlice, nil
  346. case xsql.STRINGS:
  347. if srcSlice == nil {
  348. return []string(nil), nil
  349. }
  350. tempSlice := make([]string, 0)
  351. for i, t := range srcSlice {
  352. if reflect.ValueOf(t).Kind() == reflect.String {
  353. tempSlice = append(tempSlice, t.(string))
  354. } else {
  355. return nil, fmt.Errorf("invalid data type for [%d], expect string but found %[2]T(%[2]v)", i, t)
  356. }
  357. }
  358. return tempSlice, nil
  359. case xsql.DATETIME:
  360. if srcSlice == nil {
  361. return []time.Time(nil), nil
  362. }
  363. tempSlice := make([]time.Time, 0)
  364. for i, t := range srcSlice {
  365. jtype := reflect.ValueOf(t).Kind()
  366. switch jtype {
  367. case reflect.Int:
  368. ai := t.(int64)
  369. tempSlice = append(tempSlice, common.TimeFromUnixMilli(ai))
  370. case reflect.Float64:
  371. ai := int64(t.(float64))
  372. tempSlice = append(tempSlice, common.TimeFromUnixMilli(ai))
  373. case reflect.String:
  374. if ai, err := p.parseTime(t.(string)); err != nil {
  375. return nil, fmt.Errorf("invalid data type for %s, cannot convert to datetime: %[2]T(%[2]v)", t, err)
  376. } else {
  377. tempSlice = append(tempSlice, ai)
  378. }
  379. default:
  380. return nil, fmt.Errorf("invalid data type for [%d], expect datetime but found %[2]T(%[2]v)", i, t)
  381. }
  382. }
  383. return tempSlice, nil
  384. case xsql.BOOLEAN:
  385. if srcSlice == nil {
  386. return []bool(nil), nil
  387. }
  388. tempSlice := make([]bool, 0)
  389. for i, t := range srcSlice {
  390. jtype := reflect.ValueOf(t).Kind()
  391. if jtype == reflect.Bool {
  392. tempSlice = append(tempSlice, t.(bool))
  393. } else if jtype == reflect.String {
  394. if v, err := strconv.ParseBool(t.(string)); err != nil {
  395. return nil, fmt.Errorf("invalid data type for [%d], expect boolean but found %[2]T(%[2]v)", i, t)
  396. } else {
  397. tempSlice = append(tempSlice, v)
  398. }
  399. } else {
  400. return nil, fmt.Errorf("invalid data type for [%d], expect boolean but found %[2]T(%[2]v)", i, t)
  401. }
  402. }
  403. return tempSlice, nil
  404. default:
  405. return nil, fmt.Errorf("invalid data type for %T", ft.Type)
  406. }
  407. }
  408. }