query/test/backends/StatementTest.cpp

114 lines
3.1 KiB
C++

#include <catch2/catch_test_macros.hpp>
#include "matador/object/object_generator.hpp"
#include "matador/sql/connection.hpp"
#include "matador/query/criteria.hpp"
#include "matador/query/generator.hpp"
#include "matador/query/query.hpp"
#include "matador/object/object_ptr.hpp"
#include "QueryFixture.hpp"
#include "models/airplane.hpp"
#include "models/model_metas.hpp"
using namespace matador::sql;
using namespace matador::object;
using namespace matador::query;
using namespace matador::test;
using namespace matador::query::meta;
namespace matador::test::detail {
template<class Type, typename... Args>
[[maybe_unused]] object_ptr<Type> make_object_ptr(Args&&... args) {
return object_ptr(new Type(std::forward<Args>(args)...));
}
}
class StatementTestFixture : public QueryFixture {
public:
StatementTestFixture() {
REQUIRE(repo.attach<airplane>("airplanes"));
}
protected:
std::vector<object_ptr<airplane>> planes{
matador::test::detail::make_object_ptr<airplane>(1, "Airbus", "A380"),
matador::test::detail::make_object_ptr<airplane>(2, "Boeing", "707"),
matador::test::detail::make_object_ptr<airplane>(3, "Boeing", "747")
};
};
TEST_CASE_METHOD(StatementTestFixture, "Create prepared statement", "[statement]") {
using namespace matador::utils;
REQUIRE(repo.create(db));
SECTION("Insert with prepared statement and placeholder") {
auto stmt = query::insert()
.into(AIRPLANE, {AIRPLANE.id, AIRPLANE.brand, AIRPLANE.model})
.values(generator::placeholders<airplane>())
.prepare(db);
REQUIRE(stmt.is_ok());
for (const auto &plane: planes) {
auto res = stmt->bind(*plane).execute();
REQUIRE(res.is_ok());
REQUIRE(*res == 1);
stmt->reset();
}
auto result = query::select({AIRPLANE.id, AIRPLANE.brand, AIRPLANE.model})
.from(AIRPLANE)
.fetch_all<airplane>(db);
REQUIRE(result.is_ok());
size_t index{0};
for (const auto &i: *result) {
REQUIRE(i.id == planes[index]->id);
REQUIRE(i.brand == planes[index]->brand);
REQUIRE(i.model == planes[index++]->model);
}
}
SECTION("Select with prepared statement") {
for (const auto &plane: planes) {
auto res = query::insert()
.into(AIRPLANE, {AIRPLANE.id, AIRPLANE.brand, AIRPLANE.model})
.values(*plane)
.execute(db);
REQUIRE(res.is_ok());
REQUIRE(*res == 1);
}
auto stmt = query::select(generator::columns<airplane>(repo))
.from(AIRPLANE)
.where(AIRPLANE.brand == _)
.prepare(db);
REQUIRE(stmt.is_ok());
auto result = stmt->bind(0, "Airbus")
.fetch<airplane>();
REQUIRE(result.is_ok());
for (const auto &i: *result) {
REQUIRE(i.id == planes[0]->id);
REQUIRE(i.brand == planes[0]->brand);
REQUIRE(i.model == planes[0]->model);
}
stmt->reset();
result = stmt->bind(0, "Boeing")
.fetch<airplane>();
size_t index{1};
REQUIRE(result.is_ok());
for (const auto &i: *result) {
REQUIRE(i.id == planes[index]->id);
REQUIRE(i.brand == planes[index]->brand);
REQUIRE(i.model == planes[index++]->model);
}
}
}