sqliteDatabase.go 1.5 KB

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