sqlLookup.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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. }
  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.Open(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. _, err = dburl.Parse(cfg.Url)
  51. if err != nil {
  52. return fmt.Errorf("dburl.Parse %s fail with error: %v", cfg.Url, err)
  53. }
  54. s.url = cfg.Url
  55. s.table = datasource
  56. return nil
  57. }
  58. func (s *sqlLookupSource) Lookup(ctx api.StreamContext, fields []string, keys []string, values []interface{}) ([]api.SourceTuple, error) {
  59. ctx.GetLogger().Debug("Start to lookup tuple")
  60. query := "SELECT "
  61. if len(fields) == 0 {
  62. query += "*"
  63. } else {
  64. for i, f := range fields {
  65. if i > 0 {
  66. query += ","
  67. }
  68. query += f
  69. }
  70. }
  71. query += fmt.Sprintf(" FROM %s WHERE ", s.table)
  72. for i, k := range keys {
  73. if i > 0 {
  74. query += " AND "
  75. }
  76. switch v := values[i].(type) {
  77. case string:
  78. query += fmt.Sprintf("`%s` = '%s'", k, v)
  79. default:
  80. query += fmt.Sprintf("`%s` = %v", k, v)
  81. }
  82. }
  83. ctx.GetLogger().Debugf("Query is %s", query)
  84. rows, err := s.db.Query(query)
  85. if err != nil {
  86. return nil, err
  87. }
  88. cols, _ := rows.Columns()
  89. types, err := rows.ColumnTypes()
  90. if err != nil {
  91. return nil, err
  92. }
  93. var result []api.SourceTuple
  94. for rows.Next() {
  95. data := make(map[string]interface{})
  96. columns := make([]interface{}, len(cols))
  97. prepareValues(columns, types, cols)
  98. err := rows.Scan(columns...)
  99. if err != nil {
  100. return nil, err
  101. }
  102. scanIntoMap(data, columns, cols)
  103. result = append(result, api.NewDefaultSourceTuple(data, nil))
  104. }
  105. return result, nil
  106. }
  107. func (s *sqlLookupSource) Close(ctx api.StreamContext) error {
  108. ctx.GetLogger().Debugf("Closing sql lookup source")
  109. defer func() { s.db = nil }()
  110. if s.db != nil {
  111. return s.db.Close()
  112. }
  113. return nil
  114. }
  115. func SqlLookup() api.LookupSource {
  116. return &sqlLookupSource{}
  117. }