database.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 sqlite
  15. import (
  16. "database/sql"
  17. "fmt"
  18. "os"
  19. "path"
  20. "sync"
  21. // introduce sqlite
  22. _ "modernc.org/sqlite"
  23. "github.com/lf-edge/ekuiper/internal/conf"
  24. "github.com/lf-edge/ekuiper/internal/pkg/store/definition"
  25. )
  26. type Database struct {
  27. db *sql.DB
  28. Path string
  29. mu sync.Mutex
  30. }
  31. func NewSqliteDatabase(c definition.Config, name string) (definition.Database, error) {
  32. conf.Log.Infof("use cgo disabled sqlite as store %v", name)
  33. sqliteConf := c.Sqlite
  34. dir := sqliteConf.Path
  35. if sqliteConf.Name != "" {
  36. name = sqliteConf.Name
  37. }
  38. if _, err := os.Stat(dir); os.IsNotExist(err) {
  39. os.MkdirAll(dir, os.ModePerm)
  40. }
  41. dbPath := path.Join(dir, name)
  42. return &Database{
  43. db: nil,
  44. Path: dbPath,
  45. mu: sync.Mutex{},
  46. }, nil
  47. }
  48. func (d *Database) Connect() error {
  49. db, err := sql.Open("sqlite", connectionString(d.Path))
  50. if err != nil {
  51. return err
  52. }
  53. db.SetMaxIdleConns(1)
  54. db.SetMaxOpenConns(1)
  55. db.SetConnMaxLifetime(-1)
  56. d.db = db
  57. return nil
  58. }
  59. func connectionString(dpath string) string {
  60. return fmt.Sprintf("file:%s?cache=shared&_journal=WAL&sync=2", dpath)
  61. }
  62. func (d *Database) Disconnect() error {
  63. err := d.db.Close()
  64. return err
  65. }
  66. func (d *Database) Apply(f func(db *sql.DB) error) error {
  67. d.mu.Lock()
  68. err := f(d.db)
  69. d.mu.Unlock()
  70. return err
  71. }