sqlLookup.go 3.1 KB

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