7 DB::DB(const std::string &filename)
9 int ret = sqlite3_open(filename.c_str(), &db);
10 if (ret != SQLITE_OK) {
11 fprintf(stderr, "%s: %s\n", filename.c_str(), sqlite3_errmsg(db));
16 CREATE TABLE IF NOT EXISTS state (state BLOB);
17 )", nullptr, nullptr, nullptr); // Ignore errors.
19 sqlite3_exec(db, "PRAGMA journal_mode=WAL", nullptr, nullptr, nullptr); // Ignore errors.
20 sqlite3_exec(db, "PRAGMA synchronous=NORMAL", nullptr, nullptr, nullptr); // Ignore errors.
23 StateProto DB::get_state()
28 int ret = sqlite3_prepare(db, "SELECT state FROM state", -1, &stmt, 0);
29 if (ret != SQLITE_OK) {
30 fprintf(stderr, "SELECT prepare: %s\n", sqlite3_errmsg(db));
34 ret = sqlite3_step(stmt);
35 if (ret == SQLITE_ROW) {
36 bool ok = state.ParseFromArray(sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));
38 fprintf(stderr, "State in database is corrupted!\n");
41 } else if (ret != SQLITE_DONE) {
42 fprintf(stderr, "SELECT step: %s\n", sqlite3_errmsg(db));
46 ret = sqlite3_finalize(stmt);
47 if (ret != SQLITE_OK) {
48 fprintf(stderr, "SELECT finalize: %s\n", sqlite3_errmsg(db));
55 void DB::store_state(const StateProto &state)
58 state.SerializeToString(&serialized);
60 int ret = sqlite3_exec(db, "BEGIN", nullptr, nullptr, nullptr);
61 if (ret != SQLITE_OK) {
62 fprintf(stderr, "BEGIN: %s\n", sqlite3_errmsg(db));
66 ret = sqlite3_exec(db, "DELETE FROM state", nullptr, nullptr, nullptr);
67 if (ret != SQLITE_OK) {
68 fprintf(stderr, "DELETE: %s\n", sqlite3_errmsg(db));
73 ret = sqlite3_prepare(db, "INSERT INTO state VALUES (?)", -1, &stmt, 0);
74 if (ret != SQLITE_OK) {
75 fprintf(stderr, "INSERT prepare: %s\n", sqlite3_errmsg(db));
79 sqlite3_bind_blob(stmt, 1, serialized.data(), serialized.size(), SQLITE_STATIC);
81 ret = sqlite3_step(stmt);
82 if (ret == SQLITE_ROW) {
83 fprintf(stderr, "INSERT step: %s\n", sqlite3_errmsg(db));
87 ret = sqlite3_finalize(stmt);
88 if (ret != SQLITE_OK) {
89 fprintf(stderr, "INSERT finalize: %s\n", sqlite3_errmsg(db));
93 ret = sqlite3_exec(db, "COMMIT", nullptr, nullptr, nullptr);
94 if (ret != SQLITE_OK) {
95 fprintf(stderr, "COMMIT: %s\n", sqlite3_errmsg(db));