sql.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. "time"
  19. driver2 "github.com/lf-edge/ekuiper/extensions/sqldatabase/driver"
  20. "github.com/lf-edge/ekuiper/extensions/sqldatabase/sqlgen"
  21. "github.com/lf-edge/ekuiper/extensions/util"
  22. "github.com/lf-edge/ekuiper/pkg/api"
  23. "github.com/lf-edge/ekuiper/pkg/cast"
  24. "github.com/xo/dburl"
  25. )
  26. type sqlConConfig struct {
  27. Interval int `json:"interval"`
  28. Url string `json:"url"`
  29. }
  30. type sqlsource struct {
  31. conf *sqlConConfig
  32. Query sqlgen.SqlQueryGenerator
  33. //The db connection instance
  34. db *sql.DB
  35. }
  36. func (m *sqlsource) Configure(_ string, props map[string]interface{}) error {
  37. cfg := &sqlConConfig{}
  38. err := cast.MapToStruct(props, cfg)
  39. if err != nil {
  40. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  41. }
  42. if cfg.Url == "" {
  43. return fmt.Errorf("property Url is required")
  44. }
  45. if cfg.Interval == 0 {
  46. return fmt.Errorf("property interval is required")
  47. }
  48. Db, err := dburl.Parse(cfg.Url)
  49. if err != nil {
  50. return fmt.Errorf("dburl.Parse %s fail with error: %v", cfg.Url, err)
  51. }
  52. generator, err := sqlgen.GetQueryGenerator(Db, props)
  53. if err != nil {
  54. return fmt.Errorf("GetQueryGenerator %s fail with error: %v", cfg.Url, err)
  55. }
  56. m.Query = generator
  57. m.conf = cfg
  58. db, err := util.Open(m.conf.Url)
  59. if err != nil {
  60. return fmt.Errorf("connection to %s Open with error %v, support build tags are %v", m.conf.Url, err, driver2.KnownBuildTags())
  61. }
  62. m.db = db
  63. return nil
  64. }
  65. func (m *sqlsource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  66. logger := ctx.GetLogger()
  67. t := time.NewTicker(time.Duration(m.conf.Interval) * time.Millisecond)
  68. defer t.Stop()
  69. for {
  70. select {
  71. case <-t.C:
  72. query, err := m.Query.SqlQueryStatement()
  73. if err != nil {
  74. logger.Errorf("Get sql query error %v", err)
  75. }
  76. logger.Debugf("Query the database with %s", query)
  77. rows, err := m.db.Query(query)
  78. if err != nil {
  79. logger.Errorf("Run sql query(%s) error %v", query, err)
  80. errCh <- err
  81. return
  82. }
  83. cols, _ := rows.Columns()
  84. types, err := rows.ColumnTypes()
  85. if err != nil {
  86. logger.Errorf("row ColumnTypes error %v", query, err)
  87. errCh <- err
  88. return
  89. }
  90. for rows.Next() {
  91. data := make(map[string]interface{})
  92. columns := make([]interface{}, len(cols))
  93. prepareValues(columns, types, cols)
  94. err := rows.Scan(columns...)
  95. if err != nil {
  96. logger.Errorf("Run sql scan(%s) error %v", query, err)
  97. errCh <- err
  98. return
  99. }
  100. scanIntoMap(data, columns, cols)
  101. m.Query.UpdateMaxIndexValue(data)
  102. consumer <- api.NewDefaultSourceTuple(data, nil)
  103. }
  104. case <-ctx.Done():
  105. return
  106. }
  107. }
  108. }
  109. func (m *sqlsource) GetOffset() (interface{}, error) {
  110. return m.Query.GetIndexValue(), nil
  111. }
  112. func (m *sqlsource) Rewind(offset interface{}) error {
  113. m.Query.SetIndexValue(offset)
  114. return nil
  115. }
  116. func (m *sqlsource) Close(ctx api.StreamContext) error {
  117. logger := ctx.GetLogger()
  118. logger.Debugf("Closing sql stream to %v", m.conf)
  119. if m.db != nil {
  120. _ = m.db.Close()
  121. }
  122. return nil
  123. }
  124. func Sql() api.Source {
  125. return &sqlsource{}
  126. }