sqlLookup.go 3.4 KB

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