Older/Server/Database.cpp

57 lines
1.9 KiB
C++
Raw Normal View History

2023-12-30 00:15:03 +08:00
#include "Database.h"
2023-12-30 01:19:36 +08:00
#include "BoostLog.h"
#include <sqlite3.h>
#include <sstream>
2023-12-30 00:15:03 +08:00
bool Database::open(const std::string &path) {
2023-12-30 01:19:36 +08:00
bool ret = true;
int result = sqlite3_open(path.c_str(), &m_sqlite3);
if (result != SQLITE_OK) {
ret = false;
LOG(error) << "open database failed.";
}
initialize();
return ret;
2023-12-30 00:15:03 +08:00
}
2023-12-30 01:19:36 +08:00
void Database::addTask(uint64_t createTime, const std::string &content, bool finished) {
std::ostringstream oss;
oss << "INSERT INTO tasks (create_time,content,finished) VALUES (" << createTime << ",\"" << content << "\","
<< finished << ");";
auto sql = oss.str();
int result = sqlite3_exec(m_sqlite3, sql.c_str(), NULL, NULL, NULL);
if (result != SQLITE_OK) {
LOG(error) << "add task failed: " << sqlite3_errmsg(m_sqlite3) << ", sql: " << sql;
return;
}
}
void Database::setTaskFinished(int id, bool finished, uint64_t finishedTime) {
std::ostringstream oss;
oss << "UPDATE tasks SET finished = " << finished << ", finished_time = " << finishedTime << " WHERE id = " << id;
auto sql = oss.str();
int result = sqlite3_exec(m_sqlite3, sql.c_str(), NULL, NULL, NULL);
if (result != SQLITE_OK) {
LOG(error) << "add task failed: " << sqlite3_errmsg(m_sqlite3) << ", sql: " << sql;
return;
}
}
void Database::initialize() {
const char *sql =
"CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY AUTOINCREMENT, create_time INTEGER NOT NULL, "
"parent_id INTEGER, content VARCHAR(512) NOT NULL, finished BOLL, finished_time INTEGER);";
int result = sqlite3_exec(m_sqlite3, sql, NULL, NULL, NULL);
if (result != SQLITE_OK) {
LOG(error) << "Failed to create table: " << sqlite3_errmsg(m_sqlite3);
return;
}
}
Database::~Database() {
if (m_sqlite3 != nullptr) {
sqlite3_close(m_sqlite3);
m_sqlite3 = nullptr;
}
2023-12-30 00:15:03 +08:00
}