sqlLookup.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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 main
  15. import (
  16. "database/sql"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/extensions/util"
  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. )
  23. type sqlLookupConfig struct {
  24. Url string `json:"url"`
  25. }
  26. type sqlLookupSource struct {
  27. url string
  28. table string
  29. db *sql.DB
  30. }
  31. // Open establish a connection to the database
  32. func (s *sqlLookupSource) Open(ctx api.StreamContext) error {
  33. ctx.GetLogger().Debugf("Opening sql lookup source")
  34. db, err := util.FetchDBToOneNode(util.GlobalPool, s.url)
  35. if err != nil {
  36. return fmt.Errorf("connection to %s Open with error %v", s.url, err)
  37. }
  38. s.db = db
  39. return nil
  40. }
  41. func (s *sqlLookupSource) Configure(datasource string, props map[string]interface{}) error {
  42. cfg := &sqlLookupConfig{}
  43. err := cast.MapToStruct(props, cfg)
  44. if err != nil {
  45. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  46. }
  47. if cfg.Url == "" {
  48. return fmt.Errorf("property Url is required")
  49. }
  50. s.url = cfg.Url
  51. s.table = datasource
  52. return nil
  53. }
  54. func (s *sqlLookupSource) Lookup(ctx api.StreamContext, fields []string, keys []string, values []interface{}) ([]api.SourceTuple, error) {
  55. ctx.GetLogger().Debug("Start to lookup tuple")
  56. rcvTime := conf.GetNow()
  57. query := "SELECT "
  58. if len(fields) == 0 {
  59. query += "*"
  60. } else {
  61. for i, f := range fields {
  62. if i > 0 {
  63. query += ","
  64. }
  65. query += f
  66. }
  67. }
  68. query += fmt.Sprintf(" FROM %s WHERE ", s.table)
  69. for i, k := range keys {
  70. if i > 0 {
  71. query += " AND "
  72. }
  73. switch v := values[i].(type) {
  74. case string:
  75. query += fmt.Sprintf("`%s` = '%s'", k, v)
  76. default:
  77. query += fmt.Sprintf("`%s` = %v", k, v)
  78. }
  79. }
  80. ctx.GetLogger().Debugf("Query is %s", query)
  81. rows, err := s.db.Query(query)
  82. if err != nil {
  83. return nil, err
  84. }
  85. cols, _ := rows.Columns()
  86. types, err := rows.ColumnTypes()
  87. if err != nil {
  88. return nil, err
  89. }
  90. var result []api.SourceTuple
  91. for rows.Next() {
  92. data := make(map[string]interface{})
  93. columns := make([]interface{}, len(cols))
  94. prepareValues(columns, types, cols)
  95. err := rows.Scan(columns...)
  96. if err != nil {
  97. return nil, err
  98. }
  99. scanIntoMap(data, columns, cols)
  100. result = append(result, api.NewDefaultSourceTupleWithTime(data, nil, rcvTime))
  101. }
  102. return result, nil
  103. }
  104. func (s *sqlLookupSource) Close(ctx api.StreamContext) error {
  105. ctx.GetLogger().Debugf("Closing sql lookup source")
  106. defer func() { s.db = nil }()
  107. if s.db != nil {
  108. return util.ReturnDBFromOneNode(util.GlobalPool, s.url)
  109. }
  110. return nil
  111. }
  112. func SqlLookup() api.LookupSource {
  113. return &sqlLookupSource{}
  114. }