tdengine.go 4.9 KB

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