#include #include "MySQLUserDAO.h" #include using namespace std; using namespace string_literals; namespace uad { MySQLUserDAO::MySQLUserDAO(mysqlx::Session& session) : session_(session) { } string MySQLUserDAO::Create(const User& created_user) { boost::uuids::random_generator generator; boost::uuids::uuid uuid = generator(); std::string uuid_str = boost::uuids::to_string(uuid); string sql_script = "INSERT INTO `up_and_down`.`users` (`uuid`, `login`, `hashed_password`) VALUES (?, ?, ?);"s; session_.sql(sql_script) .bind(uuid_str, created_user.GetLogin(), created_user.GetHashedPassword()) .execute(); return uuid_str; } optional MySQLUserDAO::GetByUUID(string uuid) { mysqlx::SqlResult sql_result = session_. sql("SELECT * FROM `up_and_down`.`users` WHERE (uuid = '" + uuid + "') LIMIT 1;"s).execute(); return GetSingleUserBySQLResult(std::move(sql_result)); } optional MySQLUserDAO::GetByLogin(string login) { mysqlx::SqlResult sql_result = session_. sql("SELECT * FROM `up_and_down`.`users` WHERE (login = '" + login + "') LIMIT 1;"s).execute(); return GetSingleUserBySQLResult(std::move(sql_result)); } pair> MySQLUserDAO::GetAll(size_t limit, size_t offset) { mysqlx::SqlResult sql_result = session_ .sql("SELECT * FROM `up_and_down`.`users` LIMIT ? OFFSET ?;"s) .bind(limit, offset) .execute(); list rows = sql_result.fetchAll(); pair> ret; if (!rows.size()) { ret.first = true; ret.second = vector{}; return ret; } ret.first = rows.size() != limit + 1; ret.second = vector{}; ret.second.reserve(limit); for (const auto& row : rows) { if (!limit) { break; } User user; string user_uuid = row[0].get(); string user_login = row[1].get(); user.SetLogin(user_login); user.SetUUID(user_uuid); ret.second.push_back(std::move(user)); --limit; } return ret; } bool MySQLUserDAO::Update(const User& u) { auto schema = session_.getSchema("up_and_down"); auto table = schema.getTable("users"); mysqlx::Result res = table.update() .set("login", u.GetLogin()) .set("hashed_password", u.GetHashedPassword()) .where("uuid = :uuid") .bind("uuid", u.GetUUID()) .execute(); return !!res.getAffectedItemsCount(); } bool MySQLUserDAO::Delete(string id) { return false; } std::optional MySQLUserDAO::GetSingleUserBySQLResult(mysqlx::SqlResult&& sql_result) { list rows = sql_result.fetchAll(); if (!rows.size()) { return nullopt; } auto row_data = *rows.begin(); string user_uuid = row_data[0].get(); string user_login = row_data[1].get(); string user_hashed_password = row_data[2].get(); User user; user.SetUUID(user_uuid); user.SetLogin(user_login); user.SetHashedPassword(user_hashed_password); return optional(std::move(user)); } } // uad