Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

database version 1.0.0 #4

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
174 changes: 174 additions & 0 deletions Header files/database.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <strstream>

#include <libpq-fe.h>


class BasicUser {
public:
~BasicUser() = default;

// Подключиться к бд
virtual bool connect(const std::string &dbName, const std::string &user,
const std::string &password, const std::string &hostAddr,
const std::string &port) = 0;

// ------------------ Table User -----------------------
// Добавить пользователя
virtual bool insertUser(const std::string &user_name, const std::string &mail,
const std::string &password, const std::string &token) = 0;

// Изменить данные пользователя
virtual bool alterUser(const std::string &user_name, const std::string &name,
const std::string &mail, const std::string &password,
const std::string &token) = 0;

// Удалить пользователя
virtual bool deleteUser(const std::string &user_name) = 0;

// Выбрать данные пользователя
virtual bool selectUser(const std::string &user_name, std::vector<std::string> &output) = 0;
};


class BasicQuestion {
public:
~BasicQuestion() = default;

// Подключиться к бд
virtual bool connect(const std::string &dbName, const std::string &user,
const std::string &password, const std::string &hostAddr,
const std::string &port) = 0;

// ------------------ Table Question -----------------------
// Добавить вопрос и ответ добавить возвращение q_id
virtual std::string insertQuestionAndAnswer(const std::string &user_name,
const std::string &question,
const std::string &answer) = 0;

// Удалить историю пользователя
virtual bool deleteUserHistory(const std::string &user_name) = 0;

// Удалить вопрос и ответы к нему
virtual bool deleteQuestion(const std::string &question_id) = 0;

// Получить историю пользователя
virtual bool getUserHistory(const std::string &user_name, std::string &output) = 0;
};


class BasicAnswer {
public:
~BasicAnswer() = default;

// Подключиться к бд
virtual bool connect(const std::string &dbName, const std::string &user,
const std::string &password, const std::string &hostAddr,
const std::string &port) = 0;

// ------------------ Table Answer -----------------------
// Добавить ответ
virtual bool insertAnswer(const std::string &question_id, const std::string &text) = 0;

// Выбрать 3 ответа на вопрос
virtual bool selectQuestionAnswers(const std::string &question_id,
std::vector<std::string> &output) = 0;

};


class UserDB : public BasicUser {
public:
explicit UserDB(): connection_({nullptr,&PQfinish}) {}
~UserDB() = default;

// Подключиться к бд
bool connect(const std::string &dbName, const std::string &user,
const std::string &password, const std::string &hostAddr,
const std::string &port) override;


// ------------------ Table User -----------------------
// Добавить пользователя
bool insertUser(const std::string& user_name, const std::string& mail,
const std::string& password, const std::string& token) override;

// Изменить данные пользователя
bool alterUser(const std::string &user_name, const std::string &name, const std::string &mail,
const std::string &password, const std::string &token) override;

// Удалить пользователя
bool deleteUser(const std::string &user_name) override;

// Выбрать данные пользователя
bool selectUser(const std::string &user_name, std::vector<std::string> &output) override;

private:
std::unique_ptr<PGconn, decltype(&PQfinish)> connection_;

bool exists(const std::string &user_name);
};


class QuestionDB : public BasicQuestion {
public:
explicit QuestionDB(): connection_({nullptr,&PQfinish}) {}
~QuestionDB() = default;

// Подключиться к бд
bool connect(const std::string &dbName, const std::string &user,
const std::string &password, const std::string &hostAddr,
const std::string &port) override;

// ------------------ Table Question -----------------------
// Добавить вопрос и ответ
std::string insertQuestionAndAnswer(const std::string &user_name, const std::string &question,
const std::string &answer) override;

// Удалить историю пользователя
bool deleteUserHistory(const std::string &user_name) override;

// Удалить выбранные вопросы и ответы
bool deleteQuestion(const std::string &question_id) override;

// Получить последний вопрос пользователя
bool getUserHistory(const std::string &user_name, std::string &output) override;

private:
std::unique_ptr<PGconn, decltype(&PQfinish)> connection_;
};


class AnswerDB : public BasicAnswer {
public:
explicit AnswerDB(): connection_({nullptr,&PQfinish}) {}
~AnswerDB() = default;

// Подключиться к бд
bool connect(const std::string &dbName, const std::string &user,
const std::string &password, const std::string &hostAddr,
const std::string &port) override;

// ------------------ Table Answer -----------------------
// Добавить ответ
bool insertAnswer(const std::string &question_id, const std::string &text) override;

// Выбрать 3 последних ответа на вопрос
bool selectQuestionAnswers(const std::string &question_id,
std::vector<std::string> &output) override;

private:
std::unique_ptr<PGconn, decltype(&PQfinish)> connection_;
};


/*
* Проверяю методы на тестовой бд
*/

bool reset_sequence(PGconn* conn, const std::string& table_name);
void set_default();
101 changes: 101 additions & 0 deletions Source files/answerMethods.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
#include "../Header files/database.h"


