database.go 1.7 KB

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