kvStore.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 sqlkv
  15. import (
  16. "github.com/lf-edge/ekuiper/pkg/kv"
  17. "sync"
  18. )
  19. type kvstores struct {
  20. stores map[string]kv.KeyValue
  21. mu sync.Mutex
  22. }
  23. var stores = kvstores{
  24. stores: make(map[string]kv.KeyValue),
  25. mu: sync.Mutex{},
  26. }
  27. var database Database
  28. func Setup(dataDir string) error {
  29. err, db := newSqliteDatabase(dataDir)
  30. if err != nil {
  31. return err
  32. }
  33. err = db.Connect()
  34. if err != nil {
  35. return err
  36. }
  37. database = db
  38. return nil
  39. }
  40. func Close() {
  41. if database != nil {
  42. database.Disconnect()
  43. database = nil
  44. }
  45. }
  46. func (s *kvstores) get(table string) (kv.KeyValue, error) {
  47. s.mu.Lock()
  48. defer s.mu.Unlock()
  49. if store, contains := s.stores[table]; contains {
  50. return store, nil
  51. }
  52. err, store := CreateSqlKvStore(database, table)
  53. if err != nil {
  54. return nil, err
  55. }
  56. s.stores[table] = store
  57. return store, nil
  58. }
  59. func GetKVStore(table string) (kv.KeyValue, error) {
  60. return stores.get(table)
  61. }