database.go 1.6 KB

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