template.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 transform
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "text/template"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/lf-edge/ekuiper/internal/converter"
  22. "github.com/lf-edge/ekuiper/internal/converter/delimited"
  23. "github.com/lf-edge/ekuiper/pkg/ast"
  24. "github.com/lf-edge/ekuiper/pkg/message"
  25. )
  26. // TransFunc is the function to transform data
  27. // The second parameter indicates whether to select fields based on the fields property.
  28. // If it is false, then after the dataTemplate, output the result directly.
  29. // If it is true, then after the dataTemplate, select the fields based on the fields property.
  30. type TransFunc func(interface{}, bool) ([]byte, bool, error)
  31. func GenTransform(dt string, format string, schemaId string, delimiter string, fields []string) (TransFunc, error) {
  32. var (
  33. tp *template.Template = nil
  34. c message.Converter
  35. err error
  36. )
  37. switch format {
  38. case message.FormatProtobuf, message.FormatCustom:
  39. c, err = converter.GetOrCreateConverter(&ast.Options{FORMAT: format, SCHEMAID: schemaId})
  40. if err != nil {
  41. return nil, err
  42. }
  43. case message.FormatDelimited:
  44. c, err = converter.GetOrCreateConverter(&ast.Options{FORMAT: format, DELIMITER: delimiter})
  45. if err != nil {
  46. return nil, err
  47. }
  48. c.(*delimited.Converter).SetColumns(fields)
  49. case message.FormatJson:
  50. c, err = converter.GetOrCreateConverter(&ast.Options{FORMAT: format})
  51. if err != nil {
  52. return nil, err
  53. }
  54. }
  55. if dt != "" {
  56. temp, err := template.New("sink").Funcs(conf.FuncMap).Parse(dt)
  57. if err != nil {
  58. return nil, err
  59. }
  60. tp = temp
  61. }
  62. return func(d interface{}, s bool) ([]byte, bool, error) {
  63. var (
  64. bs []byte
  65. transformed bool
  66. selected bool
  67. )
  68. if tp != nil {
  69. var output bytes.Buffer
  70. err := tp.Execute(&output, d)
  71. if err != nil {
  72. return nil, false, fmt.Errorf("fail to encode data %v with dataTemplate for error %v", d, err)
  73. }
  74. bs = output.Bytes()
  75. transformed = true
  76. }
  77. // just for sinks like tdengine and sql.
  78. if !s {
  79. if transformed {
  80. return bs, true, nil
  81. }
  82. outBytes, err := json.Marshal(d)
  83. return outBytes, false, err
  84. } else {
  85. // Consider that if only the dataTemplate is needed, and the data after trans cannot be converted into map[string]interface
  86. var m interface{}
  87. var err error
  88. if transformed {
  89. m, err = SelectMap(bs, fields)
  90. } else {
  91. m, err = SelectMap(d, fields)
  92. }
  93. if err != nil && err.Error() != "fields cannot be empty" {
  94. return nil, false, fmt.Errorf("fail to decode data %s after applying dataTemplate for error %v", string(bs), err)
  95. } else if err == nil {
  96. d = m
  97. selected = true
  98. }
  99. }
  100. switch format {
  101. case message.FormatJson:
  102. if transformed && !selected {
  103. return bs, true, nil
  104. }
  105. outBytes, err := c.Encode(d)
  106. return outBytes, transformed || selected, err
  107. case message.FormatProtobuf, message.FormatCustom, message.FormatDelimited:
  108. if transformed && !selected {
  109. m := make(map[string]interface{})
  110. err := json.Unmarshal(bs, &m)
  111. if err != nil {
  112. return nil, false, fmt.Errorf("fail to decode data %s after applying dataTemplate for error %v", string(bs), err)
  113. }
  114. d = m
  115. }
  116. outBytes, err := c.Encode(d)
  117. return outBytes, transformed || selected, err
  118. default: // should not happen
  119. return nil, false, fmt.Errorf("unsupported format %v", format)
  120. }
  121. }, nil
  122. }
  123. func GenTp(dt string) (*template.Template, error) {
  124. return template.New("sink").Funcs(conf.FuncMap).Parse(dt)
  125. }
  126. // SelectMap select fields from input map or array of map.
  127. // If you do not need to convert data to []byte, you can use this function directly. Otherwise, use TransFunc.
  128. func SelectMap(input interface{}, fields []string) (interface{}, error) {
  129. if len(fields) == 0 {
  130. return input, fmt.Errorf("fields cannot be empty")
  131. }
  132. if _, ok := input.([]byte); ok {
  133. var m map[string]interface{}
  134. err := json.Unmarshal(input.([]byte), &m)
  135. if err != nil {
  136. return input, fmt.Errorf("fail to decode data %s for error %v", string(input.([]byte)), err)
  137. }
  138. input = m
  139. }
  140. outputs := make([]map[string]interface{}, 0)
  141. switch input.(type) {
  142. case map[string]interface{}:
  143. output := make(map[string]interface{})
  144. for _, field := range fields {
  145. output[field] = input.(map[string]interface{})[field]
  146. }
  147. return output, nil
  148. case []interface{}:
  149. for _, v := range input.([]interface{}) {
  150. output := make(map[string]interface{})
  151. if out, ok := v.(map[string]interface{}); !ok {
  152. return input, fmt.Errorf("unsupported type %v", input)
  153. } else {
  154. for _, field := range fields {
  155. output[field] = out[field]
  156. }
  157. outputs = append(outputs, output)
  158. }
  159. }
  160. return outputs, nil
  161. case []map[string]interface{}:
  162. for _, v := range input.([]map[string]interface{}) {
  163. output := make(map[string]interface{})
  164. for _, field := range fields {
  165. output[field] = v[field]
  166. }
  167. outputs = append(outputs, output)
  168. }
  169. return outputs, nil
  170. default:
  171. return input, fmt.Errorf("unsupported type %v", input)
  172. }
  173. }