bool AnswerDB::connect(const std::string &dbName, const std::string &user,
const std::string &password, const std::string &hostAddr,
const std::string &port) {
std::string connectionString = "dbname=" + dbName + " user=" + user + " password=" +
password + " hostaddr=" + hostAddr + " port=" + port;
const char* connection = connectionString.c_str();
connection_.reset(PQconnectdb(connection));
if (PQstatus(connection_.get()) != CONNECTION_OK) {
std::cerr << "Connection to database failed: " << PQerrorMessage(connection_.get()) <<
std::endl;
return false;
}
return true;
}


// ------------------ Table Answer -----------------------

bool AnswerDB::insertAnswer(const std::string &question_id, const std::string &text) {
const char* sql = "INSERT INTO public.answer (question_id, answer_text) VALUES ($1, $2)";
const char* sqlParams[2];

sqlParams[0] = question_id.c_str();
sqlParams[1] = text.c_str();

std::unique_ptr<PGresult, decltype(&PQclear)> result(
PQexec(connection_.get(), nullptr),
&PQclear);
try {
result.reset(PQexecParams(connection_.get(),
sql,
2,
nullptr,
sqlParams,
nullptr,
nullptr,
0));

if (PQresultStatus(result.get()) != PGRES_COMMAND_OK) {
throw std::runtime_error(PQresultErrorMessage(result.get()));
}
} catch (const std::exception& e) {
std::cerr << "Failed to insert data into table 'public.answer': " << e.what() << std::endl;
return false;
}

return true;
}


bool AnswerDB::selectQuestionAnswers(const std::string &question_id,
std::vector<std::string> &output) {
const char* sql = "SELECT answer_text FROM public.answer "
"WHERE question_id = $1 "
"ORDER BY answer_time DESC "
"LIMIT 3;";
const char* sqlParams[1] = { question_id.c_str() };
int numParams = 1;

std::unique_ptr<PGresult, decltype(&PQclear)> result(
PQexecParams(connection_.get(),
sql,
numParams,
nullptr,
sqlParams,
nullptr,
nullptr,
0),
&PQclear);

if (PQresultStatus(result.get()) != PGRES_TUPLES_OK) {
std::cerr << "Query failed: " << PQresultErrorMessage(result.get()) << std::endl;
return false;
} else {
if (PQntuples(result.get()) == 0) {
std::cerr << "No question or answers" << std::endl;
return false;
} else {
output.clear();
int nRows = PQntuples(result.get());
int nCols = PQnfields(result.get());

std::string outString;
for (int i = 0; i < nRows; ++i) {
for (int j = 0; j < nCols; ++j) {
outString += PQgetvalue(result.get(), i, j);
if (j != nCols - 1)
outString += " ";
}
output.emplace_back(outString);
outString.clear();
}
}
}

return true;
}

61 changes: 61 additions & 0 deletions Source files/functions.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#include "../Header files/database.h"


bool reset_sequence(PGconn* conn, const std::string& table_name) {
std::string query = "SELECT setval(pg_get_serial_sequence('" + table_name + "', '" + table_name + "_id'), 1, false);";
PGresult* res = PQexec(conn, query.c_str());
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
std::cerr << "Failed to reset sequence: " << PQresultErrorMessage(res) << std::endl;
PQclear(res);
return false;
}
PQclear(res);
return true;
}



void set_default() {
std::shared_ptr<BasicUser> userDb(new UserDB());
userDb->connect("your_voice", "user", "qwerty", "127.0.0.1", "5432");

userDb->deleteUser("");
PGconn* conn = PQconnectdb("dbname=your_voice user=user password=qwerty host=127.0.0.1 port=5432");

if (!reset_sequence(conn, "user")) {
std::cerr << "Failed to reset sequence!" << std::endl;
}
if (!reset_sequence(conn, "question")) {
std::cerr << "Failed to reset sequence!" << std::endl;
}
if (!reset_sequence(conn, "answer")) {
std::cerr << "Failed to reset sequence!" << std::endl;
}
userDb->insertUser("user1", "qwerty@mail.ru", "qwerty",
"afasdhfojhonc3y498r2403c7rn02382347c502374c5");
userDb->insertUser("user2", "asdf@mail.ru", "qwerty",
"3427c5624c29c4529b6");
userDb->insertUser("user11", "user11@mail.ru", "qwerty",
"3427c5624c29c4529b6");

std::shared_ptr<BasicQuestion> questionDb(new QuestionDB());
questionDb->connect("your_voice", "user", "qwerty", "127.0.0.1", "5432");

questionDb->insertQuestionAndAnswer("user1", "question1 user1", "answer1 question1 user1");
questionDb->insertQuestionAndAnswer("user1", "question2 user1", "answer1 question2 user1");

questionDb->insertQuestionAndAnswer("user2", "question1 user2", "answer1 question1 user2");
questionDb->insertQuestionAndAnswer("user2", "question2 user2", "answer1 question2 user2");


std::shared_ptr<BasicAnswer> answerDb(new AnswerDB());
answerDb->connect("your_voice", "user", "qwerty", "127.0.0.1", "5432");

answerDb->insertAnswer("1", "answer2 question1 user1");
answerDb->insertAnswer("2", "answer2 question2 user1");
answerDb->insertAnswer("2", "answer3 question2 user1");

answerDb->insertAnswer("3", "answer2 question1 user2");
answerDb->insertAnswer("4", "answer2 question2 user2");

}
Loading