#include "history.h" #include #include "defer.h" #include #include #include #include "defer.h" #define FELLOW_TABLE "fellow" #define MESSAGE_TABLE "message" #define CHECK_SQLITE_RET(ret, action, result)\ if (ret != SQLITE_OK)\ {\ cout<<"failed to"#action":"<getIp()); if (fellowId < 0) { string sql = "insert into " FELLOW_TABLE " values(null," +record.who->getIp() +","+record.who->getName() +","+record.who->getMac() +");"; ret = sqlite3_exec(mDb, sql.c_str(), nullptr, nullptr, nullptr); CHECK_SQLITE_RET2(ret, "insert fellow to db"); fellowId = findFellowId(record.who->getIp()); } //再增加记录 Parcel parcel; record.what->writeTo(parcel); string sql = "insert into " MESSAGE_TABLE "values(null," +to_string(fellowId) +","+ to_string(record.when.time_since_epoch().count()) +",?);"; sqlite3_stmt* stmt = nullptr; ret = sqlite3_prepare_v2(mDb, sql.c_str(), sql.length(), &stmt, nullptr); CHECK_SQLITE_RET2(ret, "prepare to insert message"); Defer finalizeStmt{ [stmt](){ sqlite3_finalize(stmt); } }; auto buf = parcel.raw(); ret = sqlite3_bind_blob(stmt, 1, buf.data(), buf.size(), nullptr); CHECK_SQLITE_RET2(ret, "bind content to blob"); ret = sqlite3_step(stmt); CHECK_SQLITE_RET2(ret, "insert message"); } vector History::query(const string& selection, const vector& args) { vector result; sqlite3_stmt* stmt; string sql = "select * from " MESSAGE_TABLE " where "+selection; auto ret = sqlite3_prepare_v2(mDb, sql.c_str(), sql.length(), &stmt, nullptr); CHECK_SQLITE_RET(ret, "prepare to query", result); Defer finalizeStmt{ [stmt](){ sqlite3_finalize(stmt); } }; int len = args.size(); for (auto i = 0; i < len; i++) { ret = sqlite3_bind_blob(stmt, i+1, args[i].c_str(), args[i].length(), nullptr); CHECK_SQLITE_RET(ret, "bind args", result); } while(true) { ret = sqlite3_step(stmt); if (ret == SQLITE_DONE) { return result; } else if (ret != SQLITE_ROW) { cerr<<"error occur while step query:"<(std::move(fellow)); record.when = time_point(milliseconds(when)); Parcel parcel; parcel.fillWith(contentData, contentLen); parcel.resetForRead(); record.what = ContentParcelFactory::createFromParcel(parcel); result.push_back(record); } } return result; } unique_ptr History::getFellow(int id) { } int History::findFellowId(const string &ip) { }