tdengine.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // Copyright 2021 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. //go:build plugins
  15. // +build plugins
  16. package main
  17. import (
  18. "database/sql"
  19. "fmt"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. "github.com/lf-edge/ekuiper/pkg/cast"
  22. "github.com/lf-edge/ekuiper/pkg/errorx"
  23. _ "github.com/taosdata/driver-go/v2/taosSql"
  24. "reflect"
  25. "strings"
  26. )
  27. type (
  28. taosConfig struct {
  29. ProvideTs bool `json:"provideTs"`
  30. Port int `json:"port"`
  31. Ip string `json:"ip"`
  32. User string `json:"user"`
  33. Password string `json:"password"`
  34. Database string `json:"database"`
  35. Table string `json:"table"`
  36. TsFieldName string `json:"tsFieldName"`
  37. Fields []string `json:"fields"`
  38. }
  39. taosSink struct {
  40. conf *taosConfig
  41. db *sql.DB
  42. }
  43. )
  44. func (this *taosConfig) delTsField() {
  45. var auxFields []string
  46. for _, v := range this.Fields {
  47. if v != this.TsFieldName {
  48. auxFields = append(auxFields, v)
  49. }
  50. }
  51. this.Fields = auxFields
  52. }
  53. func (this *taosConfig) buildSql(ctx api.StreamContext, mapData map[string]interface{}) (string, error) {
  54. if 0 == len(mapData) {
  55. return "", fmt.Errorf("data is empty.")
  56. }
  57. if 0 == len(this.TsFieldName) {
  58. return "", fmt.Errorf("tsFieldName is empty.")
  59. }
  60. logger := ctx.GetLogger()
  61. var keys, vals []string
  62. if this.ProvideTs {
  63. if v, ok := mapData[this.TsFieldName]; !ok {
  64. return "", fmt.Errorf("Timestamp field not found : %s.", this.TsFieldName)
  65. } else {
  66. keys = append(keys, this.TsFieldName)
  67. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  68. delete(mapData, this.TsFieldName)
  69. this.delTsField()
  70. }
  71. } else {
  72. vals = append(vals, "now")
  73. keys = append(keys, this.TsFieldName)
  74. }
  75. for _, k := range this.Fields {
  76. if v, ok := mapData[k]; ok {
  77. keys = append(keys, k)
  78. if reflect.String == reflect.TypeOf(v).Kind() {
  79. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  80. } else {
  81. vals = append(vals, fmt.Sprintf(`%v`, v))
  82. }
  83. } else {
  84. logger.Warnln("not found field:", k)
  85. }
  86. }
  87. if 0 != len(this.Fields) {
  88. if len(this.Fields) < len(mapData) {
  89. logger.Warnln("some of values will be ignored.")
  90. }
  91. return fmt.Sprintf(`INSERT INTO %s (%s)VALUES(%s);`, this.Table, strings.Join(keys, `,`), strings.Join(vals, `,`)), nil
  92. }
  93. for k, v := range mapData {
  94. keys = append(keys, k)
  95. if reflect.String == reflect.TypeOf(v).Kind() {
  96. vals = append(vals, fmt.Sprintf(`"%v"`, v))
  97. } else {
  98. vals = append(vals, fmt.Sprintf(`%v`, v))
  99. }
  100. }
  101. if 0 != len(keys) {
  102. return fmt.Sprintf(`INSERT INTO %s (%s)VALUES(%s);`, this.Table, strings.Join(keys, `,`), strings.Join(vals, `,`)), nil
  103. }
  104. return "", nil
  105. }
  106. func (m *taosSink) Configure(props map[string]interface{}) error {
  107. cfg := &taosConfig{}
  108. err := cast.MapToStruct(props, cfg)
  109. if err != nil {
  110. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  111. }
  112. if cfg.Ip == "" {
  113. cfg.Ip = "127.0.0.1"
  114. }
  115. if cfg.User == "" {
  116. cfg.User = "root"
  117. }
  118. if cfg.Password == "" {
  119. cfg.Password = "taosdata"
  120. }
  121. if cfg.Database == "" {
  122. return fmt.Errorf("property database is required")
  123. }
  124. if cfg.Table == "" {
  125. return fmt.Errorf("property table is required")
  126. }
  127. if cfg.TsFieldName == "" {
  128. return fmt.Errorf("property TsFieldName is required")
  129. }
  130. m.conf = cfg
  131. return nil
  132. }
  133. func (m *taosSink) Open(ctx api.StreamContext) (err error) {
  134. logger := ctx.GetLogger()
  135. logger.Debug("Opening tdengine sink")
  136. url := fmt.Sprintf(`%s:%s@tcp(%s:%d)/%s`, m.conf.User, m.conf.Password, m.conf.Ip, m.conf.Port, m.conf.Database)
  137. m.db, err = sql.Open("taosSql", url)
  138. return err
  139. }
  140. func (m *taosSink) Collect(ctx api.StreamContext, item interface{}) error {
  141. logger := ctx.GetLogger()
  142. logger.Debugf("tdengine sink receive %s", item)
  143. sliData, ok := item.([]map[string]interface{})
  144. if !ok {
  145. return fmt.Errorf("tdengine sink receive non map slice data: %#v", item)
  146. }
  147. for _, mapData := range sliData {
  148. sql, err := m.conf.buildSql(ctx, mapData)
  149. if nil != err {
  150. return err
  151. }
  152. logger.Debugf(sql)
  153. rows, err := m.db.Query(sql)
  154. if err != nil {
  155. return fmt.Errorf("%s:%s", errorx.IOErr, err.Error())
  156. }
  157. rows.Close()
  158. }
  159. return nil
  160. }
  161. func (m *taosSink) Close(ctx api.StreamContext) error {
  162. if m.db != nil {
  163. return m.db.Close()
  164. }
  165. return nil
  166. }
  167. func Tdengine() api.Sink {
  168. return &taosSink{}
  169. }