Files
UpAndDown/src/DAO/MySQLUserTreatmentSchemesDAO.cpp
T

113 lines
2.9 KiB
C++

#include <mysqlx/xdevapi.h>
#include <unordered_map>
#include "MySQLUserTreatmentSchemesDAO.h"
namespace uad
{
MySQLUserTreatmentSchemesDAO::MySQLUserTreatmentSchemesDAO(mysqlx::Session& session)
: session_(session)
{
}
std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserUUID(
std::string_view user_uuid)
{
static const std::string query = R"(
SELECT
uts.uuid,
uts.treatment_name,
uts.instructions,
ts.medication_uuid
FROM up_and_down.users u
JOIN up_and_down.user_treatment_schemes uts
ON uts.user_uuid = u.uuid
LEFT JOIN up_and_down.treatment_schemes ts
ON ts.user_treatment_schemes_uuid = uts.uuid
WHERE u.uuid = ?
ORDER BY uts.uuid
)";
mysqlx::SqlResult result = session_
.sql(query)
.bind(user_uuid.data())
.execute();
std::unordered_map<std::string, user_treatment_scheme_dto> scheme_map;
for (const mysqlx::Row& row : result)
{
const std::string scheme_uuid = row[0].get<std::string>();
if (scheme_map.find(scheme_uuid) == scheme_map.end())
{
user_treatment_scheme_dto dto;
dto.uuid = scheme_uuid;
dto.treatment_name = row[1].isNull() ? "" : row[1].get<std::string>();
dto.instructions = row[2].isNull() ? "" : row[2].get<std::string>();
scheme_map.emplace(scheme_uuid, std::move(dto));
}
if (!row[3].isNull())
{
scheme_map[scheme_uuid]
.medication_uuids
.push_back(row[3].get<std::string>());
}
}
std::vector<user_treatment_scheme_dto> schemes;
schemes.reserve(scheme_map.size());
for (auto& [_, dto] : scheme_map)
{
schemes.push_back(std::move(dto));
}
return std::move(schemes);
}
void MySQLUserTreatmentSchemesDAO::CreateUserTreatmentScheme(
std::string_view user_uuid,
const user_treatment_scheme_dto& dto)
{
session_.startTransaction();
try {
session_.sql(R"(
INSERT INTO up_and_down.user_treatment_schemes (
uuid,
user_uuid,
treatment_name,
instructions
) VALUES (?, ?, ?, ?)
)")
.bind(
dto.uuid,
user_uuid.data(),
dto.treatment_name,
dto.instructions
)
.execute();
for (const auto& medication_uuid : dto.medication_uuids) {
session_.sql(R"(
INSERT INTO up_and_down.treatment_schemes (
user_treatment_schemes_uuid,
medication_uuid
) VALUES (?, ?)
)")
.bind(dto.uuid, medication_uuid)
.execute();
}
session_.commit();
}
catch (...) {
session_.rollback();
throw;
}
}
} // uad