57 lines
1.9 KiB
C++
57 lines
1.9 KiB
C++
#include "Database.h"
|
|
#include "BoostLog.h"
|
|
#include <sqlite3.h>
|
|
#include <sstream>
|
|
|
|
bool Database::open(const std::string &path) {
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|