sqlLookup.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. template string
  28. keys []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 := dburl.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{}, keys []string) 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.keys = keys
  56. s.template = fmt.Sprintf("SELECT * FROM `%s` WHERE ", datasource)
  57. return nil
  58. }
  59. func (s *sqlLookupSource) Lookup(ctx api.StreamContext, values []interface{}) ([]api.SourceTuple, error) {
  60. ctx.GetLogger().Debug("Start to lookup tuple")
  61. query := s.template
  62. for i, k := range s.keys {
  63. if i > 0 {
  64. query += " AND "
  65. }
  66. switch v := values[i].(type) {
  67. case string:
  68. query += fmt.Sprintf("`%s` = \"%s\"", k, v)
  69. default:
  70. query += fmt.Sprintf("`%s` = %v", k, v)
  71. }
  72. }
  73. ctx.GetLogger().Debugf("Query is %s", query)
  74. // TODO extract common functions
  75. rows, err := s.db.Query(query)
  76. if err != nil {
  77. return nil, err
  78. }
  79. cols, _ := rows.Columns()
  80. types, err := rows.ColumnTypes()
  81. if err != nil {
  82. return nil, err
  83. }
  84. var result []api.SourceTuple
  85. for rows.Next() {
  86. data := make(map[string]interface{})
  87. columns := make([]interface{}, len(cols))
  88. prepareValues(columns, types, cols)
  89. err := rows.Scan(columns...)
  90. if err != nil {
  91. return nil, err
  92. }
  93. scanIntoMap(data, columns, cols)
  94. result = append(result, api.NewDefaultSourceTuple(data, nil))
  95. }
  96. return result, nil
  97. }
  98. func (s *sqlLookupSource) Close(ctx api.StreamContext) error {
  99. defer func() { s.db = nil }()
  100. if s.db != nil {
  101. return s.db.Close()
  102. }
  103. return nil
  104. }
  105. func SqlLookup() api.LookupSource {
  106. return &sqlLookupSource{}
  107. }