Save messages to database

This commit is contained in:
2026-07-23 14:31:13 +10:00
parent d61946d2ec
commit 1159bdebde
4 changed files with 186 additions and 15 deletions

View File

@@ -1,4 +1,5 @@
#include "db.h"
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <fstream>
@@ -60,6 +61,14 @@ Database::Database(const std::string& path) {
postid INTEGER NOT NULL,
userid INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY,
senderid INTEGER NOT NULL,
recieverid INTEGER NOT NULL,
timestamp INTEGER NOT NULL,
text TEXT NOT NULL
);
)";
char* errmsg = nullptr;
@@ -448,3 +457,69 @@ void Database::invalidateUserSessions(const User& user) {
sqlite3_finalize(stmt);
}
std::vector<Message> Database::getMessages(uint64_t userA, uint64_t userB, uint64_t amount) {
const char* sql = R"(
SELECT * FROM messages
WHERE (senderid = ? AND recieverid = ?) OR (senderid = ? AND recieverid = ?)
ORDER BY timestamp DESC
LIMIT ?;
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db)));
}
sqlite3_bind_int64(stmt, 1, userA);
sqlite3_bind_int64(stmt, 2, userB);
sqlite3_bind_int64(stmt, 3, userB);
sqlite3_bind_int64(stmt, 4, userA);
sqlite3_bind_int64(stmt, 5, amount);
std::vector<Message> messages = {};
while (sqlite3_step(stmt) == SQLITE_ROW) {
uint64_t id = sqlite3_column_int64(stmt, 0);
uint64_t senderId = sqlite3_column_int64(stmt, 1);
uint64_t recieverId = sqlite3_column_int64(stmt, 2);
std::time_t timestamp = sqlite3_column_int64(stmt, 3);
const char* textptr = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 4));
std::string text;
if (textptr == NULL) {
text = "";
} else {
text = std::string(textptr);
}
messages.emplace_back(id, senderId, recieverId, text, timestamp);
}
sqlite3_finalize(stmt);
return messages;
}
void Database::addMessage(Message& message) {
const char* sql = R"(
INSERT INTO messages (senderid, recieverid, timestamp, text)
VALUES (?, ?, ?, ?);
)";
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr) != SQLITE_OK) {
throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db)));
}
sqlite3_bind_int64(stmt, 1, message.sender);
sqlite3_bind_int64(stmt, 2, message.reciever);
sqlite3_bind_int64(stmt, 3, message.timestamp);
sqlite3_bind_text(stmt, 4, message.content.c_str(), -1, SQLITE_STATIC);
if (sqlite3_step(stmt) != SQLITE_DONE) {
throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db)));
}
sqlite3_finalize(stmt);
}