20#include "gflags/gflags.h"
22#include "absl/strings/str_cat.h"
27 "Path to Key-value DB file.");
36 static int Callback(
void *data,
int argc,
char **argv,
char **col_name) {
37 if (data !=
nullptr) {
38 std::string *data_str =
static_cast<std::string *
>(data);
39 *data_str = argc > 0 ? argv[0] :
"";
46 if (sqlite3_open(FLAGS_kv_db_path.c_str(), &db_) != 0) {
47 AERROR <<
"Can't open Key-Value database: " << sqlite3_errmsg(db_);
53 static const char *kCreateTableSql =
54 "CREATE TABLE IF NOT EXISTS key_value "
55 "(key VARCHAR(128) PRIMARY KEY NOT NULL, value TEXT);";
56 if (!SQL(kCreateTableSql)) {
61 ~SqliteWraper() { Release(); }
63 bool SQL(std::string_view sql, std::string *value =
nullptr) {
64 AINFO <<
"Executing SQL: " << sql;
66 AERROR <<
"DB is not open properly.";
70 char *error =
nullptr;
71 if (sqlite3_exec(db_, sql.data(), Callback, value, &error) != SQLITE_OK) {
72 AERROR <<
"Failed to execute SQL: " << error;
79 sqlite3* GetDB()
const {
return db_; }
89 sqlite3 *db_ =
nullptr;
94bool KVDB::Put(std::string_view key, std::string_view value) {
97 absl::StrCat(
"INSERT OR REPLACE INTO key_value (key, value) VALUES ('",
98 key,
"', '", value,
"');"));
104 absl::StrCat(
"DELETE FROM key_value WHERE key='", key,
"';"));
107std::optional<std::string>
KVDB::Get(std::string_view key) {
110 const bool ret = sqlite.SQL(
111 absl::StrCat(
"SELECT value FROM key_value WHERE key='", key,
"';"),
113 if (ret && !value.empty()) {
120 std::string_view start) {
122 std::vector<std::pair<std::string, std::string>> results;
126 std::string sql = absl::StrCat(
127 "SELECT key, value FROM key_value WHERE key LIKE '", start,
"%';");
130 auto callback = [](
void *data,
int argc,
char **argv,
131 char **col_name) ->
int {
133 static_cast<std::vector<std::pair<std::string, std::string>
> *>(data);
134 if (argc == 2 && argv[0] && argv[1]) {
135 vec->emplace_back(argv[0], argv[1]);
140 char *error =
nullptr;
141 if (sqlite3_exec(sqlite.GetDB(), sql.c_str(), callback, &results, &error) !=
143 AERROR <<
"Failed to execute SQL: " << error;
static std::optional< std::string > Get(std::string_view key)
Get value of a key.
static bool Put(std::string_view key, std::string_view value)
Store {key, value} to DB.
static std::vector< std::pair< std::string, std::string > > GetWithStart(std::string_view start)
Get the tuple whose key starts with start.
static bool Delete(std::string_view key)
Delete a key.
DEFINE_string(kv_db_path, "data/kv_db.sqlite", "Path to Key-value DB file.")