Everyone gets... ONE vote!

This commit is contained in:
2026-07-21 16:58:44 +10:00
parent 7e9271db72
commit 5d5982c2dc
3 changed files with 46 additions and 13 deletions

View File

@@ -2,6 +2,7 @@
#include <iomanip>
#include <iostream>
#include <fstream>
#include <ostream>
#include <sqlite3.h>
#include <stdexcept>
#include <sstream>
@@ -53,6 +54,11 @@ Database::Database(const std::string& path) {
userid INTEGER NOT NULL,
expiry INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS likes (
postid INTEGER NOT NULL,
userid INTEGER NOT NULL
);
)";
char* errmsg = nullptr;
@@ -183,13 +189,9 @@ void Database::addPost(const Post& post) {
}
void Database::addLike(uint64_t postId, uint64_t userId) {
// check if the post has already been liked
std::stringstream sql;
sql << R"(
UPDATE posts
SET likes = COALESCE(likes, 0) + 1
WHERE id =
)";
sql << postId << ";";
sql << "SELECT * FROM likes WHERE postid = " << postId << " AND userId = " << userId << ";";
std::string sqlstr = sql.str();
sqlite3_stmt* stmt;
@@ -198,11 +200,38 @@ void Database::addLike(uint64_t postId, uint64_t userId) {
}
if (sqlite3_step(stmt) != SQLITE_DONE) {
throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db)));
sqlite3_finalize(stmt);
throw std::runtime_error("you lowkey already liked the post");
}
sqlite3_finalize(stmt);
// add like to the post
sql.str("");
sql.clear();
sql << "UPDATE posts SET likes = COALESCE(likes, 0) + 1 WHERE id = " << postId << ";";
sqlstr = sql.str();
if (sqlite3_prepare_v2(db, sqlstr.c_str(), -1, &stmt, nullptr) != SQLITE_OK) {
throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db)));
}
if (sqlite3_step(stmt) != SQLITE_DONE) {
throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db)));
}
sqlite3_finalize(stmt);
// add like to the likes table
sql.str("");
sql.clear();
sql << "INSERT INTO likes (postid, userid) VALUES (" << postId << ", " << userId << ");";
sqlstr = sql.str();
if (sqlite3_prepare_v2(db, sqlstr.c_str(), -1, &stmt, nullptr) != SQLITE_OK) {
throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db)));
}
if (sqlite3_step(stmt) != SQLITE_DONE) {
throw std::runtime_error("sqlite3 error: " + std::string(sqlite3_errmsg(db)));
}
sqlite3_finalize(stmt);
}