kv.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "sync"
  17. )
  18. type kvstores struct {
  19. stores map[string]KeyValue
  20. mu sync.Mutex
  21. }
  22. var stores = kvstores{
  23. stores: make(map[string]KeyValue),
  24. mu: sync.Mutex{},
  25. }
  26. var database Database
  27. type KeyValue interface {
  28. // Set key to hold string value if key does not exist otherwise return an error
  29. Setnx(key string, value interface{}) error
  30. // Set key to hold the string value. If key already holds a value, it is overwritten
  31. Set(key string, value interface{}) error
  32. Get(key string, val interface{}) (bool, error)
  33. //Must return *common.Error with NOT_FOUND error
  34. Delete(key string) error
  35. Keys() (keys []string, err error)
  36. Clean() error
  37. }
  38. func SetKVStoreDatabase(d Database) {
  39. database = d
  40. }
  41. func (s *kvstores) get(table string) (error, KeyValue) {
  42. s.mu.Lock()
  43. defer s.mu.Unlock()
  44. if store, contains := s.stores[table]; contains {
  45. return nil, store
  46. }
  47. err, store := CreateSqlKvStore(database, table)
  48. if err != nil {
  49. return err, nil
  50. }
  51. s.stores[table] = store
  52. return nil, store
  53. }
  54. func GetKVStore(table string) (error, KeyValue) {
  55. return stores.get(table)
  56. }