tdengine.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // Copyright 2021-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 main
  15. import (
  16. "database/sql"
  17. "encoding/json"
  18. "fmt"
  19. "reflect"
  20. "strings"
  21. _ "github.com/taosdata/driver-go/v2/taosSql"
  22. "github.com/lf-edge/ekuiper/internal/conf"
  23. "github.com/lf-edge/ekuiper/internal/topo/transform"
  24. "github.com/lf-edge/ekuiper/pkg/api"
  25. "github.com/lf-edge/ekuiper/pkg/cast"
  26. "github.com/lf-edge/ekuiper/pkg/errorx"
  27. )
  28. type (
  29. taosConfig struct {
  30. ProvideTs bool `json:"provideTs"`
  31. Port int `json:"port"`
  32. Ip string `json:"ip"` // To be deprecated
  33. Host string `json:"host"`
  34. User string `json:"user"`
  35. Password string `json:"password"`
  36. Database string `json:"database"`
  37. Table string `json:"table"`
  38. TsFieldName string `json:"tsFieldName"`
  39. Fields []string `json:"fields"`
  40. STable string `json:"sTable"`
  41. TagFields []string `json:"tagFields"`
  42. DataTemplate string `json:"dataTemplate"`
  43. TableDataField string `json:"tableDataField"`
  44. DataField string `json:"dataField"`
  45. }
  46. taosSink struct {
  47. conf *taosConfig
  48. url string
  49. db *sql.DB
  50. }
  51. )
  52. func (t *taosConfig) delTsField() {
  53. var auxFields []string
  54. for _, v := range t.Fields {
  55. if v != t.TsFieldName {
  56. auxFields = append(auxFields, v)
  57. }
  58. }
  59. t.Fields = auxFields
  60. }
  61. func (t *taosConfig) buildSql(ctx api.StreamContext, mapData map[string]interface{}) (string, error) {
  62. if 0 == len(mapData) {
  63. return "", fmt.Errorf("data is empty.")
  64. }
  65. logger := ctx.GetLogger()
  66. var (
  67. table, sTable string
  68. keys, vals, tags []string
  69. err error
  70. )
  71. table, err = ctx.ParseTemplate(t.Table, mapData)
  72. if err != nil {
  73. logger.Errorf("parse template for table %s error: %v", t.Table, err)
  74. return "", err
  75. }
  76. sTable, err = ctx.ParseTemplate(t.STable, mapData)
  77. if err != nil {
  78. logger.Errorf("parse template for sTable %s error: %v", t.STable, err)
  79. return "", err
  80. }
  81. if t.ProvideTs {
  82. if v, ok := mapData[t.TsFieldName]; !ok {
  83. return "", fmt.Errorf("timestamp field not found : %s", t.TsFieldName)
  84. } else {
  85. keys = append(keys, t.TsFieldName)
  86. timeStamp, err := cast.ToInt64(v, cast.CONVERT_SAMEKIND)
  87. if err != nil {
  88. return "", fmt.Errorf("timestamp field can not convert to int64 : %v", v)
  89. }
  90. vals = append(vals, fmt.Sprintf(`%v`, timeStamp))
  91. }
  92. } else {
  93. vals = append(vals, "now")
  94. keys = append(keys, t.TsFieldName)
  95. }
  96. if len(t.Fields) != 0 {
  97. for _, k := range t.Fields {
  98. if k == t.TsFieldName {
  99. continue
  100. }
  101. if v, ok := mapData[k]; ok {
  102. keys = append(keys, k)
  103. if reflect.String == reflect.TypeOf(v).Kind() {
  104. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  105. } else {
  106. vals = append(vals, fmt.Sprintf(`%v`, v))
  107. }
  108. } else {
  109. logger.Warnln("not found field:", k)
  110. }
  111. }
  112. } else {
  113. for k, v := range mapData {
  114. if k == t.TsFieldName {
  115. continue
  116. }
  117. keys = append(keys, k)
  118. if reflect.String == reflect.TypeOf(v).Kind() {
  119. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  120. } else {
  121. vals = append(vals, fmt.Sprintf(`%v`, v))
  122. }
  123. }
  124. }
  125. if len(t.TagFields) > 0 {
  126. for _, v := range t.TagFields {
  127. switch mapData[v].(type) {
  128. case string:
  129. tags = append(tags, fmt.Sprintf(`"%s"`, mapData[v]))
  130. default:
  131. tags = append(tags, fmt.Sprintf(`%v`, mapData[v]))
  132. }
  133. }
  134. }
  135. sqlStr := fmt.Sprintf("%s (%s)", table, strings.Join(keys, ","))
  136. if sTable != "" {
  137. sqlStr += " using " + sTable
  138. }
  139. if len(tags) != 0 {
  140. sqlStr += " tags (" + strings.Join(tags, ",") + ")"
  141. }
  142. sqlStr += " values (" + strings.Join(vals, ",") + ")"
  143. return sqlStr, nil
  144. }
  145. func (m *taosSink) Configure(props map[string]interface{}) error {
  146. cfg := &taosConfig{
  147. User: "root",
  148. Password: "taosdata",
  149. }
  150. err := cast.MapToStruct(props, cfg)
  151. if err != nil {
  152. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  153. }
  154. if cfg.Ip != "" {
  155. conf.Log.Warnf("Deprecated: Tdengine sink ip property is deprecated, use host instead.")
  156. if cfg.Host == "" {
  157. cfg.Host = cfg.Ip
  158. }
  159. }
  160. if cfg.Host == "" {
  161. cfg.Host = "localhost"
  162. }
  163. if cfg.User == "" {
  164. return fmt.Errorf("propert user is required.")
  165. }
  166. if cfg.Password == "" {
  167. return fmt.Errorf("propert password is required.")
  168. }
  169. if cfg.Database == "" {
  170. return fmt.Errorf("property database is required")
  171. }
  172. if cfg.Table == "" {
  173. return fmt.Errorf("property table is required")
  174. }
  175. if cfg.TsFieldName == "" {
  176. return fmt.Errorf("property TsFieldName is required")
  177. }
  178. if cfg.STable != "" && len(cfg.TagFields) == 0 {
  179. return fmt.Errorf("property tagFields is required when sTable is set")
  180. }
  181. m.url = fmt.Sprintf(`%s:%s@tcp(%s)/%s`, cfg.User, cfg.Password, cast.JoinHostPortInt(cfg.Host, cfg.Port), cfg.Database)
  182. if cfg.DataField == "" {
  183. cfg.DataField = cfg.TableDataField
  184. }
  185. m.conf = cfg
  186. return nil
  187. }
  188. func (m *taosSink) Open(ctx api.StreamContext) (err error) {
  189. ctx.GetLogger().Debug("Opening tdengine sink")
  190. m.db, err = sql.Open("taosSql", m.url)
  191. return err
  192. }
  193. func (m *taosSink) Collect(ctx api.StreamContext, item interface{}) error {
  194. ctx.GetLogger().Debugf("tdengine sink receive %s", item)
  195. if m.conf.DataTemplate != "" {
  196. jsonBytes, _, err := ctx.TransformOutput(item)
  197. if err != nil {
  198. return err
  199. }
  200. tm := make(map[string]interface{})
  201. err = json.Unmarshal(jsonBytes, &tm)
  202. if err != nil {
  203. return fmt.Errorf("fail to decode data %s after applying dataTemplate for error %v", string(jsonBytes), err)
  204. }
  205. item = tm
  206. } else {
  207. tm, _, err := transform.TransItem(item, m.conf.DataField, m.conf.Fields)
  208. if err != nil {
  209. return fmt.Errorf("fail to transform data %v for error %v", item, err)
  210. }
  211. item = tm
  212. }
  213. switch v := item.(type) {
  214. case []map[string]interface{}:
  215. strSli := make([]string, len(v))
  216. for _, mapData := range v {
  217. str, err := m.conf.buildSql(ctx, mapData)
  218. if err != nil {
  219. ctx.GetLogger().Errorf("tdengine sink build sql error %v for data", err, mapData)
  220. return err
  221. }
  222. strSli = append(strSli, str)
  223. }
  224. if len(strSli) > 0 {
  225. strBatch := strings.Join(strSli, " ")
  226. return m.writeToDB(ctx, &strBatch)
  227. }
  228. return nil
  229. case map[string]interface{}:
  230. strBatch, err := m.conf.buildSql(ctx, v)
  231. if err != nil {
  232. ctx.GetLogger().Errorf("tdengine sink build sql error %v for data", err, v)
  233. return err
  234. }
  235. return m.writeToDB(ctx, &strBatch)
  236. case []interface{}:
  237. strSli := make([]string, len(v))
  238. for _, data := range v {
  239. mapData, ok := data.(map[string]interface{})
  240. if !ok {
  241. ctx.GetLogger().Errorf("unsupported type: %T", data)
  242. return fmt.Errorf("unsupported type: %T", data)
  243. }
  244. str, err := m.conf.buildSql(ctx, mapData)
  245. if err != nil {
  246. ctx.GetLogger().Errorf("tdengine sink build sql error %v for data", err, mapData)
  247. return err
  248. }
  249. strSli = append(strSli, str)
  250. }
  251. if len(strSli) > 0 {
  252. strBatch := strings.Join(strSli, " ")
  253. return m.writeToDB(ctx, &strBatch)
  254. }
  255. return nil
  256. default: // never happen
  257. return fmt.Errorf("unsupported type: %T", item)
  258. }
  259. }
  260. func (m *taosSink) writeToDB(ctx api.StreamContext, SqlVal *string) error {
  261. finalSql := "INSERT INTO " + *SqlVal + ";"
  262. ctx.GetLogger().Debugf(finalSql)
  263. rows, err := m.db.Query(finalSql)
  264. if err != nil {
  265. return fmt.Errorf("%s: %s", errorx.IOErr, err.Error())
  266. }
  267. rows.Close()
  268. return nil
  269. }
  270. func (m *taosSink) Close(ctx api.StreamContext) error {
  271. if m.db != nil {
  272. return m.db.Close()
  273. }
  274. return nil
  275. }
  276. func Tdengine() api.Sink {
  277. return &taosSink{}
  278. }