Apollo 10.0
自动驾驶开放平台
kv_db.cc
浏览该文件的文档.
1/******************************************************************************
2 * Copyright 2017 The Apollo Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *****************************************************************************/
17
18#include <sqlite3.h>
19
20#include "gflags/gflags.h"
21
22#include "absl/strings/str_cat.h"
23#include "cyber/common/log.h"
25
26DEFINE_string(kv_db_path, "data/kv_db.sqlite",
27 "Path to Key-value DB file.");
28
29namespace apollo {
30namespace common {
31namespace {
32
33// Self-maintained sqlite instance.
34class SqliteWraper {
35 public:
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] : "";
40 }
41 return 0;
42 }
43
44 SqliteWraper() {
45 // Open DB.
46 if (sqlite3_open(FLAGS_kv_db_path.c_str(), &db_) != 0) {
47 AERROR << "Can't open Key-Value database: " << sqlite3_errmsg(db_);
48 Release();
49 return;
50 }
51
52 // Create table if it doesn't exist.
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)) {
57 Release();
58 }
59 }
60
61 ~SqliteWraper() { Release(); }
62
63 bool SQL(std::string_view sql, std::string *value = nullptr) {
64 AINFO << "Executing SQL: " << sql;
65 if (db_ == nullptr) {
66 AERROR << "DB is not open properly.";
67 return false;
68 }
69
70 char *error = nullptr;
71 if (sqlite3_exec(db_, sql.data(), Callback, value, &error) != SQLITE_OK) {
72 AERROR << "Failed to execute SQL: " << error;
73 sqlite3_free(error);
74 return false;
75 }
76 return true;
77 }
78
79 sqlite3* GetDB() const { return db_; }
80
81 private:
82 void Release() {
83 if (db_ != nullptr) {
84 sqlite3_close(db_);
85 db_ = nullptr;
86 }
87 }
88
89 sqlite3 *db_ = nullptr;
90};
91
92} // namespace
93
94bool KVDB::Put(std::string_view key, std::string_view value) {
95 SqliteWraper sqlite;
96 return sqlite.SQL(
97 absl::StrCat("INSERT OR REPLACE INTO key_value (key, value) VALUES ('",
98 key, "', '", value, "');"));
99}
100
101bool KVDB::Delete(std::string_view key) {
102 SqliteWraper sqlite;
103 return sqlite.SQL(
104 absl::StrCat("DELETE FROM key_value WHERE key='", key, "';"));
105}
106
107std::optional<std::string> KVDB::Get(std::string_view key) {
108 SqliteWraper sqlite;
109 std::string value;
110 const bool ret = sqlite.SQL(
111 absl::StrCat("SELECT value FROM key_value WHERE key='", key, "';"),
112 &value);
113 if (ret && !value.empty()) {
114 return value;
115 }
116 return {};
117}
118
119std::vector<std::pair<std::string, std::string>> KVDB::GetWithStart(
120 std::string_view start) {
121 SqliteWraper sqlite;
122 std::vector<std::pair<std::string, std::string>> results;
123
124 // Use the SQL LIKE operator to match any key that starts with the 'start'
125 // parameter.
126 std::string sql = absl::StrCat(
127 "SELECT key, value FROM key_value WHERE key LIKE '", start, "%';");
128
129 // Modify the callback function to handle multiple rows.
130 auto callback = [](void *data, int argc, char **argv,
131 char **col_name) -> int {
132 auto *vec =
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]);
136 }
137 return 0;
138 };
139
140 char *error = nullptr;
141 if (sqlite3_exec(sqlite.GetDB(), sql.c_str(), callback, &results, &error) !=
142 SQLITE_OK) {
143 AERROR << "Failed to execute SQL: " << error;
144 sqlite3_free(error);
145 }
146
147 return results;
148}
149
150
151} // namespace common
152} // namespace apollo
static std::optional< std::string > Get(std::string_view key)
Get value of a key.
Definition kv_db.cc:107
static bool Put(std::string_view key, std::string_view value)
Store {key, value} to DB.
Definition kv_db.cc:94
static std::vector< std::pair< std::string, std::string > > GetWithStart(std::string_view start)
Get the tuple whose key starts with start.
Definition kv_db.cc:119
static bool Delete(std::string_view key)
Delete a key.
Definition kv_db.cc:101
DEFINE_string(kv_db_path, "data/kv_db.sqlite", "Path to Key-value DB file.")
#define AERROR
Definition log.h:44
#define AINFO
Definition log.h:42
Some util functions.
class register implement
Definition arena_queue.h:37