sqliteKV.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. "bytes"
  17. "database/sql"
  18. "encoding/gob"
  19. "fmt"
  20. "github.com/lf-edge/ekuiper/pkg/errorx"
  21. _ "github.com/mattn/go-sqlite3"
  22. "os"
  23. "path"
  24. "path/filepath"
  25. "strings"
  26. )
  27. type SqliteKVStore struct {
  28. db *sql.DB
  29. table string
  30. path string
  31. }
  32. func init() {
  33. gob.Register(make(map[string]interface{}))
  34. }
  35. func GetSqliteKVStore(fpath string) (ret *SqliteKVStore) {
  36. dir, file := filepath.Split(fpath)
  37. if _, err := os.Stat(dir); os.IsNotExist(err) {
  38. os.MkdirAll(dir, os.ModePerm)
  39. }
  40. ret = new(SqliteKVStore)
  41. ret.path = path.Join(dir, "sqliteKV.db")
  42. ret.table = file
  43. return ret
  44. }
  45. func (m *SqliteKVStore) Open() error {
  46. db, err := sql.Open("sqlite3", m.path)
  47. if nil != err {
  48. return err
  49. }
  50. m.db = db
  51. sql := fmt.Sprintf("CREATE TABLE IF NOT EXISTS '%s'('key' VARCHAR(255) PRIMARY KEY, 'val' BLOB);", m.table)
  52. _, err = m.db.Exec(sql)
  53. return err
  54. }
  55. func (m *SqliteKVStore) Close() error {
  56. if nil != m.db {
  57. return m.db.Close()
  58. }
  59. return nil
  60. }
  61. func (m *SqliteKVStore) encode(value interface{}) ([]byte, error) {
  62. var buf bytes.Buffer
  63. gob.Register(value)
  64. enc := gob.NewEncoder(&buf)
  65. if err := enc.Encode(value); err != nil {
  66. return nil, err
  67. }
  68. return buf.Bytes(), nil
  69. }
  70. func (m *SqliteKVStore) Setnx(key string, value interface{}) error {
  71. b, err := m.encode(value)
  72. if nil != err {
  73. return err
  74. }
  75. sql := fmt.Sprintf("INSERT INTO %s(key,val) values(?,?);", m.table)
  76. stmt, err := m.db.Prepare(sql)
  77. _, err = stmt.Exec(key, b)
  78. stmt.Close()
  79. if nil != err && strings.Contains(err.Error(), "UNIQUE constraint failed") {
  80. return fmt.Errorf(`Item %s already exists`, key)
  81. }
  82. return err
  83. }
  84. func (m *SqliteKVStore) Set(key string, value interface{}) error {
  85. b, err := m.encode(value)
  86. if nil != err {
  87. return err
  88. }
  89. sql := fmt.Sprintf("REPLACE INTO %s(key,val) values(?,?);", m.table)
  90. stmt, err := m.db.Prepare(sql)
  91. _, err = stmt.Exec(key, b)
  92. stmt.Close()
  93. return err
  94. }
  95. func (m *SqliteKVStore) Get(key string, value interface{}) (bool, error) {
  96. sql := fmt.Sprintf("SELECT val FROM %s WHERE key='%s';", m.table, key)
  97. row := m.db.QueryRow(sql)
  98. var tmp []byte
  99. err := row.Scan(&tmp)
  100. if nil != err {
  101. return false, nil
  102. }
  103. dec := gob.NewDecoder(bytes.NewBuffer(tmp))
  104. if err := dec.Decode(value); err != nil {
  105. return false, err
  106. }
  107. return true, nil
  108. }
  109. func (m *SqliteKVStore) Delete(key string) error {
  110. sql := fmt.Sprintf("SELECT key FROM %s WHERE key='%s';", m.table, key)
  111. row := m.db.QueryRow(sql)
  112. var tmp []byte
  113. err := row.Scan(&tmp)
  114. if nil != err || 0 == len(tmp) {
  115. return errorx.NewWithCode(errorx.NOT_FOUND, fmt.Sprintf("%s is not found", key))
  116. }
  117. sql = fmt.Sprintf("DELETE FROM %s WHERE key='%s';", m.table, key)
  118. _, err = m.db.Exec(sql)
  119. return err
  120. }
  121. func (m *SqliteKVStore) Keys() ([]string, error) {
  122. keys := make([]string, 0)
  123. sql := fmt.Sprintf("SELECT key FROM %s", m.table)
  124. row, err := m.db.Query(sql)
  125. if nil != err {
  126. return nil, err
  127. }
  128. defer row.Close()
  129. for row.Next() {
  130. var val string
  131. err = row.Scan(&val)
  132. if nil != err {
  133. return nil, err
  134. } else {
  135. keys = append(keys, val)
  136. }
  137. }
  138. return keys, nil
  139. }
  140. func (m *SqliteKVStore) Clean() error {
  141. sql := fmt.Sprintf("DELETE FROM %s", m.table)
  142. _, err := m.db.Exec(sql)
  143. return err
  144. }