template.go 5.5 KB

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