database.go 1.7 KB

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