Compare commits
66
Commits
main
...
2271702e6c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2271702e6c | ||
|
|
dafa81aef0 | ||
|
|
9f718b7e36 | ||
|
|
4dcbf009da | ||
|
|
e72733d37e | ||
|
|
c28ba7da5e | ||
|
|
62e3d18144 | ||
|
|
7d47ef0b82 | ||
|
|
c9cf4b8997 | ||
|
|
df0be4f37c | ||
|
|
4e4a294d19 | ||
|
|
6ec5011e21 | ||
|
|
261f9fd6cb | ||
|
|
35f078bbc4 | ||
|
|
d0b3ce4231 | ||
|
|
0eb1ae9fe8 | ||
|
|
dfb0d7c56a | ||
|
|
8ab8274d93 | ||
|
|
784f6e768d | ||
|
|
901d9c071a | ||
|
|
5109659882 | ||
|
|
9a95725959 | ||
|
|
6cb19f6ec8 | ||
|
|
66d5bc6c86 | ||
|
|
ec96c15905 | ||
|
|
6e64ba99de | ||
|
|
d070a5a0ac | ||
|
|
336b2a7342 | ||
|
|
2efb106fc3 | ||
|
|
5d41a592bb | ||
|
|
42acaf24ce | ||
|
|
55f9f8cf67 | ||
|
|
1d83abcb1b | ||
|
|
a631a5a36c | ||
|
|
e3e0eb932c | ||
|
|
504e111491 | ||
|
|
a4d6f68ee2 | ||
|
|
6cb501ded9 | ||
|
|
73c13026d8 | ||
|
|
936ba06458 | ||
|
|
81cd8eecb2 | ||
|
|
2e5257a5fa | ||
|
|
9e60b5e485 | ||
|
|
23646ab4ee | ||
|
|
8b41fbc531 | ||
|
|
a593539ae4 | ||
|
|
a1bdb32e04 | ||
|
|
005b42d131 | ||
|
|
8ef78bb658 | ||
|
|
27d9bac316 | ||
|
|
c591302063 | ||
|
|
b8df32bdf9 | ||
|
|
84af642f14 | ||
|
|
3d90d9d6ee | ||
|
|
0b70f5d4ee | ||
|
|
c76aa56440 | ||
|
|
bc3ffbda10 | ||
|
|
45a7199ccf | ||
|
|
d3674532c0 | ||
|
|
61a80d93f7 | ||
|
|
98af2bc6c4 | ||
|
|
405f158a88 | ||
|
|
f01e9ff87f | ||
|
|
6a5974337d | ||
|
|
89fb7e8a8d | ||
|
|
ded3daceb3 |
+47
-38
@@ -1,50 +1,59 @@
|
||||
cmake_minimum_required(VERSION 3.26)
|
||||
cmake_minimum_required(VERSION 3.30)
|
||||
|
||||
project(
|
||||
query
|
||||
VERSION 1.0.0
|
||||
DESCRIPTION "SQL query fluent prototype for PostgreSQL, SQLite, MySQL and MSSQL"
|
||||
LANGUAGES CXX
|
||||
matador
|
||||
VERSION 0.9.8
|
||||
LANGUAGES C CXX
|
||||
)
|
||||
|
||||
include(cmake/CPM.cmake)
|
||||
include(CTest)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
set(GCC_CLANG_COMMON_FLAGS "-Wall -Wconversion -Wextra -pedantic -ftemplate-backtrace-limit=0")
|
||||
SET(GCC_CLANG_COMMON_FLAGS "-Wall -Wextra -pedantic -ftemplate-backtrace-limit=0")
|
||||
SET(GCC_CLANG_COMMON_FLAGS_DEBUG "-O0 -g -DDEBUG")
|
||||
SET(GCC_CLANG_COMMON_FLAGS_RELEASE "-O1 -DNDEBUG")
|
||||
SET(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
if (WIN32)
|
||||
add_compile_options(/Zc:preprocessor)
|
||||
endif()
|
||||
message(STATUS "C++ Compiler ID: ${CMAKE_CXX_COMPILER_ID}")
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake)
|
||||
|
||||
find_package(ODBC REQUIRED)
|
||||
find_package(SQLite3 REQUIRED)
|
||||
find_package(PostgreSQL REQUIRED)
|
||||
find_package(MySQL REQUIRED)
|
||||
|
||||
message(STATUS "Found ODBC config ${ODBC_CONFIG}")
|
||||
message(STATUS "Adding ODBC include directory: ${ODBC_INCLUDE_DIRS}")
|
||||
message(STATUS "Adding ODBC libs: ${ODBC_LIBRARIES}")
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||
message(STATUS "GCC detected - Adding compiler flags")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_CLANG_COMMON_FLAGS}")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${GCC_CLANG_COMMON_FLAGS_DEBUG}")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${GCC_CLANG_COMMON_FLAGS_RELEASE}")
|
||||
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
|
||||
message(STATUS "MSVC detected - Adding compiler flags")
|
||||
# set(CMAKE_CXX_FLAGS "/W3 /EHsc /bigobj")
|
||||
# set(CMAKE_CXX_FLAGS_DEBUG "/MDd /Od /Zi /D_DEBUG /DDEBUG")
|
||||
# set(CMAKE_CXX_FLAGS_RELEASE "/O1 /DNDEBUG")
|
||||
add_compile_options(/Zc:preprocessor)
|
||||
endif ()
|
||||
#if(ENABLE_COVERAGE)
|
||||
# # set compiler flags
|
||||
# set(CMAKE_CXX_FLAGS "-O0 -coverage")
|
||||
#
|
||||
# # find required tools
|
||||
# find_program(LCOV lcov REQUIRED)
|
||||
# find_program(GENHTML genhtml REQUIRED)
|
||||
#
|
||||
# # add coverage target
|
||||
# add_custom_target(coverage
|
||||
# # gather data
|
||||
# COMMAND ${LCOV} --directory . --exclude catch2 --exclude /usr/include --exclude test --capture --base-directory ${CMAKE_SOURCE_DIR} --output-file coverage.info
|
||||
# # generate report
|
||||
# COMMAND ${GENHTML} --demangle-cpp -o coverage coverage.info
|
||||
# WORKING_DIRECTORY ${CMAKE_BINARY_DIR})
|
||||
#endif()
|
||||
|
||||
message(STATUS "Found SQLite3 ${SQLite3_VERSION}")
|
||||
message(STATUS "Adding SQLite3 include directory: ${SQLite3_INCLUDE_DIRS}")
|
||||
message(STATUS "Adding SQLite3 libs: ${SQLite3_LIBRARIES}")
|
||||
|
||||
message(STATUS "Adding MySQL include directory: ${MYSQL_INCLUDE_DIR}")
|
||||
message(STATUS "Adding MySQL libs: ${MYSQL_LIBRARY}")
|
||||
|
||||
message(STATUS "Adding PostgreSQL include directory: ${PostgreSQL_INCLUDE_DIR}")
|
||||
message(STATUS "Adding PostgreSQL libs: ${PostgreSQL_LIBRARY}")
|
||||
|
||||
message(STATUS "Common flags ${CMAKE_CXX_FLAGS}")
|
||||
message(STATUS "Debug flags ${CMAKE_CXX_FLAGS_DEBUG}")
|
||||
message(STATUS "Relase flags ${CMAKE_CXX_FLAGS_RELEASE}")
|
||||
|
||||
message(STATUS "Linker flags ${CMAKE_EXE_LINKER_FLAGS}")
|
||||
|
||||
enable_testing()
|
||||
|
||||
add_subdirectory(src)
|
||||
add_subdirectory(test)
|
||||
add_subdirectory(backends)
|
||||
add_subdirectory(source)
|
||||
add_subdirectory(demo)
|
||||
add_subdirectory(backends)
|
||||
add_subdirectory(test)
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# Todo
|
||||
|
||||
- Add is_valid() method to connection & connection_impl
|
||||
- Read in entity fields
|
||||
- Add special handling for update in backends
|
||||
- Add ODBC/SQL Server backend
|
||||
|
||||
|
||||
Fetch eager strategies
|
||||
======================
|
||||
|
||||
ONE TO ONE/MANY
|
||||
*person* *address*
|
||||
- has one address - belongs to person
|
||||
|
||||
=> join "address" on "person.id" == "address.person_id"
|
||||
|
||||
*address* *person*
|
||||
- belongs to person - has one address
|
||||
|
||||
=> join "person" on "address.person_id" == "person.id"
|
||||
|
||||
*book* *author*
|
||||
- belongs to author - has many books
|
||||
|
||||
- => join "author" on "book.author_id" == "author.id"
|
||||
|
||||
HAS MANY TO ONE (WITHOUT RELATION TABLE)
|
||||
|
||||
*author* *book*
|
||||
- has many books - belongs to author
|
||||
|
||||
- => join "book" on "author.id" == "book.author_id"
|
||||
|
||||
if "has many" type has primary key & field "author_id"
|
||||
if table name belongs to entity template type?
|
||||
|
||||
HAS MANY TO MANY (WITHOUT RELATION TABLE)
|
||||
|
||||
*student* *student_course* *course*
|
||||
- has many courses - belongs to student
|
||||
- belongs to course - has many students
|
||||
|
||||
=> join "student_course" on "student.id" == "student_course.student_id"
|
||||
join "student_course" on "course.id" == "student_course.course_id"
|
||||
|
||||
if has many type hasn't primary key (is relation table)
|
||||
@@ -1,3 +1,4 @@
|
||||
add_subdirectory(sqlite)
|
||||
#add_subdirectory(sqlite)
|
||||
add_subdirectory(postgres)
|
||||
add_subdirectory(mysql)
|
||||
#add_subdirectory(mysql)
|
||||
#add_subdirectory(odbc)
|
||||
@@ -1,37 +0,0 @@
|
||||
set(HEADER
|
||||
include/mysql_connection.hpp
|
||||
include/mysql_error.hpp
|
||||
include/mysql_result_reader.hpp
|
||||
include/mysql_dialect.hpp
|
||||
include/mysql_statement.hpp
|
||||
include/mysql_parameter_binder.hpp
|
||||
include/mysql_prepared_result_reader.hpp
|
||||
)
|
||||
|
||||
set(SOURCES
|
||||
src/mysql_connection.cpp
|
||||
src/mysql_error.cpp
|
||||
src/mysql_result_reader.cpp
|
||||
src/mysql_dialect.cpp
|
||||
src/mysql_statement.cpp
|
||||
src/mysql_parameter_binder.cpp
|
||||
src/mysql_prepared_result_reader.cpp
|
||||
)
|
||||
|
||||
set(LIBRARY_TARGET matador-mysql)
|
||||
|
||||
add_subdirectory(test)
|
||||
|
||||
add_library(${LIBRARY_TARGET} MODULE ${SOURCES} ${HEADER})
|
||||
|
||||
set_target_properties(${LIBRARY_TARGET}
|
||||
PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/backends"
|
||||
)
|
||||
|
||||
target_include_directories(${LIBRARY_TARGET} PRIVATE
|
||||
${PROJECT_SOURCE_DIR}/include
|
||||
${PROJECT_SOURCE_DIR}/backends/mysql/include
|
||||
${MYSQL_INCLUDE_DIR})
|
||||
|
||||
target_link_libraries(${LIBRARY_TARGET} matador ${MYSQL_LIBRARY})
|
||||
@@ -1,61 +0,0 @@
|
||||
#ifndef QUERY_POSTGRES_CONNECTION_HPP
|
||||
#define QUERY_POSTGRES_CONNECTION_HPP
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#ifdef matador_mysql_EXPORTS
|
||||
#define MATADOR_MYSQL_API __declspec(dllexport)
|
||||
#else
|
||||
#define MATADOR_MYSQL_API __declspec(dllimport)
|
||||
#endif
|
||||
#pragma warning(disable: 4355)
|
||||
#else
|
||||
#define MATADOR_MYSQL_API
|
||||
#endif
|
||||
|
||||
#include "matador/sql/connection_impl.hpp"
|
||||
|
||||
#include <unordered_map>
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <mysql.h>
|
||||
#else
|
||||
#include <mysql/mysql.h>
|
||||
#endif
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
class mysql_connection : public matador::sql::connection_impl
|
||||
{
|
||||
public:
|
||||
explicit mysql_connection(const sql::connection_info &info);
|
||||
void open() override;
|
||||
void close() override;
|
||||
bool is_open() override;
|
||||
|
||||
std::unique_ptr<sql::query_result_impl> fetch(const std::string &stmt) override;
|
||||
std::unique_ptr<sql::statement_impl> prepare(sql::query_context context) override;
|
||||
|
||||
size_t execute(const std::string &stmt) override;
|
||||
|
||||
std::vector<sql::column_definition> describe(const std::string& table) override;
|
||||
|
||||
bool exists(const std::string &schema_name, const std::string &table_name) override;
|
||||
|
||||
private:
|
||||
mutable std::unique_ptr<MYSQL> mysql_;
|
||||
|
||||
using string_to_int_map = std::unordered_map<std::string, unsigned long>;
|
||||
|
||||
static string_to_int_map statement_name_map_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
extern "C"
|
||||
{
|
||||
MATADOR_MYSQL_API matador::sql::connection_impl* create_database(const matador::sql::connection_info &info);
|
||||
|
||||
MATADOR_MYSQL_API void destroy_database(matador::sql::connection_impl *db);
|
||||
}
|
||||
|
||||
#endif //QUERY_POSTGRES_CONNECTION_HPP
|
||||
@@ -1,19 +0,0 @@
|
||||
#ifndef QUERY_POSTGRES_DIALECT_HPP
|
||||
#define QUERY_POSTGRES_DIALECT_HPP
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#ifdef matador_mysql_EXPORTS
|
||||
#define MATADOR_MYSQL_API __declspec(dllexport)
|
||||
#else
|
||||
#define MATADOR_MYSQL_API __declspec(dllimport)
|
||||
#endif
|
||||
#pragma warning(disable: 4355)
|
||||
#else
|
||||
#define MATADOR_MYSQL_API
|
||||
#endif
|
||||
|
||||
#include "matador/sql/dialect.hpp"
|
||||
|
||||
extern "C" [[maybe_unused]] MATADOR_MYSQL_API const matador::sql::dialect* get_dialect();
|
||||
|
||||
#endif //QUERY_POSTGRES_DIALECT_HPP
|
||||
@@ -1,20 +0,0 @@
|
||||
#ifndef QUERY_POSTGRES_ERROR_HPP
|
||||
#define QUERY_POSTGRES_ERROR_HPP
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <mysql.h>
|
||||
#else
|
||||
#include <mysql/mysql.h>
|
||||
#endif
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
void throw_mysql_error(const char *what, const std::string &source);
|
||||
void throw_mysql_error(MYSQL *db, const std::string &source);
|
||||
void throw_mysql_error(MYSQL_STMT *stmt, const std::string &source, const std::string &sql);
|
||||
|
||||
}
|
||||
|
||||
#endif //QUERY_POSTGRES_ERROR_HPP
|
||||
@@ -1,74 +0,0 @@
|
||||
#ifndef QUERY_POSTGRES_PARAMETER_BINDER_H
|
||||
#define QUERY_POSTGRES_PARAMETER_BINDER_H
|
||||
|
||||
#include "matador/sql/parameter_binder.hpp"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <mysql.h>
|
||||
#else
|
||||
#include <mysql/mysql.h>
|
||||
#endif
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
struct mysql_result_info
|
||||
{
|
||||
unsigned long length = 0;
|
||||
my_bool is_null = false;
|
||||
my_bool error = false;
|
||||
// std::unique_ptr<char[]> buffer;
|
||||
char *buffer = nullptr;
|
||||
unsigned long buffer_length = 0;
|
||||
bool is_allocated = false;
|
||||
|
||||
~mysql_result_info()
|
||||
{
|
||||
if (is_allocated) {
|
||||
delete [] buffer;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class mysql_parameter_binder final : public sql::parameter_binder
|
||||
{
|
||||
public:
|
||||
explicit mysql_parameter_binder(size_t size);
|
||||
|
||||
void bind(size_t pos, char i) override;
|
||||
void bind(size_t pos, short i) override;
|
||||
void bind(size_t pos, int i) override;
|
||||
void bind(size_t pos, long i) override;
|
||||
void bind(size_t pos, long long int i) override;
|
||||
void bind(size_t pos, unsigned char i) override;
|
||||
void bind(size_t pos, unsigned short i) override;
|
||||
void bind(size_t pos, unsigned int i) override;
|
||||
void bind(size_t pos, unsigned long i) override;
|
||||
void bind(size_t pos, unsigned long long int i) override;
|
||||
void bind(size_t pos, bool b) override;
|
||||
void bind(size_t pos, float d) override;
|
||||
void bind(size_t pos, double d) override;
|
||||
void bind(size_t pos, const char *string) override;
|
||||
void bind(size_t pos, const char *string, size_t size) override;
|
||||
void bind(size_t pos, const std::string &string) override;
|
||||
void bind(size_t pos, const std::string &x, size_t size) override;
|
||||
|
||||
void bind(size_t pos, const utils::blob &blob) override;
|
||||
|
||||
[[nodiscard]] std::vector<MYSQL_BIND>& bind_params();
|
||||
|
||||
private:
|
||||
struct is_null_t
|
||||
{
|
||||
my_bool is_null = false;
|
||||
};
|
||||
|
||||
std::vector<MYSQL_BIND> bind_params_;
|
||||
std::vector<is_null_t> is_null_vector;
|
||||
std::vector<mysql_result_info> info_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //QUERY_POSTGRES_PARAMETER_BINDER_H
|
||||
@@ -1,36 +0,0 @@
|
||||
#ifndef QUERY_MYSQL_PREPARED_RESULT_READER_HPP
|
||||
#define QUERY_MYSQL_PREPARED_RESULT_READER_HPP
|
||||
|
||||
#include "matador/sql/query_result_reader.hpp"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <mysql.h>
|
||||
#else
|
||||
#include <mysql/mysql.h>
|
||||
#endif
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
class mysql_prepared_result_reader : public sql::query_result_reader
|
||||
{
|
||||
public:
|
||||
explicit mysql_prepared_result_reader(MYSQL_STMT *stmt);
|
||||
~mysql_prepared_result_reader() override;
|
||||
|
||||
[[nodiscard]] size_t column_count() const override;
|
||||
[[nodiscard]] const char *column(size_t index) const override;
|
||||
bool fetch() override;
|
||||
|
||||
private:
|
||||
MYSQL_STMT *stmt_{};
|
||||
|
||||
MYSQL_ROW current_row_{};
|
||||
|
||||
size_t row_count_{};
|
||||
size_t column_count_{};
|
||||
int row_index_{-1};
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //QUERY_MYSQL_PREPARED_RESULT_READER_HPP
|
||||
@@ -1,36 +0,0 @@
|
||||
#ifndef QUERY_POSTGRES_RESULT_READER_HPP
|
||||
#define QUERY_POSTGRES_RESULT_READER_HPP
|
||||
|
||||
#include "matador/sql/query_result_reader.hpp"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <mysql.h>
|
||||
#else
|
||||
#include <mysql/mysql.h>
|
||||
#endif
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
class mysql_result_reader : public sql::query_result_reader
|
||||
{
|
||||
public:
|
||||
explicit mysql_result_reader(MYSQL_RES *result, unsigned int column_count);
|
||||
~mysql_result_reader() override;
|
||||
|
||||
[[nodiscard]] size_t column_count() const override;
|
||||
[[nodiscard]] const char *column(size_t index) const override;
|
||||
bool fetch() override;
|
||||
|
||||
private:
|
||||
MYSQL_RES *result_{};
|
||||
|
||||
MYSQL_ROW current_row_{};
|
||||
|
||||
size_t row_count_{};
|
||||
size_t column_count_{};
|
||||
int row_index_{-1};
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //QUERY_POSTGRES_RESULT_READER_HPP
|
||||
@@ -1,37 +0,0 @@
|
||||
#ifndef QUERY_POSTGRES_STATEMENT_HPP
|
||||
#define QUERY_POSTGRES_STATEMENT_HPP
|
||||
|
||||
#include "matador/sql/statement_impl.hpp"
|
||||
|
||||
#include "mysql_parameter_binder.hpp"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <mysql.h>
|
||||
#else
|
||||
#include <mysql/mysql.h>
|
||||
#endif
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
class mysql_statement final : public sql::statement_impl
|
||||
{
|
||||
public:
|
||||
mysql_statement(MYSQL_STMT *stmt, const sql::query_context &query);
|
||||
|
||||
size_t execute() override;
|
||||
std::unique_ptr<sql::query_result_impl> fetch() override;
|
||||
void reset() override;
|
||||
protected:
|
||||
sql::parameter_binder& binder() override;
|
||||
|
||||
private:
|
||||
MYSQL_STMT *stmt_{nullptr};
|
||||
|
||||
std::string name_;
|
||||
|
||||
mysql_parameter_binder binder_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //QUERY_POSTGRES_STATEMENT_HPP
|
||||
@@ -1,280 +0,0 @@
|
||||
#include "mysql_connection.hpp"
|
||||
#include "mysql_error.hpp"
|
||||
#include "mysql_result_reader.hpp"
|
||||
#include "mysql_statement.hpp"
|
||||
|
||||
#include "matador/sql/record.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <regex>
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
mysql_connection::string_to_int_map mysql_connection::statement_name_map_{};
|
||||
|
||||
mysql_connection::mysql_connection(const sql::connection_info &info)
|
||||
: connection_impl(info) {}
|
||||
|
||||
void mysql_connection::open()
|
||||
{
|
||||
if (is_open()) {
|
||||
return;
|
||||
}
|
||||
|
||||
mysql_ = std::make_unique<MYSQL>();
|
||||
|
||||
if (!mysql_init(mysql_.get())) {
|
||||
throw_mysql_error(mysql_.get(), "mysql_init");
|
||||
}
|
||||
|
||||
if (!mysql_real_connect(mysql_.get(),
|
||||
info().hostname.c_str(),
|
||||
info().user.c_str(),
|
||||
!info().password.empty() ? info().password.c_str() : nullptr,
|
||||
info().database.c_str(),
|
||||
info().port,
|
||||
nullptr,
|
||||
0)) {
|
||||
// disconnect all handles
|
||||
const std::string error_message = mysql_error(mysql_.get());
|
||||
mysql_close(mysql_.get());
|
||||
|
||||
mysql_.reset();
|
||||
// throw exception
|
||||
throw_mysql_error(error_message.c_str(), "mysql_real_connect");
|
||||
}
|
||||
}
|
||||
|
||||
void mysql_connection::close()
|
||||
{
|
||||
if (mysql_) {
|
||||
mysql_close(mysql_.get());
|
||||
mysql_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
bool mysql_connection::is_open()
|
||||
{
|
||||
return mysql_ != nullptr;
|
||||
}
|
||||
|
||||
sql::data_type_t to_type(enum_field_types type, unsigned int flags)
|
||||
{
|
||||
switch (type) {
|
||||
case MYSQL_TYPE_TINY:
|
||||
return flags & UNSIGNED_FLAG ? sql::data_type_t::type_unsigned_char : sql::data_type_t::type_char;
|
||||
case MYSQL_TYPE_SHORT:
|
||||
return flags & UNSIGNED_FLAG ? sql::data_type_t::type_unsigned_short : sql::data_type_t::type_short;
|
||||
case MYSQL_TYPE_LONG:
|
||||
return flags & UNSIGNED_FLAG ? sql::data_type_t::type_unsigned_int : sql::data_type_t::type_int;
|
||||
case MYSQL_TYPE_LONGLONG:
|
||||
return flags & UNSIGNED_FLAG ? sql::data_type_t::type_unsigned_long_long : sql::data_type_t::type_long_long;
|
||||
case MYSQL_TYPE_FLOAT:
|
||||
return sql::data_type_t::type_float;
|
||||
case MYSQL_TYPE_DOUBLE:
|
||||
return sql::data_type_t::type_double;
|
||||
case MYSQL_TYPE_VARCHAR:
|
||||
case MYSQL_TYPE_VAR_STRING:
|
||||
return sql::data_type_t::type_varchar;
|
||||
case MYSQL_TYPE_BLOB:
|
||||
return sql::data_type_t::type_blob;
|
||||
case MYSQL_TYPE_STRING:
|
||||
return sql::data_type_t::type_text;
|
||||
case MYSQL_TYPE_DATE:
|
||||
return sql::data_type_t::type_date;
|
||||
case MYSQL_TYPE_DATETIME:
|
||||
case MYSQL_TYPE_TIMESTAMP:
|
||||
return sql::data_type_t::type_time;
|
||||
default:
|
||||
return sql::data_type_t::type_unknown;
|
||||
}
|
||||
}
|
||||
|
||||
utils::constraints to_constraints(unsigned int flags)
|
||||
{
|
||||
utils::constraints options{utils::constraints::NONE};
|
||||
if (flags & PRI_KEY_FLAG) {
|
||||
options |= utils::constraints::PRIMARY_KEY;
|
||||
}
|
||||
if (flags & UNIQUE_KEY_FLAG) {
|
||||
options |= utils::constraints::UNIQUE;
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
sql::null_option to_null_option(unsigned int flags)
|
||||
{
|
||||
return flags & NOT_NULL_FLAG ? sql::null_option::NOT_NULL : sql::null_option::NULLABLE;
|
||||
}
|
||||
|
||||
sql::data_type_t string2type(const std::string &type_string)
|
||||
{
|
||||
if (strncmp(type_string.c_str(), "tinyint", 7) == 0) {
|
||||
return sql::data_type_t::type_char;
|
||||
} else if (strncmp(type_string.c_str(), "smallint", 8) == 0) {
|
||||
if (strstr(type_string.c_str(), "unsigned") != nullptr) {
|
||||
return sql::data_type_t::type_unsigned_short;
|
||||
} else {
|
||||
return sql::data_type_t::type_short;
|
||||
}
|
||||
} else if (strncmp(type_string.c_str(), "int", 3) == 0) {
|
||||
if (strstr(type_string.c_str(), "unsigned") != nullptr) {
|
||||
return sql::data_type_t::type_unsigned_int;
|
||||
} else {
|
||||
return sql::data_type_t::type_int;
|
||||
}
|
||||
} else if (strncmp(type_string.c_str(), "bigint", 6) == 0) {
|
||||
if (strstr(type_string.c_str(), "unsigned") != nullptr) {
|
||||
return sql::data_type_t::type_unsigned_long_long;
|
||||
} else {
|
||||
return sql::data_type_t::type_long_long;
|
||||
}
|
||||
} else if (strcmp(type_string.c_str(), "date") == 0) {
|
||||
return sql::data_type_t::type_date;
|
||||
} else if (strncmp(type_string.c_str(), "datetime", 8) == 0) {
|
||||
return sql::data_type_t::type_time;
|
||||
} else if (strcmp(type_string.c_str(), "float") == 0) {
|
||||
return sql::data_type_t::type_float;
|
||||
} else if (strcmp(type_string.c_str(), "double") == 0) {
|
||||
return sql::data_type_t::type_double;
|
||||
} else if (strncmp(type_string.c_str(), "varchar", 7) == 0) {
|
||||
return sql::data_type_t::type_varchar;
|
||||
} else if (strncmp(type_string.c_str(), "text", 4) == 0) {
|
||||
return sql::data_type_t::type_text;
|
||||
} else {
|
||||
return sql::data_type_t::type_unknown;
|
||||
}
|
||||
}
|
||||
|
||||
struct type_info
|
||||
{
|
||||
sql::data_type_t type{sql::data_type_t::type_unknown};
|
||||
size_t size{};
|
||||
};
|
||||
|
||||
type_info determine_type_info(const std::string &type_string)
|
||||
{
|
||||
static const std::regex TYPE_REGEX(R"(^(\w+)(\((\d+)(,(\d+))?\))?$)");
|
||||
std::smatch matcher;
|
||||
|
||||
type_info result;
|
||||
if (std::regex_match(type_string, matcher, TYPE_REGEX)) {
|
||||
result.type = string2type(matcher[1].str());
|
||||
if (matcher[3].matched) {
|
||||
result.size = std::stoi(matcher[3].str());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::unique_ptr<sql::query_result_impl> mysql_connection::fetch(const std::string &stmt)
|
||||
{
|
||||
if (mysql_query(mysql_.get(), stmt.c_str())) {
|
||||
throw_mysql_error(mysql_.get(), stmt);
|
||||
}
|
||||
|
||||
auto result = mysql_store_result(mysql_.get());
|
||||
if (result == nullptr) {
|
||||
throw_mysql_error(mysql_.get(), stmt);
|
||||
}
|
||||
|
||||
auto field_count = mysql_num_fields(result);
|
||||
auto fields = mysql_fetch_fields(result);
|
||||
std::vector<sql::column_definition> prototype;
|
||||
for (unsigned i = 0; i < field_count; ++i) {
|
||||
auto type = to_type(fields[i].type, fields[i].flags);
|
||||
auto options = to_constraints(fields[i].flags);
|
||||
auto null_opt = to_null_option(fields[i].flags);
|
||||
|
||||
prototype.emplace_back(fields[i].name, type, options, null_opt);
|
||||
}
|
||||
|
||||
return std::move(std::make_unique<sql::query_result_impl>(std::make_unique<mysql_result_reader>(result, field_count), std::move(prototype)));
|
||||
}
|
||||
|
||||
std::unique_ptr<sql::statement_impl> mysql_connection::prepare(sql::query_context context)
|
||||
{
|
||||
MYSQL_STMT *stmt = mysql_stmt_init(mysql_.get());
|
||||
if (stmt == nullptr) {
|
||||
throw_mysql_error(mysql_.get(), "mysql_stmt_init");
|
||||
}
|
||||
|
||||
if (mysql_stmt_prepare(stmt, context.sql.c_str(), static_cast<unsigned long>(context.sql.size())) != 0) {
|
||||
throw_mysql_error(stmt, "mysql_stmt_prepare", context.sql);
|
||||
}
|
||||
|
||||
return std::make_unique<mysql_statement>(stmt, std::move(context));
|
||||
}
|
||||
|
||||
size_t mysql_connection::execute(const std::string &stmt)
|
||||
{
|
||||
if (mysql_query(mysql_.get(), stmt.c_str())) {
|
||||
throw_mysql_error(mysql_.get(), stmt);
|
||||
}
|
||||
|
||||
return mysql_affected_rows(mysql_.get());
|
||||
}
|
||||
|
||||
std::vector<sql::column_definition> mysql_connection::describe(const std::string &table)
|
||||
{
|
||||
std::string stmt("SHOW COLUMNS FROM " + table);
|
||||
|
||||
if (mysql_query(mysql_.get(), stmt.c_str())) {
|
||||
throw_mysql_error(mysql_.get(), stmt);
|
||||
}
|
||||
|
||||
auto result = mysql_store_result(mysql_.get());
|
||||
if (result == nullptr) {
|
||||
throw_mysql_error(mysql_.get(), stmt);
|
||||
}
|
||||
|
||||
mysql_result_reader reader(result, mysql_num_fields(result));
|
||||
std::vector<sql::column_definition> prototype;
|
||||
while (reader.fetch()) {
|
||||
|
||||
char *end = nullptr;
|
||||
std::string name = reader.column(0);
|
||||
|
||||
auto typeinfo = determine_type_info(reader.column(1));
|
||||
end = nullptr;
|
||||
sql::null_option null_opt{sql::null_option::NULLABLE};
|
||||
if (strtoul(reader.column(2), &end, 10) == 0) {
|
||||
null_opt = sql::null_option::NOT_NULL;
|
||||
}
|
||||
prototype.push_back({name, typeinfo.type, {typeinfo.size}, null_opt, prototype.size()});
|
||||
}
|
||||
|
||||
return prototype;
|
||||
}
|
||||
|
||||
bool mysql_connection::exists(const std::string &/*schema_name*/, const std::string &table_name)
|
||||
{
|
||||
std::string stmt("SELECT 1 FROM information_schema.tables WHERE table_schema = '" + info().database + "' AND table_name = '" + table_name + "'");
|
||||
|
||||
if (mysql_query(mysql_.get(), stmt.c_str())) {
|
||||
throw_mysql_error(mysql_.get(), stmt);
|
||||
}
|
||||
|
||||
auto result = mysql_store_result(mysql_.get());
|
||||
if (result == nullptr) {
|
||||
throw_mysql_error(mysql_.get(), stmt);
|
||||
}
|
||||
|
||||
return result->row_count == 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extern "C"
|
||||
{
|
||||
MATADOR_MYSQL_API matador::sql::connection_impl *create_database(const matador::sql::connection_info &info)
|
||||
{
|
||||
return new matador::backends::mysql::mysql_connection(info);
|
||||
}
|
||||
|
||||
MATADOR_MYSQL_API void destroy_database(matador::sql::connection_impl *db)
|
||||
{
|
||||
delete db;
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
#include "mysql_dialect.hpp"
|
||||
|
||||
#include "matador/sql/dialect_builder.hpp"
|
||||
|
||||
[[maybe_unused]] const matador::sql::dialect *get_dialect()
|
||||
{
|
||||
using namespace matador::sql;
|
||||
const static dialect d = dialect_builder::builder()
|
||||
.create()
|
||||
.with_token_replace_map({
|
||||
{dialect::token_t::START_QUOTE, "`"},
|
||||
{dialect::token_t::END_QUOTE, "`"},
|
||||
})
|
||||
.with_default_schema_name("")
|
||||
.build();
|
||||
return &d;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
#include "mysql_error.hpp"
|
||||
|
||||
#include <sstream>
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
void throw_mysql_error(const char *what, const std::string &source)
|
||||
{
|
||||
std::stringstream msg;
|
||||
msg << "mysql error (" << source << "): " << what;
|
||||
throw std::logic_error(msg.str());
|
||||
}
|
||||
|
||||
void throw_mysql_error(MYSQL *db, const std::string &source)
|
||||
{
|
||||
if (mysql_errno(db) != 0) {
|
||||
throw_mysql_error(mysql_error(db), source);
|
||||
}
|
||||
}
|
||||
|
||||
void throw_mysql_error(MYSQL_STMT *stmt, const std::string &source, const std::string &sql)
|
||||
{
|
||||
if (mysql_stmt_errno(stmt) != 0) {
|
||||
std::stringstream msg;
|
||||
msg << "mysql error (" << source << ") " << mysql_stmt_error(stmt) << ": " << sql;
|
||||
throw std::logic_error(msg.str());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
#include "mysql_parameter_binder.hpp"
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
namespace detail {
|
||||
|
||||
template < class T >
|
||||
void bind_value(enum_field_types type, T value, MYSQL_BIND &bind, my_bool &is_null)
|
||||
{
|
||||
if (bind.buffer == nullptr) {
|
||||
// allocating memory
|
||||
bind.buffer = new char[sizeof(T)];
|
||||
bind.buffer_type = type;
|
||||
bind.buffer_length = sizeof(T);
|
||||
bind.is_null = &is_null;
|
||||
bind.is_unsigned = std::is_unsigned<T>::value;
|
||||
}
|
||||
*static_cast<T*>(bind.buffer) = value;
|
||||
is_null = false;
|
||||
}
|
||||
|
||||
void bind_value(enum_field_types type, const char *value, size_t, MYSQL_BIND &bind, my_bool &is_null)
|
||||
{
|
||||
std::size_t len(strlen(value) + 1);
|
||||
if (bind.buffer_length < len) {
|
||||
// reallocate memory
|
||||
delete [] static_cast<char*>(bind.buffer);
|
||||
bind.buffer = nullptr;
|
||||
bind.buffer_length = 0;
|
||||
bind.buffer_type = type;
|
||||
bind.is_null = &is_null;
|
||||
}
|
||||
if (bind.buffer == nullptr) {
|
||||
// allocating memory
|
||||
bind.buffer = new char[len];
|
||||
memset(bind.buffer, 0, len);
|
||||
}
|
||||
bind.buffer_length = (unsigned long)(len - 1);
|
||||
#ifdef _MSC_VER
|
||||
strncpy_s(static_cast<char*>(bind.buffer), len, value, _TRUNCATE);
|
||||
#else
|
||||
strncpy(static_cast<char*>(bind.buffer), value, len);
|
||||
#endif
|
||||
is_null = false;
|
||||
}
|
||||
|
||||
//void bind_value(enum_field_types type, const matador::date &x, MYSQL_BIND &bind, my_bool &is_null)
|
||||
//{
|
||||
// if (bind.buffer == nullptr) {
|
||||
// size_t s = sizeof(MYSQL_TIME);
|
||||
// bind.buffer = new char[s];
|
||||
// bind.buffer_length = (unsigned long)s;
|
||||
// bind.is_null = &is_null;
|
||||
// bind.buffer_type = type;
|
||||
// bind.length = nullptr;
|
||||
// }
|
||||
// memset(bind.buffer, 0, sizeof(MYSQL_TIME));
|
||||
// is_null = false;
|
||||
// auto *mt = static_cast<MYSQL_TIME*>(bind.buffer);
|
||||
// mt->day = (unsigned int)x.day();
|
||||
// mt->month = (unsigned int)x.month();
|
||||
// mt->year = (unsigned int)x.year();
|
||||
// mt->time_type = MYSQL_TIMESTAMP_DATE;
|
||||
//}
|
||||
//
|
||||
//void bind_value(enum_field_types type, const matador::time &x, MYSQL_BIND &bind, my_bool &is_null)
|
||||
//{
|
||||
// if (bind.buffer == nullptr) {
|
||||
// size_t s = sizeof(MYSQL_TIME);
|
||||
// bind.buffer = new char[s];
|
||||
// bind.buffer_length = (unsigned long)s;
|
||||
// bind.buffer_type = type;
|
||||
// bind.length = nullptr;
|
||||
// bind.is_null = &is_null;
|
||||
// }
|
||||
// memset(bind.buffer, 0, sizeof(MYSQL_TIME));
|
||||
// is_null = false;
|
||||
// auto *mt = static_cast<MYSQL_TIME*>(bind.buffer);
|
||||
// mt->day = (unsigned int)x.day();
|
||||
// mt->month = (unsigned int)x.month();
|
||||
// mt->year = (unsigned int)x.year();
|
||||
// mt->hour = (unsigned int)x.hour();
|
||||
// mt->minute = (unsigned int)x.minute();
|
||||
// mt->second = (unsigned int)x.second();
|
||||
// mt->second_part = (unsigned long)x.milli_second() * 1000;
|
||||
// mt->time_type = MYSQL_TIMESTAMP_DATETIME;
|
||||
//}
|
||||
|
||||
}
|
||||
|
||||
mysql_parameter_binder::mysql_parameter_binder(size_t size)
|
||||
: bind_params_(size)
|
||||
, is_null_vector(size)
|
||||
, info_(size)
|
||||
{}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, char i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_TINY, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, short i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_SHORT, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, int i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_LONG, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, long i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_LONG, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, long long int i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_LONGLONG, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, unsigned char i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_TINY, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, unsigned short i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_SHORT, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, unsigned int i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_LONG, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, unsigned long i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_LONG, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, unsigned long long int i)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_LONGLONG, i, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, bool b)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_TINY, b, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, float d)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_FLOAT, d, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, double d)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_DOUBLE, d, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, const char *str)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_STRING, str, strlen(str), bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, const char *str, size_t size)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_VAR_STRING, str, size, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, const std::string &str)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_STRING, str.data(), str.size(), bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, const std::string &str, size_t size)
|
||||
{
|
||||
detail::bind_value(MYSQL_TYPE_VAR_STRING, str.data(), size, bind_params_[pos], is_null_vector[pos].is_null);
|
||||
}
|
||||
|
||||
void mysql_parameter_binder::bind(size_t pos, const utils::blob &blob)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
std::vector<MYSQL_BIND> &mysql_parameter_binder::bind_params()
|
||||
{
|
||||
return bind_params_;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
#include "mysql_prepared_result_reader.hpp"
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
mysql_prepared_result_reader::mysql_prepared_result_reader(MYSQL_STMT *stmt)
|
||||
: stmt_(stmt)
|
||||
{}
|
||||
|
||||
mysql_prepared_result_reader::~mysql_prepared_result_reader()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
size_t mysql_prepared_result_reader::column_count() const
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char *mysql_prepared_result_reader::column(size_t index) const
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool mysql_prepared_result_reader::fetch()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
#include "mysql_result_reader.hpp"
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
mysql_result_reader::mysql_result_reader(MYSQL_RES *result, unsigned int column_count)
|
||||
: result_(result)
|
||||
, row_count_(mysql_num_rows(result_))
|
||||
, column_count_(column_count)
|
||||
{}
|
||||
|
||||
mysql_result_reader::~mysql_result_reader()
|
||||
{
|
||||
if (result_) {
|
||||
mysql_free_result(result_);
|
||||
}
|
||||
}
|
||||
|
||||
size_t mysql_result_reader::column_count() const
|
||||
{
|
||||
return column_count_;
|
||||
}
|
||||
|
||||
const char *mysql_result_reader::column(size_t index) const
|
||||
{
|
||||
return current_row_[index];
|
||||
}
|
||||
|
||||
bool mysql_result_reader::fetch()
|
||||
{
|
||||
current_row_ = mysql_fetch_row(result_);
|
||||
|
||||
return current_row_ != nullptr;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
#include "mysql_statement.hpp"
|
||||
#include "mysql_error.hpp"
|
||||
#include "mysql_prepared_result_reader.hpp"
|
||||
|
||||
namespace matador::backends::mysql {
|
||||
|
||||
mysql_statement::mysql_statement(MYSQL_STMT *stmt, const sql::query_context &query)
|
||||
: statement_impl(query)
|
||||
, stmt_(stmt)
|
||||
, binder_(query_.bind_vars.size())
|
||||
{}
|
||||
|
||||
size_t mysql_statement::execute()
|
||||
{
|
||||
if (!binder_.bind_params().empty()) {
|
||||
if (mysql_stmt_bind_param(stmt_, binder_.bind_params().data()) != 0) {
|
||||
throw_mysql_error(stmt_, "mysql", query_.sql);
|
||||
}
|
||||
}
|
||||
|
||||
if (mysql_stmt_execute(stmt_) != 0) {
|
||||
throw_mysql_error(stmt_, "mysql", query_.sql);
|
||||
}
|
||||
|
||||
return mysql_stmt_affected_rows(stmt_);
|
||||
}
|
||||
|
||||
std::unique_ptr<sql::query_result_impl> mysql_statement::fetch()
|
||||
{
|
||||
if (!binder_.bind_params().empty()) {
|
||||
if (mysql_stmt_bind_param(stmt_, binder_.bind_params().data()) != 0) {
|
||||
throw_mysql_error(stmt_, "mysql", query_.sql);
|
||||
}
|
||||
}
|
||||
|
||||
if (mysql_stmt_execute(stmt_) != 0) {
|
||||
throw_mysql_error(stmt_, "mysql", query_.sql);
|
||||
}
|
||||
if (mysql_stmt_store_result(stmt_) != 0) {
|
||||
throw_mysql_error(stmt_, "mysql", query_.sql);
|
||||
}
|
||||
|
||||
return std::move(std::make_unique<sql::query_result_impl>(std::make_unique<mysql_prepared_result_reader>(stmt_), std::move(query_.prototype)));
|
||||
}
|
||||
|
||||
void mysql_statement::reset() {}
|
||||
|
||||
sql::parameter_binder& mysql_statement::binder()
|
||||
{
|
||||
return binder_;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
Include(FetchContent)
|
||||
|
||||
FetchContent_Declare(
|
||||
Catch2
|
||||
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
|
||||
GIT_TAG v3.5.4 # or a later release
|
||||
)
|
||||
|
||||
FetchContent_MakeAvailable(Catch2)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${catch2_SOURCE_DIR}/extras)
|
||||
include(CTest)
|
||||
include(Catch)
|
||||
|
||||
set(MYSQL_CONNECTION_STRING "mysql://test:test123!@127.0.0.1:3306/matador_test")
|
||||
|
||||
configure_file(Connection.hpp.in ${PROJECT_BINARY_DIR}/backends/mysql/test/connection.hpp @ONLY IMMEDIATE)
|
||||
|
||||
message(STATUS "mysql connection string: ${MYSQL_CONNECTION_STRING}")
|
||||
|
||||
set(TEST_SOURCES
|
||||
../../tests/QueryTest.cpp
|
||||
../../tests/QueryTest.cpp
|
||||
../../tests/ConnectionTest.cpp
|
||||
../../tests/QueryRecordTest.cpp
|
||||
../../tests/StatementTest.cpp
|
||||
../../tests/TypeTraitsTest.cpp
|
||||
../../tests/StatementCacheTest.cpp
|
||||
../../tests/SessionTest.cpp)
|
||||
|
||||
set(LIBRARY_TEST_TARGET mysql_tests)
|
||||
|
||||
add_executable(${LIBRARY_TEST_TARGET} ${TEST_SOURCES})
|
||||
|
||||
target_link_libraries(${LIBRARY_TEST_TARGET} PRIVATE
|
||||
Catch2::Catch2WithMain
|
||||
matador
|
||||
${CMAKE_DL_LIBS}
|
||||
${MySQL_LIBRARY})
|
||||
|
||||
target_include_directories(${LIBRARY_TEST_TARGET}
|
||||
PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>/include
|
||||
PRIVATE $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>/test
|
||||
PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
catch_discover_tests(${LIBRARY_TEST_TARGET} TEST_SUFFIX " (MySQL)")
|
||||
@@ -1,8 +0,0 @@
|
||||
#ifndef MYSQL_CONNECTION_HPP
|
||||
#define MYSQL_CONNECTION_HPP
|
||||
|
||||
namespace matador::test::connection {
|
||||
const char* const dns = "@MYSQL_CONNECTION_STRING@";
|
||||
}
|
||||
|
||||
#endif /*SQLITE_CONNECTION_HPP*/
|
||||
@@ -32,4 +32,10 @@ target_include_directories(${LIBRARY_TARGET} PRIVATE
|
||||
${PROJECT_SOURCE_DIR}/backends/postgres/include
|
||||
${PostgreSQL_INCLUDE_DIRS})
|
||||
|
||||
target_link_libraries(${LIBRARY_TARGET} matador ${PostgreSQL_LIBRARIES})
|
||||
target_link_libraries(${LIBRARY_TARGET}
|
||||
matador-core
|
||||
matador-orm
|
||||
${CMAKE_DL_LIBS}
|
||||
${CMAKE_THREAD_LIBS_INIT}
|
||||
${PostgreSQL_LIBRARIES}
|
||||
)
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
#define MATADOR_POSTGRES_API
|
||||
#endif
|
||||
|
||||
#include "matador/sql/connection_impl.hpp"
|
||||
#include "matador/sql/interface/connection_impl.hpp"
|
||||
|
||||
#include <unordered_map>
|
||||
|
||||
@@ -20,22 +20,25 @@
|
||||
|
||||
namespace matador::backends::postgres {
|
||||
|
||||
class postgres_connection : public matador::sql::connection_impl
|
||||
class postgres_connection : public sql::connection_impl
|
||||
{
|
||||
public:
|
||||
explicit postgres_connection(const sql::connection_info &info);
|
||||
void open() override;
|
||||
void close() override;
|
||||
bool is_open() override;
|
||||
utils::result<void, utils::error> open() override;
|
||||
utils::result<void, utils::error> close() override;
|
||||
[[nodiscard]] utils::result<bool, utils::error> is_open() const override;
|
||||
[[nodiscard]] utils::result<bool, utils::error> is_valid() const override;
|
||||
[[nodiscard]] utils::result<utils::version, utils::error> client_version() const override;
|
||||
[[nodiscard]] utils::result<utils::version, utils::error> server_version() const override;
|
||||
|
||||
std::unique_ptr<sql::query_result_impl> fetch(const std::string &stmt) override;
|
||||
std::unique_ptr<sql::statement_impl> prepare(sql::query_context context) override;
|
||||
utils::result<size_t, utils::error> execute(const std::string &stmt) override;
|
||||
utils::result<std::unique_ptr<sql::statement_impl>, utils::error> prepare(const sql::query_context &context) override;
|
||||
utils::result<std::unique_ptr<sql::query_result_impl>, utils::error> fetch(const sql::query_context &context) override;
|
||||
|
||||
size_t execute(const std::string &stmt) override;
|
||||
utils::result<std::vector<object::attribute_definition>, utils::error> describe(const std::string& table) override;
|
||||
utils::result<bool, utils::error> exists(const std::string &schema_name, const std::string &table_name) override;
|
||||
|
||||
std::vector<sql::column_definition> describe(const std::string& table) override;
|
||||
|
||||
bool exists(const std::string &schema_name, const std::string &table_name) override;
|
||||
[[nodiscard]] std::string to_escaped_string( const utils::blob& value ) const override;
|
||||
|
||||
private:
|
||||
[[nodiscard]] static std::string generate_statement_name(const sql::query_context &query) ;
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
#ifndef QUERY_POSTGRES_ERROR_HPP
|
||||
#define QUERY_POSTGRES_ERROR_HPP
|
||||
|
||||
#include "matador/utils/error.hpp"
|
||||
|
||||
#include "matador/sql/error_code.hpp"
|
||||
|
||||
#include <libpq-fe.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace matador::backends::postgres {
|
||||
|
||||
void throw_postgres_error(const char *what, const std::string &source);
|
||||
void throw_postgres_error(PGconn *db, const std::string &source);
|
||||
void throw_postgres_error(PGresult *res, PGconn *db, const std::string &source, const std::string &sql);
|
||||
utils::error make_error(sql::error_code ec,
|
||||
const PGresult *res,
|
||||
const PGconn *db,
|
||||
const std::string &msg,
|
||||
const std::string &sql = {});
|
||||
|
||||
bool is_result_error(const PGresult *res);
|
||||
|
||||
// void throw_postgres_error(const char *what, const std::string &source);
|
||||
// void throw_postgres_error(PGconn *db, const std::string &source);
|
||||
// void throw_postgres_error(PGresult *res, PGconn *db, const std::string &source, const std::string &sql);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,42 +1,52 @@
|
||||
#ifndef QUERY_POSTGRES_PARAMETER_BINDER_H
|
||||
#define QUERY_POSTGRES_PARAMETER_BINDER_H
|
||||
|
||||
#include "matador/sql/parameter_binder.hpp"
|
||||
#include "matador/utils/attribute_writer.hpp"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace matador::backends::postgres {
|
||||
|
||||
class postgres_parameter_binder final : public sql::parameter_binder
|
||||
class postgres_parameter_binder final : public utils::attribute_writer
|
||||
{
|
||||
public:
|
||||
struct bind_data {
|
||||
explicit bind_data(size_t size);
|
||||
std::vector<std::string> strings;
|
||||
std::vector<std::vector<unsigned char>> bytes;
|
||||
std::vector<const char*> values;
|
||||
std::vector<int> lengths;
|
||||
std::vector<int> formats;
|
||||
};
|
||||
|
||||
explicit postgres_parameter_binder(size_t size);
|
||||
|
||||
void bind(size_t pos, char i) override;
|
||||
void bind(size_t pos, short i) override;
|
||||
void bind(size_t pos, int i) override;
|
||||
void bind(size_t pos, long i) override;
|
||||
void bind(size_t pos, long long int i) override;
|
||||
void bind(size_t pos, unsigned char i) override;
|
||||
void bind(size_t pos, unsigned short i) override;
|
||||
void bind(size_t pos, unsigned int i) override;
|
||||
void bind(size_t pos, unsigned long i) override;
|
||||
void bind(size_t pos, unsigned long long int i) override;
|
||||
void bind(size_t pos, bool b) override;
|
||||
void bind(size_t pos, float d) override;
|
||||
void bind(size_t pos, double d) override;
|
||||
void bind(size_t pos, const char *string) override;
|
||||
void bind(size_t pos, const char *string, size_t size) override;
|
||||
void bind(size_t pos, const std::string &string) override;
|
||||
void bind(size_t pos, const std::string &x, size_t size) override;
|
||||
void write_value(size_t pos, const uint8_t &x) override;
|
||||
void write_value(size_t pos, const uint16_t &x) override;
|
||||
void write_value(size_t pos, const uint32_t &x) override;
|
||||
void write_value(size_t pos, const uint64_t &x) override;
|
||||
void write_value(size_t pos, const int8_t &x) override;
|
||||
void write_value(size_t pos, const int16_t &x) override;
|
||||
void write_value(size_t pos, const int32_t &x) override;
|
||||
void write_value(size_t pos, const int64_t &x) override;
|
||||
void write_value(size_t pos, const bool &x) override;
|
||||
void write_value(size_t pos, const float &x) override;
|
||||
void write_value(size_t pos, const double &x) override;
|
||||
void write_value(size_t pos, const time &x ) override;
|
||||
void write_value(size_t pos, const date &x ) override;
|
||||
void write_value(size_t pos, const char *x) override;
|
||||
void write_value(size_t pos, const char *x, size_t size) override;
|
||||
void write_value(size_t pos, const std::string &x) override;
|
||||
void write_value(size_t pos, const std::string &x, size_t size) override;
|
||||
void write_value(size_t pos, const utils::blob &x) override;
|
||||
void write_value(size_t pos, const utils::value &x, size_t size) override;
|
||||
|
||||
void bind(size_t pos, const utils::blob &blob) override;
|
||||
|
||||
[[nodiscard]] const std::vector<const char*>& params() const;
|
||||
[[nodiscard]] const bind_data& params() const;
|
||||
|
||||
private:
|
||||
std::vector<std::string> strings_;
|
||||
std::vector<const char*> params_;
|
||||
bind_data bind_data_;
|
||||
// std::vector<std::string> strings_;
|
||||
// std::vector<const char*> params_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -1,12 +1,40 @@
|
||||
#ifndef QUERY_POSTGRES_RESULT_READER_HPP
|
||||
#define QUERY_POSTGRES_RESULT_READER_HPP
|
||||
|
||||
#include "matador/sql/interface/query_result_reader.hpp"
|
||||
|
||||
#include <libpq-fe.h>
|
||||
#include "matador/sql/query_result_reader.hpp"
|
||||
|
||||
namespace matador::backends::postgres {
|
||||
|
||||
class postgres_result_reader : public sql::query_result_reader
|
||||
namespace detail {
|
||||
|
||||
class empty_binder final : public utils::attribute_reader
|
||||
{
|
||||
public:
|
||||
void read_value(const char *, size_t, int8_t &) override {}
|
||||
void read_value(const char *, size_t, int16_t &) override {}
|
||||
void read_value(const char *, size_t, int32_t &) override {}
|
||||
void read_value(const char *, size_t, int64_t &) override {}
|
||||
void read_value(const char *, size_t, uint8_t &) override {}
|
||||
void read_value(const char *, size_t, uint16_t &) override {}
|
||||
void read_value(const char *, size_t, uint32_t &) override {}
|
||||
void read_value(const char *, size_t, uint64_t &) override {}
|
||||
void read_value(const char *, size_t, bool &) override {}
|
||||
void read_value(const char *, size_t, float &) override {}
|
||||
void read_value(const char *, size_t, double &) override {}
|
||||
void read_value(const char *, size_t, time &) override {}
|
||||
void read_value(const char *, size_t, date &) override {}
|
||||
void read_value(const char *, size_t, char *, size_t) override {}
|
||||
void read_value(const char *, size_t, std::string &) override {}
|
||||
void read_value(const char *, size_t, std::string &, size_t) override {}
|
||||
void read_value(const char *, size_t, utils::blob &) override {}
|
||||
void read_value(const char *, size_t, utils::value &, size_t) override {}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
class postgres_result_reader final : public sql::query_result_reader
|
||||
{
|
||||
public:
|
||||
explicit postgres_result_reader(PGresult *result);
|
||||
@@ -14,7 +42,31 @@ public:
|
||||
|
||||
[[nodiscard]] size_t column_count() const override;
|
||||
[[nodiscard]] const char *column(size_t index) const override;
|
||||
bool fetch() override;
|
||||
utils::result<bool, utils::error> fetch() override;
|
||||
[[nodiscard]] size_t start_column_index() const override;
|
||||
void unshift() override;
|
||||
|
||||
void read_value(const char *id, size_t index, int8_t &value) override;
|
||||
void read_value(const char *id, size_t index, int16_t &value) override;
|
||||
void read_value(const char *id, size_t index, int32_t &value) override;
|
||||
void read_value(const char *id, size_t index, int64_t &value) override;
|
||||
void read_value(const char *id, size_t index, uint8_t &value) override;
|
||||
void read_value(const char *id, size_t index, uint16_t &value) override;
|
||||
void read_value(const char *id, size_t index, uint32_t &value) override;
|
||||
void read_value(const char *id, size_t index, uint64_t &value) override;
|
||||
void read_value(const char *id, size_t index, bool &value) override;
|
||||
void read_value(const char *id, size_t index, float &value) override;
|
||||
void read_value(const char *id, size_t index, double &value) override;
|
||||
void read_value(const char *id, size_t index, matador::time &value) override;
|
||||
void read_value(const char *id, size_t index, matador::date &value) override;
|
||||
void read_value(const char *id, size_t index, char *value, size_t size) override;
|
||||
void read_value(const char *id, size_t index, std::string &value) override;
|
||||
void read_value(const char *id, size_t index, std::string &value, size_t size) override;
|
||||
void read_value(const char *id, size_t index, utils::blob &value) override;
|
||||
void read_value(const char *id, size_t index, utils::value &val, size_t size) override;
|
||||
|
||||
protected:
|
||||
attribute_reader &result_binder() override;
|
||||
|
||||
private:
|
||||
PGresult *result_{};
|
||||
@@ -22,6 +74,8 @@ private:
|
||||
size_t row_count_{};
|
||||
size_t column_count_{};
|
||||
int row_index_{-1};
|
||||
|
||||
detail::empty_binder empty_binder_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#ifndef QUERY_POSTGRES_STATEMENT_HPP
|
||||
#define QUERY_POSTGRES_STATEMENT_HPP
|
||||
|
||||
#include "matador/sql/statement_impl.hpp"
|
||||
#include "matador/sql/interface/statement_impl.hpp"
|
||||
|
||||
#include "postgres_parameter_binder.h"
|
||||
|
||||
@@ -14,11 +14,11 @@ class postgres_statement final : public sql::statement_impl
|
||||
public:
|
||||
postgres_statement(PGconn *db, PGresult *result, std::string name, const sql::query_context &query);
|
||||
|
||||
size_t execute() override;
|
||||
std::unique_ptr<sql::query_result_impl> fetch() override;
|
||||
utils::result<size_t, utils::error> execute() override;
|
||||
utils::result<std::unique_ptr<sql::query_result_impl>, utils::error> fetch() override;
|
||||
void reset() override;
|
||||
protected:
|
||||
sql::parameter_binder& binder() override;
|
||||
utils::attribute_writer& binder() override;
|
||||
|
||||
private:
|
||||
PGconn *db_{nullptr};
|
||||
|
||||
@@ -3,67 +3,112 @@
|
||||
#include "postgres_result_reader.hpp"
|
||||
#include "postgres_statement.hpp"
|
||||
|
||||
#include "matador/object/attribute_definition.hpp"
|
||||
|
||||
#include "matador/sql/error_code.hpp"
|
||||
#include "matador/sql/record.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include "matador/sql/internal/query_result_impl.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
|
||||
namespace matador::backends::postgres {
|
||||
|
||||
postgres_connection::string_to_int_map postgres_connection::statement_name_map_{};
|
||||
|
||||
postgres_connection::postgres_connection(const sql::connection_info &info)
|
||||
: connection_impl(info) {}
|
||||
: connection_impl(info) {
|
||||
}
|
||||
|
||||
void postgres_connection::open()
|
||||
{
|
||||
if (is_open()) {
|
||||
return;
|
||||
utils::result<void, utils::error> postgres_connection::open() {
|
||||
if (conn_ != nullptr) {
|
||||
return utils::ok<void>();
|
||||
}
|
||||
|
||||
std::string connection("user=" + info().user + " password=" + info().password + " host=" + info().hostname + " dbname=" + info().database + " port=" + std::to_string(info().port));
|
||||
const std::string connection(
|
||||
"user=" + info().user + " password=" + info().password + " host=" + info().hostname + " dbname=" + info().database +
|
||||
" port=" + std::to_string(info().port));
|
||||
|
||||
conn_ = PQconnectdb(connection.c_str());
|
||||
if (PQstatus(conn_) == CONNECTION_BAD) {
|
||||
const std::string msg = PQerrorMessage(conn_);
|
||||
PQfinish(conn_);
|
||||
conn_ = nullptr;
|
||||
throw_postgres_error(msg.c_str(), "postgres");
|
||||
return utils::failure(make_error(sql::error_code::OPEN_ERROR, nullptr, conn_, "Failed to connect"));
|
||||
}
|
||||
|
||||
return utils::ok<void>();
|
||||
}
|
||||
|
||||
void postgres_connection::close()
|
||||
{
|
||||
utils::result<void, utils::error> postgres_connection::close() {
|
||||
if (conn_) {
|
||||
PQfinish(conn_);
|
||||
conn_ = nullptr;
|
||||
}
|
||||
|
||||
return utils::ok<void>();
|
||||
}
|
||||
|
||||
bool postgres_connection::is_open()
|
||||
{
|
||||
return conn_ != nullptr;
|
||||
utils::result<bool, utils::error> postgres_connection::is_open() const {
|
||||
return utils::ok(conn_ != nullptr);
|
||||
}
|
||||
|
||||
std::unique_ptr<sql::query_result_impl> postgres_connection::fetch(const std::string &stmt)
|
||||
{
|
||||
PGresult *res = PQexec(conn_, stmt.c_str());
|
||||
utils::result<bool, utils::error> postgres_connection::is_valid() const {
|
||||
return utils::ok(PQstatus(conn_) == CONNECTION_OK);
|
||||
}
|
||||
|
||||
throw_postgres_error(res, conn_, "postgres", stmt);
|
||||
utils::result<utils::version, utils::error> postgres_connection::client_version() const {
|
||||
const auto client_version = PQlibVersion();
|
||||
return utils::ok(utils::version{
|
||||
static_cast<unsigned int>(client_version / 10000),
|
||||
static_cast<unsigned int>((client_version % 10000) / 100),
|
||||
static_cast<unsigned int>(client_version % 100)
|
||||
});
|
||||
}
|
||||
|
||||
std::vector<sql::column_definition> prototype;
|
||||
auto num_col = PQnfields(res);
|
||||
for (int i = 0; i < num_col; ++i) {
|
||||
const char *col_name = PQfname(res, i);
|
||||
auto type = PQftype(res, i);
|
||||
auto size = PQfmod(res, i);
|
||||
prototype.emplace_back(col_name);
|
||||
utils::result<utils::version, utils::error> postgres_connection::server_version() const {
|
||||
const auto server_version = PQserverVersion(conn_);
|
||||
|
||||
if (server_version == 0) {
|
||||
return utils::failure(make_error(sql::error_code::FAILURE, nullptr, conn_, "Failed to get server version"));
|
||||
}
|
||||
return std::move(std::make_unique<sql::query_result_impl>(std::make_unique<postgres_result_reader>(res), std::move(prototype)));
|
||||
|
||||
return utils::ok(utils::version{
|
||||
static_cast<unsigned int>(server_version / 10000),
|
||||
static_cast<unsigned int>((server_version % 10000) / 100),
|
||||
static_cast<unsigned int>(server_version % 100)
|
||||
});
|
||||
}
|
||||
|
||||
std::string postgres_connection::generate_statement_name(const sql::query_context &query)
|
||||
{
|
||||
utils::basic_type oid2type(Oid oid);
|
||||
|
||||
utils::result<std::unique_ptr<sql::query_result_impl>, utils::error> postgres_connection::fetch(const sql::query_context &context) {
|
||||
PGresult *res = PQexec(conn_, context.sql.c_str());
|
||||
|
||||
if (is_result_error(res)) {
|
||||
return utils::failure(make_error(sql::error_code::FETCH_FAILED, res, conn_, "Failed to fetch", context.sql));
|
||||
}
|
||||
|
||||
std::vector<object::attribute_definition> prototype = context.prototype;
|
||||
|
||||
const int num_col = PQnfields(res);
|
||||
if (prototype.size() != static_cast<size_t>(num_col)) {
|
||||
return utils::failure(make_error(sql::error_code::FETCH_FAILED, res, conn_, "Number of received columns doesn't match expected columns.", context.sql));
|
||||
}
|
||||
for (int i = 0; i < num_col; ++i) {
|
||||
if (!prototype.at(i).is_null()) {
|
||||
continue;
|
||||
}
|
||||
const auto type = oid2type(PQftype(res, i));
|
||||
// const char *col_name = PQfname(res, i);
|
||||
// const auto size = PQfmod(res, i);
|
||||
prototype.at(i).type(type);
|
||||
}
|
||||
|
||||
return utils::ok(std::make_unique<sql::query_result_impl>(std::make_unique<postgres_result_reader>(res), prototype));
|
||||
}
|
||||
|
||||
std::string postgres_connection::generate_statement_name(const sql::query_context &query) {
|
||||
std::stringstream name;
|
||||
name << query.table.name << "_" << query.command_name;
|
||||
auto result = postgres_connection::statement_name_map_.find(name.str());
|
||||
@@ -77,71 +122,116 @@ std::string postgres_connection::generate_statement_name(const sql::query_contex
|
||||
return name.str();
|
||||
}
|
||||
|
||||
std::unique_ptr<sql::statement_impl> postgres_connection::prepare(sql::query_context context)
|
||||
{
|
||||
utils::result<std::unique_ptr<sql::statement_impl>, utils::error> postgres_connection::prepare(const sql::query_context &context) {
|
||||
auto statement_name = postgres_connection::generate_statement_name(context);
|
||||
|
||||
PGresult *result = PQprepare(conn_, statement_name.c_str(), context.sql.c_str(), static_cast<int>(context.bind_vars.size()), nullptr);
|
||||
PGresult *result = PQprepare(conn_, statement_name.c_str(), context.sql.c_str(),
|
||||
static_cast<int>(context.bind_vars.size()), nullptr);
|
||||
|
||||
throw_postgres_error(result, conn_, "postgres", context.sql);
|
||||
if (is_result_error(result)) {
|
||||
return utils::failure(make_error(sql::error_code::PREPARE_FAILED, result, conn_, "Failed to prepare", context.sql));
|
||||
}
|
||||
|
||||
return std::make_unique<postgres_statement>(conn_, result, statement_name, std::move(context));
|
||||
std::unique_ptr<sql::statement_impl> s(std::make_unique<postgres_statement>(conn_, result, statement_name, context));
|
||||
return utils::ok(std::move(s));
|
||||
}
|
||||
|
||||
size_t postgres_connection::execute(const std::string &stmt)
|
||||
{
|
||||
utils::result<size_t, utils::error> postgres_connection::execute(const std::string &stmt) {
|
||||
PGresult *res = PQexec(conn_, stmt.c_str());
|
||||
|
||||
throw_postgres_error(res, conn_, "postgres", stmt);
|
||||
if (const auto status = PQresultStatus(res); status != PGRES_COMMAND_OK &&
|
||||
status != PGRES_TUPLES_OK) {
|
||||
return utils::failure(make_error(sql::error_code::FAILURE, res, conn_, "Failed to execute", stmt));
|
||||
}
|
||||
|
||||
const auto affected_rows = sql::to_long_long(PQcmdTuples(res));
|
||||
const auto affected_rows = utils::to<size_t>(PQcmdTuples(res));
|
||||
|
||||
PQclear(res);
|
||||
|
||||
return affected_rows;
|
||||
return utils::ok(static_cast<size_t>(affected_rows));
|
||||
}
|
||||
|
||||
sql::data_type_t string2type(const char *type)
|
||||
{
|
||||
utils::basic_type oid2type(const Oid oid) {
|
||||
switch (oid) {
|
||||
case 16:
|
||||
return utils::basic_type::type_bool;
|
||||
case 17:
|
||||
return utils::basic_type::type_blob;
|
||||
case 18:
|
||||
return utils::basic_type::type_int8;
|
||||
case 21:
|
||||
return utils::basic_type::type_int16;
|
||||
case 23:
|
||||
return utils::basic_type::type_int32;
|
||||
case 20:
|
||||
return utils::basic_type::type_int64;
|
||||
case 25:
|
||||
return utils::basic_type::type_text;
|
||||
case 1043:
|
||||
return utils::basic_type::type_varchar;
|
||||
case 700:
|
||||
return utils::basic_type::type_float;
|
||||
case 701:
|
||||
return utils::basic_type::type_double;
|
||||
case 1082:
|
||||
return utils::basic_type::type_date;
|
||||
case 1114:
|
||||
return utils::basic_type::type_time;
|
||||
default:
|
||||
return utils::basic_type::type_null;
|
||||
}
|
||||
}
|
||||
|
||||
utils::basic_type string2type(const char *type) {
|
||||
if (strcmp(type, "int2") == 0) {
|
||||
return sql::data_type_t::type_short;
|
||||
return utils::basic_type::type_int16;
|
||||
} else if (strcmp(type, "int4") == 0) {
|
||||
return sql::data_type_t::type_int;
|
||||
return utils::basic_type::type_int32;
|
||||
} else if (strcmp(type, "int8") == 0) {
|
||||
return sql::data_type_t::type_long_long;
|
||||
} else if (strncmp(type, "int8", 6) == 0) {
|
||||
return sql::data_type_t::type_long_long;
|
||||
return utils::basic_type::type_int64;
|
||||
} else if (strcmp(type, "bool") == 0) {
|
||||
return utils::basic_type::type_bool;
|
||||
} else if (strcmp(type, "date") == 0) {
|
||||
return sql::data_type_t::type_date;
|
||||
} else if (strncmp(type, "timestamp", 8) == 0) {
|
||||
return sql::data_type_t::type_time;
|
||||
return utils::basic_type::type_date;
|
||||
} else if (strcmp(type, "timestamp") == 0) {
|
||||
return utils::basic_type::type_time;
|
||||
} else if (strcmp(type, "float4") == 0) {
|
||||
return sql::data_type_t::type_float;
|
||||
return utils::basic_type::type_float;
|
||||
} else if (strcmp(type, "float8") == 0) {
|
||||
return sql::data_type_t::type_double;
|
||||
return utils::basic_type::type_double;
|
||||
} else if (strncmp(type, "varchar", 7) == 0) {
|
||||
return sql::data_type_t::type_varchar;
|
||||
} else if (strncmp(type, "character varying", 7) == 0) {
|
||||
return sql::data_type_t::type_varchar;
|
||||
} else if (strncmp(type, "text", 0) == 0) {
|
||||
return sql::data_type_t::type_text;
|
||||
return utils::basic_type::type_varchar;
|
||||
} else if (strcmp(type, "character varying") == 0) {
|
||||
return utils::basic_type::type_varchar;
|
||||
} else if (strcmp(type, "text") == 0) {
|
||||
return utils::basic_type::type_text;
|
||||
} else if (strcmp(type, "bytea") == 0) {
|
||||
return utils::basic_type::type_blob;
|
||||
} else {
|
||||
return sql::data_type_t::type_unknown;
|
||||
return utils::basic_type::type_null;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<sql::column_definition> postgres_connection::describe(const std::string &table)
|
||||
{
|
||||
std::string stmt(
|
||||
"SELECT ordinal_position, column_name, udt_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema='public' AND table_name='" + table + "'");
|
||||
utils::result<std::vector<object::attribute_definition>, utils::error> postgres_connection::describe(const std::string &table) {
|
||||
const std::string stmt(
|
||||
"SELECT ordinal_position, column_name, udt_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema='public' AND table_name='"
|
||||
+ table + "'");
|
||||
|
||||
PGresult *res = PQexec(conn_, stmt.c_str());
|
||||
|
||||
throw_postgres_error(res, conn_, "postgres", stmt);
|
||||
if (is_result_error(res)) {
|
||||
return utils::failure(make_error(sql::error_code::DESCRIBE_FAILED, res, conn_, "Failed to describe", stmt));
|
||||
}
|
||||
|
||||
postgres_result_reader reader(res);
|
||||
std::vector<sql::column_definition> prototype;
|
||||
while (reader.fetch()) {
|
||||
std::vector<object::attribute_definition> prototype;
|
||||
while (auto fetched = reader.fetch()) {
|
||||
if (!fetched.is_ok()) {
|
||||
return utils::failure(fetched.release_error());
|
||||
}
|
||||
if (!*fetched) {
|
||||
break;
|
||||
}
|
||||
char *end = nullptr;
|
||||
// Todo: Handle error
|
||||
auto index = strtoul(reader.column(0), &end, 10) - 1;
|
||||
@@ -150,39 +240,51 @@ std::vector<sql::column_definition> postgres_connection::describe(const std::str
|
||||
// Todo: extract size
|
||||
auto type = (string2type(reader.column(2)));
|
||||
end = nullptr;
|
||||
sql::null_option null_opt{sql::null_option::NULLABLE};
|
||||
object::null_option null_opt{object::null_option::NULLABLE};
|
||||
if (strtoul(reader.column(4), &end, 10) == 0) {
|
||||
null_opt = sql::null_option::NOT_NULL;
|
||||
null_opt = object::null_option::NOT_NULL;
|
||||
}
|
||||
// f.default_value(res->column(4));
|
||||
prototype.emplace_back(name, type, utils::null_attributes, null_opt, index);
|
||||
}
|
||||
|
||||
return std::move(prototype);
|
||||
return utils::ok(prototype);
|
||||
}
|
||||
|
||||
bool postgres_connection::exists(const std::string &schema_name, const std::string &table_name)
|
||||
{
|
||||
std::string stmt("SELECT 1 FROM information_schema.tables WHERE table_schema = '" + schema_name + "' AND table_name = '" + table_name + "'");
|
||||
utils::result<bool, utils::error> postgres_connection::exists(const std::string &schema_name, const std::string &table_name) {
|
||||
const std::string stmt(
|
||||
"SELECT 1 FROM information_schema.tables WHERE table_schema = '" + schema_name + "' AND table_name = '" + table_name
|
||||
+ "'");
|
||||
|
||||
PGresult *res = PQexec(conn_, stmt.c_str());
|
||||
|
||||
throw_postgres_error(res, conn_, "postgres", stmt);
|
||||
if (is_result_error(res)) {
|
||||
return utils::failure(make_error(sql::error_code::TABLE_EXISTS_FAILED, res, conn_, "Failed check if table exists", stmt));
|
||||
}
|
||||
|
||||
return sql::to_long_long(PQcmdTuples(res)) == 1;
|
||||
const auto result = utils::to<size_t>(PQcmdTuples(res));
|
||||
if (!result) {
|
||||
return utils::failure(make_error(sql::error_code::FAILURE, res, conn_, "Failed to convert result value", stmt));
|
||||
}
|
||||
return utils::ok(*result == 1);
|
||||
}
|
||||
|
||||
std::string postgres_connection::to_escaped_string(const utils::blob& value) const
|
||||
{
|
||||
size_t escapedDataLength;
|
||||
unsigned char *escapedData = PQescapeByteaConn(conn_, value.data(), value.size(), &escapedDataLength);
|
||||
|
||||
return {reinterpret_cast<char*>(escapedData), escapedDataLength-1};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extern "C"
|
||||
{
|
||||
MATADOR_POSTGRES_API matador::sql::connection_impl *create_database(const matador::sql::connection_info &info)
|
||||
{
|
||||
extern "C" {
|
||||
MATADOR_POSTGRES_API matador::sql::connection_impl *create_database(const matador::sql::connection_info &info) {
|
||||
return new matador::backends::postgres::postgres_connection(info);
|
||||
}
|
||||
|
||||
MATADOR_POSTGRES_API void destroy_database(matador::sql::connection_impl *db)
|
||||
{
|
||||
MATADOR_POSTGRES_API void destroy_database(matador::sql::connection_impl *db) {
|
||||
delete db;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,20 +2,28 @@
|
||||
|
||||
#include "matador/sql/dialect_builder.hpp"
|
||||
|
||||
#include "matador/utils/basic_types.hpp"
|
||||
|
||||
[[maybe_unused]] const matador::sql::dialect *get_dialect()
|
||||
{
|
||||
using namespace matador::sql;
|
||||
const static dialect d = dialect_builder::builder()
|
||||
.create()
|
||||
.with_placeholder_func([](size_t index) {
|
||||
.with_placeholder_func([](const size_t index) {
|
||||
return "$" + std::to_string(index);
|
||||
})
|
||||
.with_token_replace_map({
|
||||
{dialect::token_t::BEGIN_BINARY_DATA, "E'\\"}
|
||||
{dialect_token::BEGIN_BINARY_DATA, "'\\x"}
|
||||
})
|
||||
.with_data_type_replace_map({
|
||||
{data_type_t::type_blob, "BYTEA"}
|
||||
})
|
||||
{matador::utils::basic_type::type_int8, "SMALLINT"},
|
||||
{matador::utils::basic_type::type_uint8, "SMALLINT"},
|
||||
{matador::utils::basic_type::type_float, "REAL"},
|
||||
{matador::utils::basic_type::type_double, "DOUBLE PRECISION"},
|
||||
{matador::utils::basic_type::type_time, "TIMESTAMP"},
|
||||
{matador::utils::basic_type::type_blob, "BYTEA"}
|
||||
})
|
||||
.with_bool_strings("TRUE", "FALSE")
|
||||
.with_default_schema_name("public")
|
||||
.build();
|
||||
return &d;
|
||||
|
||||
@@ -6,6 +6,30 @@
|
||||
|
||||
namespace matador::backends::postgres {
|
||||
|
||||
utils::error make_error(const sql::error_code ec, const PGresult *res, const PGconn *db, const std::string &msg,
|
||||
const std::string &sql) {
|
||||
utils::error err(ec, msg);
|
||||
err.add_error_info("dbms", "postgres");
|
||||
if (!sql.empty()) {
|
||||
err.add_error_info("sql", sql);
|
||||
}
|
||||
if (res == nullptr) {
|
||||
err.add_error_info("message", PQerrorMessage(db));
|
||||
} else if (const auto status = PQresultStatus(res); status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
|
||||
err.add_error_info("message", PQresultErrorField(res, PG_DIAG_SQLSTATE));
|
||||
}
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
bool is_result_error(const PGresult *res) {
|
||||
if (res == nullptr) {
|
||||
return true;
|
||||
}
|
||||
const auto status = PQresultStatus(res);
|
||||
return status != PGRES_TUPLES_OK && status != PGRES_COMMAND_OK;
|
||||
}
|
||||
|
||||
void throw_postgres_error(const char *what, const std::string &source)
|
||||
{
|
||||
std::stringstream msg;
|
||||
@@ -26,8 +50,9 @@ void throw_postgres_error(PGresult *res, PGconn *db, const std::string &source,
|
||||
std::stringstream msg;
|
||||
msg << "postgres error (" << source << ", " << PQerrorMessage(db) << ": " << sql;
|
||||
throw std::logic_error(msg.str());
|
||||
} else if ((PQresultStatus(res) != PGRES_COMMAND_OK &&
|
||||
PQresultStatus(res) != PGRES_TUPLES_OK)) {
|
||||
}
|
||||
if (const auto status = PQresultStatus(res); status != PGRES_COMMAND_OK &&
|
||||
status != PGRES_TUPLES_OK) {
|
||||
std::stringstream msg;
|
||||
msg << "postgres error (" << source << ", " << PQresultErrorField(res, PG_DIAG_SQLSTATE) << ") " << PQerrorMessage(db) << ": " << sql;
|
||||
throw std::logic_error(msg.str());
|
||||
|
||||
@@ -1,29 +1,32 @@
|
||||
#include "postgres_parameter_binder.h"
|
||||
|
||||
#include "matador/utils/string.hpp"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace matador::backends::postgres {
|
||||
|
||||
namespace detail {
|
||||
|
||||
template < class T >
|
||||
void bind_value(std::vector<std::string> &strings, std::vector<const char*> ¶ms, size_t index, T &x)
|
||||
{
|
||||
strings[index] = std::to_string(x);
|
||||
params[index] = strings[index].c_str();
|
||||
template<class T>
|
||||
void bind_value(postgres_parameter_binder::bind_data &data, const size_t index, const T &x) {
|
||||
data.strings[index] = std::to_string(x);
|
||||
data.values[index] = data.strings[index].c_str();
|
||||
data.lengths[index] = static_cast<int>(data.strings[index].size());
|
||||
data.formats[index] = 0;
|
||||
}
|
||||
|
||||
template <>
|
||||
void bind_value(std::vector<std::string> &strings, std::vector<const char*> ¶ms, size_t index, char &x)
|
||||
{
|
||||
strings[index] = std::to_string(x);
|
||||
params[index] = strings[index].data();
|
||||
}
|
||||
// template<>
|
||||
// void bind_value(postgres_parameter_binder::bind_data &data, size_t index, const char &x) {
|
||||
// data.strings[index] = std::to_string(x);
|
||||
// data.values[index] = data.strings[index].data();
|
||||
// data.formats[index] = 0;
|
||||
// }
|
||||
|
||||
template <>
|
||||
void bind_value(std::vector<std::string> &strings, std::vector<const char*> ¶ms, size_t index, unsigned char &x)
|
||||
{
|
||||
strings[index] = std::to_string(x);
|
||||
params[index] = strings[index].data();
|
||||
}
|
||||
// template<>
|
||||
// void bind_value(postgres_parameter_binder::bind_data &data, size_t index, const unsigned char &x) {
|
||||
// data.strings[index] = std::to_string(x);
|
||||
// data.values[index] = data.strings[index].data();
|
||||
// data.formats[index] = 0;
|
||||
// }
|
||||
|
||||
//template <>
|
||||
//void bind_value(std::vector<std::string> &strings, std::vector<const char*> ¶ms, size_t &index, const matador::date &x)
|
||||
@@ -40,108 +43,111 @@ void bind_value(std::vector<std::string> &strings, std::vector<const char*> &par
|
||||
// params[index] = strings[index].c_str();
|
||||
// ++index;
|
||||
//}
|
||||
|
||||
}
|
||||
|
||||
postgres_parameter_binder::postgres_parameter_binder(size_t size)
|
||||
: strings_(size)
|
||||
, params_(size)
|
||||
postgres_parameter_binder::bind_data::bind_data(const size_t size)
|
||||
: strings(size)
|
||||
, bytes(size)
|
||||
, values(size)
|
||||
, lengths(size)
|
||||
, formats(size)
|
||||
{}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, char i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
postgres_parameter_binder::postgres_parameter_binder(size_t size)
|
||||
: bind_data_(size)
|
||||
{}
|
||||
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const int8_t &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, short i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const int16_t &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, int i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const int32_t &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, long i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const int64_t &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, long long int i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const uint8_t &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, unsigned char i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const uint16_t &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, unsigned short i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const uint32_t &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, unsigned int i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const uint64_t &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, unsigned long i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const bool &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, unsigned long long int i)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, i);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const float &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, bool b)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, b);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const double &x) {
|
||||
detail::bind_value(bind_data_, pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, float d)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, d);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const char *x) {
|
||||
bind_data_.values[pos] = x;
|
||||
bind_data_.lengths[pos] = static_cast<int>(std::strlen(x));
|
||||
bind_data_.formats[pos] = 0;
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, double d)
|
||||
{
|
||||
detail::bind_value(strings_, params_, pos, d);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const char *x, size_t /*size*/) {
|
||||
bind_data_.values[pos] = x;
|
||||
bind_data_.lengths[pos] = static_cast<int>(std::strlen(x));
|
||||
bind_data_.formats[pos] = 0;
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, const char *str)
|
||||
{
|
||||
params_[pos] = str;
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const std::string &x) {
|
||||
bind_data_.values[pos] = x.data();
|
||||
bind_data_.lengths[pos] = static_cast<int>(x.size());
|
||||
bind_data_.formats[pos] = 0;
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, const char *str, size_t size)
|
||||
{
|
||||
params_[pos] = str;
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const std::string &x, size_t /*size*/) {
|
||||
write_value(pos, x);
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, const std::string &str)
|
||||
{
|
||||
strings_[pos] = str;
|
||||
params_[pos] = strings_[pos].c_str();
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const time &/*x*/) {
|
||||
// bind_data_.strings[pos] = utils::to_string(x, "%Y-%m-%d %T.%f");
|
||||
bind_data_.values[pos] = bind_data_.strings[pos].data();
|
||||
bind_data_.lengths[pos] = static_cast<int>(bind_data_.strings[pos].size());
|
||||
bind_data_.formats[pos] = 0;
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, const std::string &str, size_t size)
|
||||
{
|
||||
bind(pos, str);
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const date &/*x*/) {
|
||||
// bind_data_.strings[pos] = utils::to_string(x, utils::date_format::ISO8601);
|
||||
bind_data_.values[pos] = bind_data_.strings[pos].data();
|
||||
bind_data_.lengths[pos] = static_cast<int>(bind_data_.strings[pos].size());
|
||||
bind_data_.formats[pos] = 0;
|
||||
}
|
||||
|
||||
void postgres_parameter_binder::bind(size_t pos, const utils::blob &blob)
|
||||
{
|
||||
params_[pos] = "";
|
||||
void postgres_parameter_binder::write_value(const size_t pos, const utils::blob &x) {
|
||||
bind_data_.bytes[pos] = x;
|
||||
bind_data_.values[pos] = reinterpret_cast<char*>(bind_data_.bytes[pos].data());
|
||||
bind_data_.lengths[pos] = static_cast<int>(bind_data_.bytes[pos].size());
|
||||
bind_data_.formats[pos] = 1;
|
||||
}
|
||||
|
||||
const std::vector<const char *> &postgres_parameter_binder::params() const
|
||||
{
|
||||
return params_;
|
||||
void postgres_parameter_binder::write_value(const size_t /*pos*/, const utils::value &/*x*/, size_t /*size*/) {}
|
||||
|
||||
const postgres_parameter_binder::bind_data &postgres_parameter_binder::params() const {
|
||||
return bind_data_;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "postgres_result_reader.hpp"
|
||||
|
||||
#include "matador/sql/to_value.hpp"
|
||||
#include "matador/utils/convert.hpp"
|
||||
#include "matador/utils/value.hpp"
|
||||
|
||||
namespace matador::backends::postgres {
|
||||
|
||||
@@ -22,14 +23,215 @@ size_t postgres_result_reader::column_count() const
|
||||
return column_count_;
|
||||
}
|
||||
|
||||
const char *postgres_result_reader::column(size_t index) const
|
||||
const char *postgres_result_reader::column( const size_t index) const
|
||||
{
|
||||
return PQgetvalue(result_, static_cast<int>(row_index_), static_cast<int>(index));
|
||||
}
|
||||
|
||||
bool postgres_result_reader::fetch()
|
||||
{
|
||||
return ++row_index_ < row_count_;
|
||||
utils::result<bool, utils::error> postgres_result_reader::fetch() { return utils::ok(++row_index_ < row_count_); }
|
||||
|
||||
size_t postgres_result_reader::start_column_index() const {
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
void postgres_result_reader::unshift() {
|
||||
if (row_index_ > 0) {
|
||||
--row_index_;
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, int8_t &value) {
|
||||
if (auto res = utils::to<int8_t>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, int16_t &value) {
|
||||
if (auto res = utils::to<int16_t>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, int32_t &value) {
|
||||
if (auto res = utils::to<int32_t>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, int64_t &value) {
|
||||
if (auto res = utils::to<int64_t>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, uint8_t &value) {
|
||||
if (auto res = utils::to<uint8_t>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, uint16_t &value) {
|
||||
if (auto res = utils::to<uint16_t>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, uint32_t &value) {
|
||||
if (auto res = utils::to<uint32_t>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, uint64_t &value) {
|
||||
if (auto res = utils::to<uint64_t>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, bool &value) {
|
||||
if (auto res = utils::to<bool>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, float &value) {
|
||||
if (auto res = utils::to<float>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, double &value) {
|
||||
if (auto res = utils::to<double>(column(index)); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, time &/*value*/) {
|
||||
// if (const auto val = column(index); strlen(val) > 0) {
|
||||
// value = time::parse(val, "%Y-%m-%d %T.%f");
|
||||
// }
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, date &/*value*/) {
|
||||
// if (const auto val = column(index); strlen(val) > 0) {
|
||||
// value.set(val, matador::utils::date_format::ISO8601);
|
||||
// }
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, char *value, size_t size) {
|
||||
auto val = column(index);
|
||||
if (const size_t len = strlen(val); len > size) {
|
||||
#ifdef _MSC_VER
|
||||
strncpy_s(value, size, val, len);
|
||||
#else
|
||||
strncpy(value, val, size);
|
||||
#endif
|
||||
value[size-1] = '\n';
|
||||
} else {
|
||||
#ifdef _MSC_VER
|
||||
strcpy_s(value, size, val);
|
||||
#else
|
||||
strcpy(value, val);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, std::string &value) {
|
||||
value.assign(column(index));
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, std::string &value, size_t /*s*/) {
|
||||
value.assign(column(index));
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value( const char* id, const size_t index, utils::blob& value )
|
||||
{
|
||||
const auto *data = reinterpret_cast<const unsigned char*>(column(index));
|
||||
// auto length = PQgetlength(result_, row_index_, static_cast<int>(index));
|
||||
|
||||
size_t length;
|
||||
unsigned char* unescaped = PQunescapeBytea(data, &length);
|
||||
|
||||
value.assign(unescaped, unescaped+length);
|
||||
}
|
||||
|
||||
template <typename Type>
|
||||
void set_value(const char* str, utils::value& value) {
|
||||
if (const auto res = utils::to<Type>(str); res.is_ok()) {
|
||||
value = res.value();
|
||||
}
|
||||
}
|
||||
|
||||
template <>
|
||||
void set_value<utils::blob>(const char* str, utils::value& value) {
|
||||
size_t length;
|
||||
unsigned char* unescaped = PQunescapeBytea(reinterpret_cast<const unsigned char*>(str), &length);
|
||||
|
||||
value = utils::blob(unescaped, unescaped+length);
|
||||
}
|
||||
|
||||
void postgres_result_reader::read_value(const char * /*id*/, const size_t index, utils::value &val, size_t) {
|
||||
switch (val.type()) {
|
||||
case utils::basic_type::type_int8:
|
||||
set_value<int8_t>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_int16:
|
||||
set_value<int16_t>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_int32:
|
||||
set_value<int32_t>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_int64:
|
||||
set_value<int64_t>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_uint8:
|
||||
set_value<uint8_t>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_uint16:
|
||||
set_value<uint16_t>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_uint32:
|
||||
set_value<uint32_t>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_uint64:
|
||||
set_value<uint64_t>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_float:
|
||||
set_value<float>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_double:
|
||||
set_value<double>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_bool:
|
||||
set_value<bool>(column(index), val);
|
||||
break;
|
||||
case utils::basic_type::type_text:
|
||||
case utils::basic_type::type_varchar: {
|
||||
if (const auto *column_value = column(index); column_value == nullptr) {
|
||||
val = std::string{};
|
||||
} else {
|
||||
val = std::string{column_value};
|
||||
}
|
||||
break;
|
||||
}
|
||||
case utils::basic_type::type_time:
|
||||
case utils::basic_type::type_date: {
|
||||
val = std::string{column(index)};
|
||||
break;
|
||||
}
|
||||
case utils::basic_type::type_null: {
|
||||
val = nullptr_t{};
|
||||
break;
|
||||
}
|
||||
case utils::basic_type::type_blob: {
|
||||
set_value<utils::blob>(column(index), val);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
utils::attribute_reader &postgres_result_reader::result_binder() {
|
||||
return empty_binder_;
|
||||
}
|
||||
|
||||
} // namespace matador::backends::postgres
|
||||
|
||||
@@ -12,27 +12,48 @@ postgres_statement::postgres_statement(PGconn *db, PGresult *result, std::string
|
||||
, binder_(query_.bind_vars.size())
|
||||
{}
|
||||
|
||||
size_t postgres_statement::execute()
|
||||
utils::result<size_t, utils::error> postgres_statement::execute()
|
||||
{
|
||||
PGresult *res = PQexecPrepared(db_, name_.c_str(), static_cast<int>(binder_.params().size()), binder_.params().data(), nullptr, nullptr, 0);
|
||||
PGresult *res = PQexecPrepared(db_,
|
||||
name_.c_str(),
|
||||
static_cast<int>(binder_.params().values.size()),
|
||||
binder_.params().values.data(),
|
||||
binder_.params().lengths.data(),
|
||||
binder_.params().formats.data(),
|
||||
0);
|
||||
|
||||
throw_postgres_error(res, db_, "postgres", query_.sql);
|
||||
if (is_result_error(res)) {
|
||||
return utils::failure(make_error(sql::error_code::EXECUTE_FAILED, res, db_, "Failed to execute statement", query_.sql));
|
||||
}
|
||||
|
||||
return std::stoul(PQcmdTuples(res));
|
||||
const auto *tuples = PQcmdTuples(res);
|
||||
if (strlen(tuples) == 0) {
|
||||
return utils::ok(static_cast<size_t>(0));
|
||||
}
|
||||
|
||||
return utils::ok(static_cast<size_t>(std::stoul(tuples)));
|
||||
}
|
||||
|
||||
std::unique_ptr<sql::query_result_impl> postgres_statement::fetch()
|
||||
utils::result<std::unique_ptr<sql::query_result_impl>, utils::error> postgres_statement::fetch()
|
||||
{
|
||||
PGresult *res = PQexecPrepared(db_, name_.c_str(), static_cast<int>(binder_.params().size()), binder_.params().data(), nullptr, nullptr, 0);
|
||||
PGresult *res = PQexecPrepared(db_,
|
||||
name_.c_str(),
|
||||
static_cast<int>(binder_.params().values.size()),
|
||||
binder_.params().values.data(),
|
||||
binder_.params().lengths.data(),
|
||||
binder_.params().formats.data(),
|
||||
0);
|
||||
|
||||
throw_postgres_error(res, db_, "postgres", query_.sql);
|
||||
if (is_result_error(res)) {
|
||||
return utils::failure(make_error(sql::error_code::FETCH_FAILED, res, db_, "Failed to fetch statement", query_.sql));
|
||||
}
|
||||
|
||||
return std::move(std::make_unique<sql::query_result_impl>(std::make_unique<postgres_result_reader>(res), std::move(query_.prototype)));
|
||||
return utils::ok(std::make_unique<sql::query_result_impl>(std::make_unique<postgres_result_reader>(res), query_.prototype));
|
||||
}
|
||||
|
||||
void postgres_statement::reset() {}
|
||||
|
||||
sql::parameter_binder& postgres_statement::binder()
|
||||
utils::attribute_writer& postgres_statement::binder()
|
||||
{
|
||||
return binder_;
|
||||
}
|
||||
|
||||
@@ -1,45 +1,50 @@
|
||||
Include(FetchContent)
|
||||
|
||||
FetchContent_Declare(
|
||||
Catch2
|
||||
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
|
||||
GIT_TAG v3.5.4 # or a later release
|
||||
)
|
||||
|
||||
FetchContent_MakeAvailable(Catch2)
|
||||
CPMAddPackage("gh:catchorg/Catch2@3.7.1")
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${catch2_SOURCE_DIR}/extras)
|
||||
include(CTest)
|
||||
include(Catch)
|
||||
|
||||
set(POSTGRES_CONNECTION_STRING "postgres://test:test123@127.0.0.1:15432/test")
|
||||
set(POSTGRES_CONNECTION_STRING "postgres://test:test123!@127.0.0.1:5432/matador")
|
||||
|
||||
configure_file(Connection.hpp.in ${PROJECT_BINARY_DIR}/backends/postgres/test/connection.hpp @ONLY IMMEDIATE)
|
||||
|
||||
message(STATUS "postgresql connection string: ${POSTGRES_CONNECTION_STRING}")
|
||||
|
||||
set(TEST_SOURCES
|
||||
../../tests/QueryTest.cpp
|
||||
../../tests/ConnectionTest.cpp
|
||||
../../tests/QueryRecordTest.cpp
|
||||
../../tests/StatementTest.cpp
|
||||
../../tests/TypeTraitsTest.cpp
|
||||
../../tests/StatementCacheTest.cpp
|
||||
../../tests/SessionTest.cpp)
|
||||
../../../test/models/coordinate.hpp
|
||||
../../../test/models/location.hpp
|
||||
../../../test/models/types.hpp
|
||||
../../../test/backends/ColorEnumTraits.cpp
|
||||
../../../test/backends/ColorEnumTraits.hpp
|
||||
../../../test/backends/ConnectionTest.cpp
|
||||
../../../test/backends/QueryBasicTest.cpp
|
||||
../../../test/backends/QueryFixture.cpp
|
||||
../../../test/backends/QueryFixture.hpp
|
||||
../../../test/backends/QueryRecordTest.cpp
|
||||
../../../test/backends/QueryStatementTests.cpp
|
||||
../../../test/backends/QueryTest.cpp
|
||||
../../../test/backends/SessionFixture.cpp
|
||||
../../../test/backends/SessionFixture.hpp
|
||||
../../../test/backends/SessionTest.cpp
|
||||
../../../test/backends/StatementCacheTest.cpp
|
||||
../../../test/backends/StatementTest.cpp
|
||||
../../../test/backends/TypeTraitsTest.cpp
|
||||
)
|
||||
|
||||
set(LIBRARY_TEST_TARGET postgres_tests)
|
||||
set(LIBRARY_TEST_TARGET PostgresTests)
|
||||
|
||||
add_executable(${LIBRARY_TEST_TARGET} ${TEST_SOURCES})
|
||||
|
||||
target_link_libraries(${LIBRARY_TEST_TARGET} PRIVATE
|
||||
Catch2::Catch2WithMain
|
||||
matador
|
||||
matador-core
|
||||
matador-orm
|
||||
${CMAKE_DL_LIBS}
|
||||
${PostgreSQL_LIBRARY})
|
||||
|
||||
add_dependencies(${LIBRARY_TEST_TARGET} matador-postgres)
|
||||
|
||||
target_include_directories(${LIBRARY_TEST_TARGET}
|
||||
PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>/include
|
||||
PRIVATE $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>/test
|
||||
PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
catch_discover_tests(${LIBRARY_TEST_TARGET} TEST_SUFFIX " (PostgreSQL)")
|
||||
#catch_discover_tests(${LIBRARY_TEST_TARGET} TEST_SUFFIX " (PostgreSQL)")
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
set(HEADER
|
||||
include/sqlite_connection.hpp
|
||||
include/sqlite_error.hpp
|
||||
include/sqlite_dialect.hpp
|
||||
include/sqlite_result_reader.hpp
|
||||
include/sqlite_statement.hpp
|
||||
include/sqlite_parameter_binder.h
|
||||
include/sqlite_prepared_result_reader.hpp
|
||||
)
|
||||
|
||||
set(SOURCES
|
||||
src/sqlite_connection.cpp
|
||||
src/sqlite_error.cpp
|
||||
src/sqlite_dialect.cpp
|
||||
src/sqlite_result_reader.cpp
|
||||
src/sqlite_statement.cpp
|
||||
src/sqlite_parameter_binder.cpp
|
||||
src/sqlite_prepared_result_reader.cpp
|
||||
)
|
||||
|
||||
set(LIBRARY_TARGET matador-sqlite)
|
||||
|
||||
add_subdirectory(test)
|
||||
|
||||
add_library(${LIBRARY_TARGET} MODULE ${SOURCES} ${HEADER})
|
||||
|
||||
set_target_properties(${LIBRARY_TARGET}
|
||||
PROPERTIES
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/backends"
|
||||
)
|
||||
|
||||
target_include_directories(${LIBRARY_TARGET} PRIVATE
|
||||
${PROJECT_SOURCE_DIR}/include
|
||||
${PROJECT_SOURCE_DIR}/backends/sqlite/include
|
||||
${SQLite3_INCLUDE_DIRS})
|
||||
|
||||
target_link_libraries(${LIBRARY_TARGET} matador ${SQLite3_LIBRARIES})
|
||||
@@ -1,65 +0,0 @@
|
||||
#ifndef QUERY_SQLITE_CONNECTION_HPP
|
||||
#define QUERY_SQLITE_CONNECTION_HPP
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#ifdef matador_sqlite_EXPORTS
|
||||
#define MATADOR_SQLITE_API __declspec(dllexport)
|
||||
#else
|
||||
#define MATADOR_SQLITE_API __declspec(dllimport)
|
||||
#endif
|
||||
#pragma warning(disable: 4355)
|
||||
#else
|
||||
#define MATADOR_SQLITE_API
|
||||
#endif
|
||||
|
||||
#include "matador/sql/connection_impl.hpp"
|
||||
|
||||
#include "sqlite_result_reader.hpp"
|
||||
|
||||
#include <sqlite3.h>
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
class sqlite_connection : public matador::sql::connection_impl
|
||||
{
|
||||
public:
|
||||
explicit sqlite_connection(const sql::connection_info &info);
|
||||
void open() override;
|
||||
void close() override;
|
||||
bool is_open() override;
|
||||
|
||||
std::unique_ptr<sql::query_result_impl> fetch(const std::string &stmt) override;
|
||||
std::unique_ptr<sql::statement_impl> prepare(sql::query_context query) override;
|
||||
|
||||
size_t execute(const std::string &stmt) override;
|
||||
|
||||
std::vector<sql::column_definition> describe(const std::string& table) override;
|
||||
|
||||
bool exists(const std::string &schema_name, const std::string &table_name) override;
|
||||
|
||||
private:
|
||||
struct fetch_context
|
||||
{
|
||||
std::vector<sql::column_definition> prototype;
|
||||
sqlite_result_reader::rows rows;
|
||||
};
|
||||
|
||||
private:
|
||||
static int parse_result(void* param, int column_count, char** values, char** columns);
|
||||
|
||||
fetch_context fetch_internal(const std::string &stmt);
|
||||
|
||||
private:
|
||||
sqlite3 *db_{};
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
extern "C"
|
||||
{
|
||||
MATADOR_SQLITE_API matador::sql::connection_impl* create_database(const matador::sql::connection_info &info);
|
||||
|
||||
MATADOR_SQLITE_API void destroy_database(matador::sql::connection_impl *db);
|
||||
}
|
||||
|
||||
#endif //QUERY_SQLITE_CONNECTION_HPP
|
||||
@@ -1,19 +0,0 @@
|
||||
#ifndef QUERY_SQLITE_DIALECT_HPP
|
||||
#define QUERY_SQLITE_DIALECT_HPP
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#ifdef matador_sqlite_EXPORTS
|
||||
#define MATADOR_SQLITE_API __declspec(dllexport)
|
||||
#else
|
||||
#define MATADOR_SQLITE_API __declspec(dllimport)
|
||||
#endif
|
||||
#pragma warning(disable: 4355)
|
||||
#else
|
||||
#define MATADOR_SQLITE_API
|
||||
#endif
|
||||
|
||||
#include "matador/sql/dialect.hpp"
|
||||
|
||||
extern "C" [[maybe_unused]] MATADOR_SQLITE_API const matador::sql::dialect* get_dialect();
|
||||
|
||||
#endif //QUERY_SQLITE_DIALECT_HPP
|
||||
@@ -1,15 +0,0 @@
|
||||
#ifndef QUERY_SQLITE_ERROR_HPP
|
||||
#define QUERY_SQLITE_ERROR_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
struct sqlite3;
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
void throw_sqlite_error(int ec, sqlite3 *db, const std::string &source);
|
||||
void throw_sqlite_error(int ec, sqlite3 *db, const std::string &source, const std::string &sql);
|
||||
|
||||
}
|
||||
|
||||
#endif //QUERY_SQLITE_ERROR_HPP
|
||||
@@ -1,44 +0,0 @@
|
||||
#ifndef QUERY_SQLITE_PARAMETER_BINDER_H
|
||||
#define QUERY_SQLITE_PARAMETER_BINDER_H
|
||||
|
||||
#include "matador/sql/parameter_binder.hpp"
|
||||
|
||||
#include <sqlite3.h>
|
||||
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
class sqlite_parameter_binder final : public sql::parameter_binder
|
||||
{
|
||||
public:
|
||||
explicit sqlite_parameter_binder(sqlite3 *db, sqlite3_stmt *stmt);
|
||||
|
||||
void bind(size_t pos, char i) override;
|
||||
void bind(size_t pos, short i) override;
|
||||
void bind(size_t pos, int i) override;
|
||||
void bind(size_t pos, long i) override;
|
||||
void bind(size_t pos, long long int i) override;
|
||||
void bind(size_t pos, unsigned char i) override;
|
||||
void bind(size_t pos, unsigned short i) override;
|
||||
void bind(size_t pos, unsigned int i) override;
|
||||
void bind(size_t pos, unsigned long i) override;
|
||||
void bind(size_t pos, unsigned long long int i) override;
|
||||
void bind(size_t pos, bool b) override;
|
||||
void bind(size_t pos, float d) override;
|
||||
void bind(size_t pos, double d) override;
|
||||
void bind(size_t pos, const char *string) override;
|
||||
void bind(size_t pos, const char *str, size_t size) override;
|
||||
void bind(size_t pos, const std::string &str) override;
|
||||
void bind(size_t pos, const std::string &str, size_t size) override;
|
||||
void bind(size_t pos, const utils::blob &blob) override;
|
||||
private:
|
||||
sqlite3 *db_{nullptr};
|
||||
sqlite3_stmt *stmt_{nullptr};
|
||||
|
||||
std::vector<std::shared_ptr<std::string> > host_strings_;
|
||||
};
|
||||
}
|
||||
|
||||
#endif //QUERY_SQLITE_PARAMETER_BINDER_H
|
||||
@@ -1,42 +0,0 @@
|
||||
#ifndef QUERY_SQLITE_PREPARED_RESULT_READER_HPP
|
||||
#define QUERY_SQLITE_PREPARED_RESULT_READER_HPP
|
||||
|
||||
#include "matador/sql/query_result_reader.hpp"
|
||||
|
||||
#include <sqlite3.h>
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
class sqlite_prepared_result_reader final : public sql::query_result_reader
|
||||
{
|
||||
public:
|
||||
sqlite_prepared_result_reader(sqlite3 *db, sqlite3_stmt *stmt);
|
||||
|
||||
[[nodiscard]] size_t column_count() const override;
|
||||
[[nodiscard]] const char *column(size_t index) const override;
|
||||
bool fetch() override;
|
||||
|
||||
void read_value(const char *id, size_t index, char &value) override;
|
||||
void read_value(const char *id, size_t index, short &value) override;
|
||||
void read_value(const char *id, size_t index, int &value) override;
|
||||
void read_value(const char *id, size_t index, long &value) override;
|
||||
void read_value(const char *id, size_t index, long long int &value) override;
|
||||
void read_value(const char *id, size_t index, unsigned char &value) override;
|
||||
void read_value(const char *id, size_t index, unsigned short &value) override;
|
||||
void read_value(const char *id, size_t index, unsigned int &value) override;
|
||||
void read_value(const char *id, size_t index, unsigned long &value) override;
|
||||
void read_value(const char *id, size_t index, unsigned long long int &value) override;
|
||||
void read_value(const char *id, size_t index, bool &value) override;
|
||||
void read_value(const char *id, size_t index, float &value) override;
|
||||
void read_value(const char *id, size_t index, double &value) override;
|
||||
void read_value(const char *id, size_t index, char *value, size_t s) override;
|
||||
void read_value(const char *id, size_t index, std::string &value) override;
|
||||
void read_value(const char *id, size_t index, std::string &value, size_t s) override;
|
||||
void read_value(const char *id, size_t index, sql::value &val, size_t size) override;
|
||||
|
||||
private:
|
||||
sqlite3 *db_{nullptr};
|
||||
sqlite3_stmt *stmt_{nullptr};
|
||||
};
|
||||
}
|
||||
#endif //QUERY_SQLITE_PREPARED_RESULT_READER_HPP
|
||||
@@ -1,33 +0,0 @@
|
||||
#ifndef QUERY_SQLITE_RESULT_READER_HPP
|
||||
#define QUERY_SQLITE_RESULT_READER_HPP
|
||||
|
||||
#include "matador/sql/query_result_reader.hpp"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
class sqlite_result_reader final : public sql::query_result_reader
|
||||
{
|
||||
public:
|
||||
using columns = std::vector<char*>;
|
||||
using rows = std::vector<columns>;
|
||||
|
||||
public:
|
||||
sqlite_result_reader(rows result, size_t column_count);
|
||||
~sqlite_result_reader() override;
|
||||
|
||||
[[nodiscard]] size_t column_count() const override;
|
||||
|
||||
[[nodiscard]] const char* column(size_t index) const override;
|
||||
[[nodiscard]] bool fetch() override;
|
||||
|
||||
private:
|
||||
rows result_;
|
||||
long long row_index_ = -1;
|
||||
size_t column_count_{};
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //QUERY_SQLITE_RESULT_READER_HPP
|
||||
@@ -1,31 +0,0 @@
|
||||
#ifndef QUERY_SQLITE_STATEMENT_HPP
|
||||
#define QUERY_SQLITE_STATEMENT_HPP
|
||||
|
||||
#include "matador/sql/statement_impl.hpp"
|
||||
|
||||
#include "sqlite_parameter_binder.h"
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
class sqlite_statement final : public sql::statement_impl
|
||||
{
|
||||
public:
|
||||
sqlite_statement(sqlite3 *db, sqlite3_stmt *stmt, const sql::query_context &query);
|
||||
~sqlite_statement();
|
||||
|
||||
size_t execute() override;
|
||||
std::unique_ptr<sql::query_result_impl> fetch() override;
|
||||
void reset() override;
|
||||
protected:
|
||||
sql::parameter_binder& binder() override;
|
||||
|
||||
private:
|
||||
sqlite3 *db_{nullptr};
|
||||
sqlite3_stmt *stmt_{nullptr};
|
||||
|
||||
sqlite_parameter_binder binder_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //QUERY_SQLITE_STATEMENT_HPP
|
||||
@@ -1,202 +0,0 @@
|
||||
#include "sqlite_connection.hpp"
|
||||
#include "sqlite_error.hpp"
|
||||
#include "sqlite_result_reader.hpp"
|
||||
#include "sqlite_statement.hpp"
|
||||
|
||||
#include "matador/sql/record.hpp"
|
||||
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
sqlite_connection::sqlite_connection(const sql::connection_info &info)
|
||||
: connection_impl(info) {
|
||||
}
|
||||
|
||||
void sqlite_connection::open()
|
||||
{
|
||||
if (is_open()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto ret = sqlite3_open(info().database.c_str(), &db_);
|
||||
|
||||
if (ret != SQLITE_OK) {
|
||||
throw_sqlite_error(ret, db_, "open");
|
||||
}
|
||||
}
|
||||
|
||||
void sqlite_connection::close()
|
||||
{
|
||||
int ret = sqlite3_close(db_);
|
||||
|
||||
throw_sqlite_error(ret, db_, "close");
|
||||
|
||||
db_ = nullptr;
|
||||
}
|
||||
|
||||
bool sqlite_connection::is_open()
|
||||
{
|
||||
return db_ != nullptr;
|
||||
}
|
||||
|
||||
int sqlite_connection::parse_result(void* param, int column_count, char** values, char** columns)
|
||||
{
|
||||
auto *context = static_cast<fetch_context*>(param);
|
||||
|
||||
sqlite_result_reader::columns column;
|
||||
for(int i = 0; i < column_count; ++i) {
|
||||
// copy and store column data;
|
||||
if (values[i] == nullptr) {
|
||||
auto val = new char[1];
|
||||
val[0] = '\0';
|
||||
column.push_back(val);
|
||||
} else {
|
||||
size_t size = strlen(values[i]);
|
||||
auto val = new char[size + 1];
|
||||
std::memcpy(val, values[i], size);
|
||||
val[size] = '\0';
|
||||
column.push_back(val);
|
||||
}
|
||||
}
|
||||
context->rows.emplace_back(column);
|
||||
|
||||
if (context->prototype.empty()) {
|
||||
for(int i = 0; i < column_count; ++i) {
|
||||
context->prototype.emplace_back(columns[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
sqlite_connection::fetch_context sqlite_connection::fetch_internal(const std::string &stmt)
|
||||
{
|
||||
fetch_context context;
|
||||
char *errmsg = nullptr;
|
||||
const int ret = sqlite3_exec(db_, stmt.c_str(), parse_result, &context, &errmsg);
|
||||
|
||||
throw_sqlite_error(ret, db_, "sqlite", stmt);
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
size_t sqlite_connection::execute(const std::string &stmt)
|
||||
{
|
||||
char *errmsg = nullptr;
|
||||
int ret = sqlite3_exec(db_, stmt.c_str(), nullptr, nullptr, &errmsg);
|
||||
|
||||
throw_sqlite_error(ret, db_, "sqlite", stmt);
|
||||
|
||||
return sqlite3_changes(db_);
|
||||
}
|
||||
|
||||
std::unique_ptr<sql::query_result_impl> sqlite_connection::fetch(const std::string &stmt)
|
||||
{
|
||||
auto context = fetch_internal(stmt);
|
||||
|
||||
return std::move(std::make_unique<sql::query_result_impl>(std::make_unique<sqlite_result_reader>(std::move(context.rows), context.prototype.size()), std::move(context.prototype)));
|
||||
}
|
||||
|
||||
std::unique_ptr<sql::statement_impl> sqlite_connection::prepare(sql::query_context query)
|
||||
{
|
||||
sqlite3_stmt *stmt{};
|
||||
int ret = sqlite3_prepare_v2(db_, query.sql.c_str(), static_cast<int>(query.sql.size()), &stmt, nullptr);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_prepare_v2", query.sql);
|
||||
|
||||
return std::make_unique<sqlite_statement>(db_, stmt, query);
|
||||
}
|
||||
|
||||
sql::data_type_t string2type(const char *type)
|
||||
{
|
||||
if (strncmp(type, "INTEGER", 7) == 0) {
|
||||
return sql::data_type_t::type_int;
|
||||
} else if (strncmp(type, "TINYINT", 7) == 0) {
|
||||
return sql::data_type_t::type_char;
|
||||
} else if (strncmp(type, "SMALLINT", 8) == 0) {
|
||||
return sql::data_type_t::type_short;
|
||||
} else if (strncmp(type, "BIGINT", 6) == 0) {
|
||||
return sql::data_type_t::type_long_long;
|
||||
} else if (strcmp(type, "BOOLEAN") == 0) {
|
||||
return sql::data_type_t::type_bool;
|
||||
} else if (strcmp(type, "REAL") == 0) {
|
||||
return sql::data_type_t::type_double;
|
||||
} else if (strcmp(type, "FLOAT") == 0) {
|
||||
return sql::data_type_t::type_float;
|
||||
} else if (strcmp(type, "DOUBLE") == 0) {
|
||||
return sql::data_type_t::type_double;
|
||||
} else if (strcmp(type, "BLOB") == 0) {
|
||||
return sql::data_type_t::type_blob;
|
||||
} else if (strcmp(type, "NULL") == 0) {
|
||||
return sql::data_type_t::type_null;
|
||||
} else if (strncmp(type, "VARCHAR", 7) == 0) {
|
||||
return sql::data_type_t::type_varchar;
|
||||
} else if (strcmp(type, "DATE") == 0) {
|
||||
return sql::data_type_t::type_date;
|
||||
} else if (strcmp(type, "DATETIME") == 0) {
|
||||
return sql::data_type_t::type_time;
|
||||
} else if (strcmp(type, "TEXT") == 0) {
|
||||
return sql::data_type_t::type_text;
|
||||
} else {
|
||||
return sql::data_type_t::type_unknown;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<sql::column_definition> sqlite_connection::describe(const std::string& table)
|
||||
{
|
||||
const auto result = fetch_internal("PRAGMA table_info(" + table + ")");
|
||||
|
||||
sqlite_result_reader reader(result.rows, result.prototype.size());
|
||||
std::vector<sql::column_definition> prototype;
|
||||
while (reader.fetch()) {
|
||||
char *end = nullptr;
|
||||
// Todo: add index to column
|
||||
auto index = strtoul(reader.column(0), &end, 10);
|
||||
std::string name = reader.column(1);
|
||||
|
||||
auto type = (string2type(reader.column(2)));
|
||||
end = nullptr;
|
||||
sql::null_option null_opt{sql::null_option::NULLABLE};
|
||||
if (strtoul(reader.column(3), &end, 10) == 0) {
|
||||
null_opt = sql::null_option::NOT_NULL;
|
||||
}
|
||||
// f.default_value(res->column(4));
|
||||
prototype.emplace_back(name, type, utils::null_attributes, null_opt, index);
|
||||
}
|
||||
|
||||
return std::move(prototype);
|
||||
}
|
||||
|
||||
bool sqlite_connection::exists(const std::string &schema_name, const std::string &table_name)
|
||||
{
|
||||
const auto result = fetch_internal("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND tbl_name='" + table_name + "' LIMIT 1");
|
||||
sqlite_result_reader reader(result.rows, result.prototype.size());
|
||||
|
||||
if (!reader.fetch()) {
|
||||
// Todo: throw an exception?
|
||||
return false;
|
||||
}
|
||||
|
||||
int v{};
|
||||
reader.read_value(nullptr, 0, v);
|
||||
|
||||
return v == 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extern "C"
|
||||
{
|
||||
MATADOR_SQLITE_API matador::sql::connection_impl *create_database(const matador::sql::connection_info &info)
|
||||
{
|
||||
return new matador::backends::sqlite::sqlite_connection(info);
|
||||
}
|
||||
|
||||
MATADOR_SQLITE_API void destroy_database(matador::sql::connection_impl *db)
|
||||
{
|
||||
delete db;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#include "sqlite_dialect.hpp"
|
||||
|
||||
#include "matador/sql/dialect_builder.hpp"
|
||||
|
||||
[[maybe_unused]] const matador::sql::dialect *get_dialect()
|
||||
{
|
||||
using namespace matador::sql;
|
||||
const static dialect d = dialect_builder::builder()
|
||||
.create()
|
||||
.with_token_replace_map({
|
||||
{dialect::token_t::BEGIN, "BEGIN TRANSACTION"},
|
||||
{dialect::token_t::COMMIT, "COMMIT TRANSACTION"},
|
||||
{dialect::token_t::ROLLBACK, "ROLLBACK TRANSACTION"}
|
||||
})
|
||||
.with_default_schema_name("main")
|
||||
.build();
|
||||
|
||||
return &d;
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
#include "sqlite_error.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
#include <sstream>
|
||||
|
||||
#include <sqlite3.h>
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
void throw_sqlite_error(int ec, sqlite3 *db, const std::string &source)
|
||||
{
|
||||
if (ec != SQLITE_OK && ec != SQLITE_DONE) {
|
||||
std::stringstream msg;
|
||||
msg << "sqlite error (" << source << "): " << sqlite3_errmsg(db);
|
||||
throw std::logic_error(msg.str());
|
||||
}
|
||||
}
|
||||
|
||||
void throw_sqlite_error(int ec, sqlite3 *db, const std::string &source, const std::string &sql)
|
||||
{
|
||||
if (ec != SQLITE_OK&& ec != SQLITE_DONE) {
|
||||
std::stringstream msg;
|
||||
msg << "sqlite error (" << source << ", sql: " << sql << "): " << sqlite3_errmsg(db);
|
||||
throw std::logic_error(msg.str());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
#include "sqlite_parameter_binder.h"
|
||||
#include "sqlite_error.hpp"
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
sqlite_parameter_binder::sqlite_parameter_binder(sqlite3 *db, sqlite3_stmt *stmt)
|
||||
: db_(db)
|
||||
, stmt_(stmt)
|
||||
{}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, char i)
|
||||
{
|
||||
int ret = sqlite3_bind_int(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, short i)
|
||||
{
|
||||
int ret = sqlite3_bind_int(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, int i)
|
||||
{
|
||||
int ret = sqlite3_bind_int(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, long i)
|
||||
{
|
||||
int ret = sqlite3_bind_int(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, long long int i)
|
||||
{
|
||||
int ret = sqlite3_bind_int64(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, unsigned char i)
|
||||
{
|
||||
int ret = sqlite3_bind_int(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, unsigned short i)
|
||||
{
|
||||
int ret = sqlite3_bind_int(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, unsigned int i)
|
||||
{
|
||||
int ret = sqlite3_bind_int64(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, unsigned long i)
|
||||
{
|
||||
int ret = sqlite3_bind_int64(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, unsigned long long int i)
|
||||
{
|
||||
int ret = sqlite3_bind_int64(stmt_, static_cast<int>(++pos), i);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, bool b)
|
||||
{
|
||||
int ret = sqlite3_bind_int(stmt_, static_cast<int>(++pos), b);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, float d)
|
||||
{
|
||||
int ret = sqlite3_bind_double(stmt_, static_cast<int>(++pos), d);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, double d)
|
||||
{
|
||||
int ret = sqlite3_bind_double(stmt_, static_cast<int>(++pos), d);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_int");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, const char *str)
|
||||
{
|
||||
int ret = sqlite3_bind_text(stmt_, static_cast<int>(++pos), str, static_cast<int>(strlen(str)), nullptr);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_text");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, const char *x, size_t size)
|
||||
{
|
||||
auto len = strlen(x);
|
||||
size = (len > size) ? size : len;
|
||||
int ret = sqlite3_bind_text(stmt_, static_cast<int>(++pos), x, static_cast<int>(size), nullptr);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_text");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, const std::string &str)
|
||||
{
|
||||
int ret = sqlite3_bind_text(stmt_, static_cast<int>(++pos), str.c_str(), static_cast<int>(str.size()), nullptr);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_text");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, const std::string &x, size_t size)
|
||||
{
|
||||
auto len = x.size();
|
||||
if (size == 0) {
|
||||
size = len;
|
||||
} else {
|
||||
size = (len > size) ? size : len;
|
||||
}
|
||||
int ret = sqlite3_bind_text(stmt_, static_cast<int>(++pos), x.data(), static_cast<int>(size), nullptr);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_bind_text");
|
||||
}
|
||||
|
||||
void sqlite_parameter_binder::bind(size_t pos, const utils::blob &blob)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
#include "sqlite_prepared_result_reader.hpp"
|
||||
#include "sqlite_error.hpp"
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
sqlite_prepared_result_reader::sqlite_prepared_result_reader(sqlite3 *db, sqlite3_stmt *stmt)
|
||||
: db_(db)
|
||||
, stmt_(stmt)
|
||||
{}
|
||||
|
||||
size_t sqlite_prepared_result_reader::column_count() const
|
||||
{
|
||||
return sqlite3_column_count(stmt_);
|
||||
}
|
||||
|
||||
const char *sqlite_prepared_result_reader::column(size_t index) const
|
||||
{
|
||||
return reinterpret_cast<const char*>(sqlite3_column_text(stmt_, static_cast<int>(index)));
|
||||
}
|
||||
|
||||
bool sqlite_prepared_result_reader::fetch()
|
||||
{
|
||||
int ret = sqlite3_step(stmt_);
|
||||
if (ret != SQLITE_ROW) {
|
||||
throw_sqlite_error(ret, db_, "sqlite3_step");
|
||||
}
|
||||
return ret != SQLITE_DONE;
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, char &value)
|
||||
{
|
||||
value = static_cast<char>(sqlite3_column_int(stmt_, static_cast<int>(index)));
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, short &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, int &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, long &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, long long int &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, unsigned char &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, unsigned short &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, unsigned int &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, unsigned long &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, unsigned long long int &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, bool &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, float &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, double &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, char *value, size_t s)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value, s);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, std::string &value)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, std::string &value, size_t s)
|
||||
{
|
||||
query_result_reader::read_value(id, index, value, s);
|
||||
}
|
||||
|
||||
void sqlite_prepared_result_reader::read_value(const char *id, size_t index, sql::value &val, size_t size)
|
||||
{
|
||||
query_result_reader::read_value(id, index, val, size);
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
#include "sqlite_result_reader.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
|
||||
sqlite_result_reader::sqlite_result_reader(sqlite_result_reader::rows result, size_t column_count)
|
||||
: result_(std::move(result))
|
||||
, column_count_(column_count) {}
|
||||
|
||||
sqlite_result_reader::~sqlite_result_reader()
|
||||
{
|
||||
std::for_each(result_.begin(), result_.end(), [](rows ::value_type& row) {
|
||||
std::for_each(row.begin(), row.end(), [](const char *val) {
|
||||
delete [] val;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
size_t sqlite_result_reader::column_count() const
|
||||
{
|
||||
return column_count_;
|
||||
}
|
||||
|
||||
const char* sqlite_result_reader::column(size_t index) const
|
||||
{
|
||||
return result_[row_index_][index];
|
||||
}
|
||||
|
||||
bool sqlite_result_reader::fetch()
|
||||
{
|
||||
return ++row_index_ < result_.size();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
#include "sqlite_statement.hpp"
|
||||
#include "sqlite_prepared_result_reader.hpp"
|
||||
#include "sqlite_error.hpp"
|
||||
|
||||
namespace matador::backends::sqlite {
|
||||
sqlite_statement::sqlite_statement(sqlite3 *db, sqlite3_stmt *stmt, const sql::query_context &query)
|
||||
: statement_impl(query)
|
||||
, db_(db)
|
||||
, stmt_(stmt)
|
||||
, binder_(db, stmt)
|
||||
{}
|
||||
|
||||
sqlite_statement::~sqlite_statement()
|
||||
{
|
||||
sqlite3_finalize(stmt_);
|
||||
}
|
||||
|
||||
size_t sqlite_statement::execute()
|
||||
{
|
||||
// get next row
|
||||
int ret = sqlite3_reset(stmt_);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_reset");
|
||||
if (ret = sqlite3_step(stmt_); ret != SQLITE_DONE) {
|
||||
throw_sqlite_error(ret, db_, "sqlite3_step");
|
||||
}
|
||||
|
||||
return sqlite3_changes(db_);
|
||||
}
|
||||
|
||||
std::unique_ptr<sql::query_result_impl> sqlite_statement::fetch()
|
||||
{
|
||||
int ret = sqlite3_reset(stmt_);
|
||||
throw_sqlite_error(ret, db_, "sqlite3_reset");
|
||||
|
||||
auto reader = std::make_unique<sqlite_prepared_result_reader>(db_, stmt_);
|
||||
return std::move(std::make_unique<sql::query_result_impl>(std::move(reader), query_.prototype));
|
||||
}
|
||||
|
||||
void sqlite_statement::reset()
|
||||
{
|
||||
if (stmt_) {
|
||||
sqlite3_reset(stmt_);
|
||||
sqlite3_clear_bindings(stmt_);
|
||||
}
|
||||
}
|
||||
|
||||
sql::parameter_binder& sqlite_statement::binder()
|
||||
{
|
||||
return binder_;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
Include(FetchContent)
|
||||
|
||||
FetchContent_Declare(
|
||||
Catch2
|
||||
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
|
||||
GIT_TAG v3.5.4 # or a later release
|
||||
)
|
||||
|
||||
FetchContent_MakeAvailable(Catch2)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${catch2_SOURCE_DIR}/extras)
|
||||
include(CTest)
|
||||
include(Catch)
|
||||
|
||||
set(SQLITE_CONNECTION_STRING "sqlite://test.db")
|
||||
|
||||
configure_file(Connection.hpp.in ${PROJECT_BINARY_DIR}/backends/sqlite/test/connection.hpp @ONLY IMMEDIATE)
|
||||
|
||||
message(STATUS "sqlite connection string: ${SQLITE_CONNECTION_STRING}")
|
||||
|
||||
set(TEST_SOURCES
|
||||
../../tests/QueryTest.cpp
|
||||
../../tests/QueryTest.cpp
|
||||
../../tests/ConnectionTest.cpp
|
||||
../../tests/QueryRecordTest.cpp
|
||||
../../tests/StatementTest.cpp
|
||||
../../tests/TypeTraitsTest.cpp
|
||||
../../tests/StatementCacheTest.cpp
|
||||
../../tests/SessionTest.cpp)
|
||||
|
||||
set(LIBRARY_TEST_TARGET sqlite_tests)
|
||||
|
||||
add_executable(${LIBRARY_TEST_TARGET} ${TEST_SOURCES})
|
||||
|
||||
target_link_libraries(${LIBRARY_TEST_TARGET} PRIVATE
|
||||
Catch2::Catch2WithMain
|
||||
matador
|
||||
${CMAKE_DL_LIBS}
|
||||
${SQLite3_LIBRARY})
|
||||
|
||||
target_include_directories(${LIBRARY_TEST_TARGET}
|
||||
PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>/include
|
||||
PRIVATE $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>/test
|
||||
PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
catch_discover_tests(${LIBRARY_TEST_TARGET} TEST_SUFFIX " (SQLite3)")
|
||||
@@ -1,8 +0,0 @@
|
||||
#ifndef SQLITE_CONNECTION_HPP
|
||||
#define SQLITE_CONNECTION_HPP
|
||||
|
||||
namespace matador::test::connection {
|
||||
const char* const dns = "@SQLITE_CONNECTION_STRING@";
|
||||
}
|
||||
|
||||
#endif /*SQLITE_CONNECTION_HPP*/
|
||||
@@ -1,19 +0,0 @@
|
||||
#include "catch2/catch_test_macros.hpp"
|
||||
|
||||
#include "matador/sql/connection.hpp"
|
||||
|
||||
#include "connection.hpp"
|
||||
|
||||
using namespace matador::sql;
|
||||
|
||||
TEST_CASE("Create connection test", "[connection]") {
|
||||
|
||||
connection c(matador::test::connection::dns);
|
||||
REQUIRE(!c.is_open());
|
||||
|
||||
c.open();
|
||||
REQUIRE(c.is_open());
|
||||
|
||||
c.close();
|
||||
REQUIRE(!c.is_open());
|
||||
}
|
||||
@@ -1,402 +0,0 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
#include "matador/sql/column.hpp"
|
||||
#include "matador/sql/condition.hpp"
|
||||
#include "matador/sql/connection.hpp"
|
||||
#include "matador/sql/query_builder.hpp"
|
||||
|
||||
#include "connection.hpp"
|
||||
|
||||
#include <list>
|
||||
|
||||
class QueryRecordFixture
|
||||
{
|
||||
public:
|
||||
QueryRecordFixture()
|
||||
: db(matador::test::connection::dns)
|
||||
, schema(db.dialect().default_schema_name())
|
||||
{
|
||||
db.open();
|
||||
}
|
||||
~QueryRecordFixture() {
|
||||
drop_table_if_exists("flight");
|
||||
drop_table_if_exists("airplane");
|
||||
drop_table_if_exists("person");
|
||||
drop_table_if_exists("quotes");
|
||||
}
|
||||
|
||||
protected:
|
||||
matador::sql::connection db;
|
||||
matador::sql::schema schema;
|
||||
|
||||
private:
|
||||
void drop_table_if_exists(const std::string &table_name) {
|
||||
if (db.exists(table_name)) {
|
||||
db.query(schema).drop().table(table_name).execute();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
using namespace matador::sql;
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Create and drop table statement", "[session][record]")
|
||||
{
|
||||
REQUIRE(!db.exists("person"));
|
||||
db.query(schema).create()
|
||||
.table("person", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("name", 255),
|
||||
make_column<unsigned short>("age")
|
||||
})
|
||||
.execute();
|
||||
|
||||
REQUIRE(db.exists("person"));
|
||||
|
||||
db.query(schema).drop()
|
||||
.table("person")
|
||||
.execute();
|
||||
|
||||
REQUIRE(!db.exists("person"));
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Create and drop table statement with foreign key", "[session][record]")
|
||||
{
|
||||
db.query(schema).create()
|
||||
.table("airplane", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("brand", 255),
|
||||
make_column<std::string>("model", 255),
|
||||
})
|
||||
.execute();
|
||||
|
||||
REQUIRE(db.exists("airplane"));
|
||||
|
||||
db.query(schema).create()
|
||||
.table("flight", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_fk_column<unsigned long>("airplane_id", "airplane", "id"),
|
||||
make_column<std::string>("pilot_name", 255),
|
||||
})
|
||||
.execute();
|
||||
|
||||
REQUIRE(db.exists("flight"));
|
||||
|
||||
db.query(schema).drop()
|
||||
.table("flight")
|
||||
.execute();
|
||||
|
||||
REQUIRE(!db.exists("flight"));
|
||||
|
||||
db.query(schema).drop()
|
||||
.table("airplane")
|
||||
.execute();
|
||||
|
||||
REQUIRE(!db.exists("airplane"));
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Execute insert record statement", "[session][record]")
|
||||
{
|
||||
db.query(schema).create()
|
||||
.table("person", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("name", 255),
|
||||
make_column<unsigned short>("age")
|
||||
})
|
||||
.execute();
|
||||
|
||||
auto res = db.query(schema).insert()
|
||||
.into("person", {"id", "name", "age"})
|
||||
.values({7, "george", 45})
|
||||
.execute();
|
||||
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto result = db.query(schema).select({"id", "name", "age"})
|
||||
.from("person")
|
||||
.fetch_all();
|
||||
|
||||
for (const auto &i: result) {
|
||||
REQUIRE(i.size() == 3);
|
||||
REQUIRE(i.at(0).name() == "id");
|
||||
// REQUIRE(i.at(0).type() == data_type_t::type_long_long);
|
||||
REQUIRE(i.at(0).template as<long long>() == 7);
|
||||
REQUIRE(i.at(1).name() == "name");
|
||||
// REQUIRE(i.at(1).type() == data_type_t::type_varchar);
|
||||
REQUIRE(i.at(1).template as<std::string>() == "george");
|
||||
REQUIRE(i.at(2).name() == "age");
|
||||
// REQUIRE(i.at(2).type() == matador::sql::data_type_t::type_int);
|
||||
REQUIRE(i.at(2).template as<int>() == 45);
|
||||
}
|
||||
|
||||
db.query(schema).drop()
|
||||
.table("person")
|
||||
.execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Execute insert record statement with foreign key", "[session][record]")
|
||||
{
|
||||
db.query(schema).create()
|
||||
.table("airplane", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("brand", 255),
|
||||
make_column<std::string>("model", 255),
|
||||
})
|
||||
.execute();
|
||||
|
||||
db.query(schema).create()
|
||||
.table("flight", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_fk_column<unsigned long>("airplane_id", "airplane", "id"),
|
||||
make_column<std::string>("pilot_name", 255),
|
||||
})
|
||||
.execute();
|
||||
|
||||
auto res = db.query(schema).insert().into("airplane", {"id", "brand", "model"}).values({1, "Airbus", "A380"}).execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
res = db.query(schema).insert().into("airplane", {"id", "brand", "model"}).values({2, "Boeing", "707"}).execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
res = db.query(schema).insert().into("airplane", {"id", "brand", "model"}).values({3, "Boeing", "747"}).execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto count = db.query(schema).select({count_all()}).from("airplane").fetch_value<int>();
|
||||
REQUIRE(count == 3);
|
||||
|
||||
res = db.query(schema).insert().into("flight", {"id", "airplane_id", "pilot_name"}).values({4, 1, "George"}).execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
db.query(schema).drop().table("flight").execute();
|
||||
db.query(schema).drop().table("airplane").execute();
|
||||
|
||||
REQUIRE(!db.exists("flight"));
|
||||
REQUIRE(!db.exists("airplane"));
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Execute update record statement", "[session][record]")
|
||||
{
|
||||
db.query(schema).create()
|
||||
.table("person", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("name", 255),
|
||||
make_column<unsigned short>("age")
|
||||
})
|
||||
.execute();
|
||||
|
||||
auto res = db.query(schema).insert()
|
||||
.into("person", {"id", "name", "age"})
|
||||
.values({7, "george", 45})
|
||||
.execute();
|
||||
|
||||
REQUIRE(res == 1);
|
||||
|
||||
res = db.query(schema).update("person")
|
||||
.set({{"id", 7},
|
||||
{"name", "jane"},
|
||||
{"age", 35}})
|
||||
.where("id"_col == 7)
|
||||
.execute();
|
||||
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto result = db.query(schema).select({"id", "name", "age"})
|
||||
.from("person")
|
||||
.fetch_all();
|
||||
|
||||
for (const auto &i: result) {
|
||||
REQUIRE(i.size() == 3);
|
||||
REQUIRE(i.at(0).name() == "id");
|
||||
REQUIRE(i.at(0).is_integer());
|
||||
REQUIRE(i.at(0).as<long long>() == 7);
|
||||
REQUIRE(i.at(1).name() == "name");
|
||||
REQUIRE(i.at(1).is_varchar());
|
||||
REQUIRE(i.at(1).as<std::string>() == "jane");
|
||||
REQUIRE(i.at(2).name() == "age");
|
||||
REQUIRE(i.at(2).is_integer());
|
||||
REQUIRE(i.at(2).as<int>() == 35);
|
||||
}
|
||||
|
||||
db.query(schema).drop().table("person").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Execute select statement", "[session][record]")
|
||||
{
|
||||
db.query(schema).create()
|
||||
.table("person", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("name", 255),
|
||||
make_column<unsigned short>("age")
|
||||
})
|
||||
.execute();
|
||||
|
||||
auto res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({1, "george", 45}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({2, "jane", 32}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({3, "michael", 67}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({4, "bob", 13}).execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto result = db.query(schema).select({"id", "name", "age"})
|
||||
.from("person")
|
||||
.fetch_all();
|
||||
|
||||
std::list<std::string> expected_names{"george", "jane", "michael", "bob"};
|
||||
for (const auto &p: result) {
|
||||
REQUIRE(p.at(1).str() == expected_names.front());
|
||||
expected_names.pop_front();
|
||||
}
|
||||
REQUIRE(expected_names.empty());
|
||||
|
||||
auto rec = db.query(schema).select({"id", "name", "age"})
|
||||
.from("person")
|
||||
.fetch_one();
|
||||
REQUIRE(rec.has_value());
|
||||
REQUIRE(rec->at(1).str() == "george");
|
||||
|
||||
auto name = db.query(schema).select({"name"})
|
||||
.from("person")
|
||||
.fetch_value<std::string>();
|
||||
REQUIRE(name == "george");
|
||||
|
||||
db.query(schema).drop().table("person").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Execute select statement with order by", "[session][record]")
|
||||
{
|
||||
db.query(schema).create()
|
||||
.table("person", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("name", 255),
|
||||
make_column<unsigned short>("age")
|
||||
})
|
||||
.execute();
|
||||
|
||||
auto res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({1, "george", 45}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({2, "jane", 32}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({3, "michael", 67}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({4, "bob", 13}).execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto result = db.query(schema).select({"id", "name", "age"})
|
||||
.from("person")
|
||||
.order_by("name").asc()
|
||||
.fetch_all();
|
||||
|
||||
std::list<std::string> expected_names{"bob", "george", "jane", "michael"};
|
||||
for (const auto &p: result) {
|
||||
REQUIRE(p.at(1).str() == expected_names.front());
|
||||
expected_names.pop_front();
|
||||
}
|
||||
REQUIRE(expected_names.empty());
|
||||
|
||||
db.query(schema).drop().table("person").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Execute select statement with group by and order by", "[session][record]")
|
||||
{
|
||||
db.query(schema).create()
|
||||
.table("person", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("name", 255),
|
||||
make_column<unsigned short>("age")
|
||||
})
|
||||
.execute();
|
||||
|
||||
auto res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({1, "george", 45}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({2, "jane", 45}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({3, "michael", 13}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({4, "bob", 13}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({5, "charlie", 67}).execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto result = db.query(schema).select({count("age").as("age_count"), "age"})
|
||||
.from("person")
|
||||
.group_by("age")
|
||||
.order_by("age_count").desc()
|
||||
.fetch_all();
|
||||
|
||||
std::list<std::pair<int, int>> expected_values{{2, 45},
|
||||
{2, 13},
|
||||
{1, 67}};
|
||||
for (const auto &r: result) {
|
||||
REQUIRE(r.at(0).as<int>() == expected_values.front().first);
|
||||
REQUIRE(r.at(1).as<int>() == expected_values.front().second);
|
||||
expected_values.pop_front();
|
||||
}
|
||||
|
||||
db.query(schema).drop().table("person").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Execute delete statement", "[session][record]")
|
||||
{
|
||||
db.query(schema).create()
|
||||
.table("person", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("name", 255),
|
||||
make_column<unsigned short>("age")
|
||||
}).execute();
|
||||
|
||||
auto res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({1, "george", 45}).execute();
|
||||
REQUIRE(res == 1);
|
||||
res = db.query(schema).insert().into("person", {"id", "name", "age"}).values({2, "jane", 45}).execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto count = db.query(schema).select({count_all()}).from("person").fetch_value<int>();
|
||||
REQUIRE(count == 2);
|
||||
|
||||
res = db.query(schema).remove()
|
||||
.from("person")
|
||||
.where("id"_col == 1)
|
||||
.execute();
|
||||
|
||||
REQUIRE(res == 1);
|
||||
|
||||
count = db.query(schema).select({count_all()}).from("person").fetch_value<int>();
|
||||
REQUIRE(count == 1);
|
||||
|
||||
db.query(schema).drop().table("person").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryRecordFixture, "Test quoted identifier", "[session][record]") {
|
||||
db.query(schema).create()
|
||||
.table("quotes", {
|
||||
make_column<std::string>("from", 255),
|
||||
make_column<std::string>("to", 255)
|
||||
}).execute();
|
||||
|
||||
// check table description
|
||||
std::vector<std::string> columns = { "from", "to"};
|
||||
std::vector<data_type_t> types = {data_type_t::type_varchar, data_type_t::type_varchar};
|
||||
auto fields = db.describe("quotes");
|
||||
|
||||
for (const auto &field : fields) {
|
||||
REQUIRE(field.name() == columns[field.index()]);
|
||||
REQUIRE(field.type() == types[field.index()]);
|
||||
}
|
||||
|
||||
db.query(schema).insert().into("quotes", {"from", "to"}).values({"Berlin", "London"}).execute();
|
||||
|
||||
auto res = db.query(schema).select({"from", "to"}).from("quotes").fetch_one();
|
||||
|
||||
REQUIRE(res.has_value());
|
||||
REQUIRE("Berlin" == res->at("from").str());
|
||||
REQUIRE("London" == res->at("to").str());
|
||||
|
||||
db.query(schema).update("quotes").set({{"from", "Hamburg"}, {"to", "New York"}}).where("from"_col == "Berlin").execute();
|
||||
|
||||
res = db.query(schema).select({"from", "to"}).from("quotes").fetch_one();
|
||||
|
||||
REQUIRE("Hamburg" == res->at("from").str());
|
||||
REQUIRE("New York" == res->at("to").str());
|
||||
|
||||
db.query(schema).drop().table("quotes").execute();
|
||||
}
|
||||
@@ -1,535 +0,0 @@
|
||||
#include "catch2/catch_test_macros.hpp"
|
||||
|
||||
#include "matador/sql/column_definition.hpp"
|
||||
#include "matador/sql/condition.hpp"
|
||||
#include "matador/sql/query_builder.hpp"
|
||||
#include "matador/sql/session.hpp"
|
||||
|
||||
#include "connection.hpp"
|
||||
|
||||
#include "models/airplane.hpp"
|
||||
#include "models/flight.hpp"
|
||||
#include "models/person.hpp"
|
||||
#include "models/recipe.hpp"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
using namespace matador::sql;
|
||||
using namespace matador::test;
|
||||
|
||||
class QueryFixture
|
||||
{
|
||||
public:
|
||||
QueryFixture()
|
||||
: db(matador::test::connection::dns)
|
||||
, schema(db.dialect().default_schema_name())
|
||||
{
|
||||
db.open();
|
||||
}
|
||||
|
||||
~QueryFixture()
|
||||
{
|
||||
drop_table_if_exists("flight");
|
||||
drop_table_if_exists("airplane");
|
||||
drop_table_if_exists("person");
|
||||
drop_table_if_exists("recipe_ingredients");
|
||||
drop_table_if_exists("recipes");
|
||||
drop_table_if_exists("ingredients");
|
||||
}
|
||||
|
||||
protected:
|
||||
matador::sql::connection db;
|
||||
matador::sql::schema schema;
|
||||
|
||||
private:
|
||||
void drop_table_if_exists(const std::string &table_name)
|
||||
{
|
||||
if (db.exists(table_name)) {
|
||||
db.query(schema).drop().table(table_name).execute();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_CASE_METHOD(QueryFixture, "Create table with foreign key relation", "[session]")
|
||||
{
|
||||
schema.attach<airplane>("airplane");
|
||||
schema.attach<flight>("flight");
|
||||
db.query(schema).create()
|
||||
.table<airplane>("airplane")
|
||||
.execute();
|
||||
|
||||
REQUIRE(db.exists("airplane"));
|
||||
|
||||
db.query(schema).create()
|
||||
.table<flight>("flight")
|
||||
.execute();
|
||||
|
||||
REQUIRE(db.exists("flight"));
|
||||
|
||||
db.query(schema).drop().table("flight").execute();
|
||||
db.query(schema).drop().table("airplane").execute();
|
||||
|
||||
REQUIRE(!db.exists("flight"));
|
||||
REQUIRE(!db.exists("airplane"));
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryFixture, "Execute select statement with where clause", "[session]")
|
||||
{
|
||||
schema.attach<person>("person");
|
||||
db.query(schema).create()
|
||||
.table<person>("person")
|
||||
.execute();
|
||||
|
||||
person george{7, "george", 45};
|
||||
george.image.push_back(37);
|
||||
|
||||
auto res = db.query(schema)
|
||||
.insert()
|
||||
.into("person", column_generator::generate<person>(schema, true))
|
||||
.values(george)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
// fetch person as record
|
||||
auto result_record = db.query(schema)
|
||||
.select(column_generator::generate<person>(schema, true))
|
||||
.from("person")
|
||||
.where("id"_col == 7)
|
||||
.fetch_all();
|
||||
|
||||
for (const auto &i: result_record) {
|
||||
REQUIRE(i.size() == 4);
|
||||
REQUIRE(i.at(0).name() == "id");
|
||||
REQUIRE(i.at(0).is_integer());
|
||||
REQUIRE(i.at(0).as<long long>() == george.id);
|
||||
REQUIRE(i.at(1).name() == "name");
|
||||
REQUIRE(i.at(1).is_varchar());
|
||||
REQUIRE(i.at(1).as<std::string>() == george.name);
|
||||
REQUIRE(i.at(2).name() == "age");
|
||||
REQUIRE(i.at(2).is_integer());
|
||||
REQUIRE(i.at(2).as<long long>() == george.age);
|
||||
}
|
||||
|
||||
// fetch person as person
|
||||
auto result_person = db.query(schema)
|
||||
.select(column_generator::generate<person>(schema, true))
|
||||
.from("person")
|
||||
.where("id"_col == 7)
|
||||
.fetch_all<person>();
|
||||
|
||||
for (const auto &i: result_person) {
|
||||
REQUIRE(i.id == 7);
|
||||
REQUIRE(i.name == "george");
|
||||
REQUIRE(i.age == 45);
|
||||
}
|
||||
|
||||
db.query(schema).drop().table("person").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryFixture, "Execute insert statement", "[session]")
|
||||
{
|
||||
db.query(schema).create()
|
||||
.table("person", {
|
||||
make_pk_column<unsigned long>("id"),
|
||||
make_column<std::string>("name", 255),
|
||||
make_column<std::string>("color", 63)
|
||||
})
|
||||
.execute();
|
||||
|
||||
auto res = db.query(schema).insert()
|
||||
.into("person", {{"", "id", ""}, {"", "name", ""}, {"", "color", ""}})
|
||||
.values({7, "george", "green"})
|
||||
.execute();
|
||||
|
||||
REQUIRE(res == 1);
|
||||
|
||||
// fetch person as record
|
||||
auto result_record = db.query(schema).select({"id", "name", "color"})
|
||||
.from("person")
|
||||
.where("id"_col == 7)
|
||||
.fetch_all();
|
||||
|
||||
for (const auto &i: result_record) {
|
||||
REQUIRE(i.size() == 3);
|
||||
REQUIRE(i.at(0).name() == "id");
|
||||
REQUIRE(i.at(0).is_integer());
|
||||
REQUIRE(i.at(0).as<unsigned long>() == 7);
|
||||
REQUIRE(i.at(1).name() == "name");
|
||||
REQUIRE(i.at(1).is_varchar());
|
||||
REQUIRE(i.at(1).as<std::string>() == "george");
|
||||
REQUIRE(i.at(2).name() == "color");
|
||||
REQUIRE(i.at(2).is_varchar());
|
||||
REQUIRE(i.at(2).as<std::string>() == "green");
|
||||
}
|
||||
|
||||
db.query(schema).drop().table("person").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryFixture, "Select statement with foreign key", "[session]")
|
||||
{
|
||||
schema.attach<airplane>("airplane");
|
||||
schema.attach<flight>("flight");
|
||||
db.query(schema).create()
|
||||
.table<airplane>("airplane")
|
||||
.execute();
|
||||
|
||||
db.query(schema).create()
|
||||
.table<flight>("flight")
|
||||
.execute();
|
||||
|
||||
std::vector<entity<airplane>> planes{
|
||||
make_entity<airplane>(1, "Airbus", "A380"),
|
||||
make_entity<airplane>(2, "Boeing", "707"),
|
||||
make_entity<airplane>(3, "Boeing", "747")
|
||||
};
|
||||
|
||||
for (const auto &plane: planes) {
|
||||
auto res = db.query(schema)
|
||||
.insert()
|
||||
.into("airplane", column_generator::generate<airplane>(schema, true))
|
||||
.values(*plane)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
}
|
||||
|
||||
auto count = db.query(schema)
|
||||
.select({count_all()})
|
||||
.from("airplane")
|
||||
.fetch_value<int>().value();
|
||||
REQUIRE(count == 3);
|
||||
|
||||
flight f4711{4, planes.at(1), "hans"};
|
||||
|
||||
auto res = db.query(schema)
|
||||
.insert()
|
||||
.into("flight", column_generator::generate<flight>(schema, true))
|
||||
.values(f4711)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto f = *db.query(schema)
|
||||
.select(column_generator::generate<flight>(schema, true))
|
||||
.from("flight")
|
||||
.fetch_all().begin();
|
||||
REQUIRE(f.at(0).as<unsigned long>() == 4);
|
||||
REQUIRE(f.at(1).as<unsigned long>() == 2);
|
||||
REQUIRE(f.at(2).as<std::string>() == "hans");
|
||||
|
||||
db.query(schema).drop().table("flight").execute();
|
||||
db.query(schema).drop().table("airplane").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryFixture, "Select statement with foreign key and join_left", "[session][join_left]")
|
||||
{
|
||||
schema.attach<airplane>("airplane");
|
||||
schema.attach<flight>("flight");
|
||||
db.query(schema).create()
|
||||
.table<airplane>("airplane")
|
||||
.execute();
|
||||
|
||||
db.query(schema).create()
|
||||
.table<flight>("flight")
|
||||
.execute();
|
||||
|
||||
std::vector<entity<airplane>> planes{
|
||||
make_entity<airplane>(1, "Airbus", "A380"),
|
||||
make_entity<airplane>(2, "Boeing", "707"),
|
||||
make_entity<airplane>(3, "Boeing", "747")
|
||||
};
|
||||
|
||||
for (const auto &plane: planes) {
|
||||
auto res = db.query(schema)
|
||||
.insert()
|
||||
.into("airplane", column_generator::generate<airplane>(schema, true))
|
||||
.values(*plane)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
}
|
||||
|
||||
auto count = db.query(schema)
|
||||
.select({count_all()})
|
||||
.from("airplane")
|
||||
.fetch_value<int>().value();
|
||||
REQUIRE(count == 3);
|
||||
|
||||
std::vector<entity<flight>> flights{
|
||||
make_entity<flight>(4, planes.at(0), "hans"),
|
||||
make_entity<flight>(5, planes.at(0), "otto"),
|
||||
make_entity<flight>(6, planes.at(1), "george"),
|
||||
make_entity<flight>(7, planes.at(2), "paul")
|
||||
};
|
||||
|
||||
for (const auto &f: flights) {
|
||||
auto res = db.query(schema)
|
||||
.insert()
|
||||
.into("flight", {"id", "airplane_id", "pilot_name"})
|
||||
.values(*f)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
}
|
||||
|
||||
auto f = *db.query(schema)
|
||||
.select(column_generator::generate<flight>(schema, true))
|
||||
.from("flight")
|
||||
.fetch_all().begin();
|
||||
REQUIRE(f.at(0).as<unsigned long>() == 4);
|
||||
REQUIRE(f.at(1).as<unsigned long>() == 1);
|
||||
REQUIRE(f.at(2).as<std::string>() == "hans");
|
||||
|
||||
auto result = db.query(schema).select({"f.id", "ap.brand", "ap.model", "f.pilot_name"})
|
||||
.from({"flight", "f"})
|
||||
.join_left({"airplane", "ap"})
|
||||
.on("f.airplane_id"_col == "ap.id"_col)
|
||||
.order_by("f.id").asc()
|
||||
.fetch_all();
|
||||
|
||||
std::vector<std::pair<unsigned long, std::string>> expected_result {
|
||||
{4, "hans"},
|
||||
{5, "otto"},
|
||||
{6, "george"},
|
||||
{7, "paul"}
|
||||
};
|
||||
size_t index{0};
|
||||
for (const auto &r: result) {
|
||||
REQUIRE(r.size() == 4);
|
||||
REQUIRE(r.at(0).as<unsigned long>() == expected_result[index].first);
|
||||
REQUIRE(r.at(3).as<std::string>() == expected_result[index++].second);
|
||||
}
|
||||
|
||||
db.query(schema).drop().table("flight").execute();
|
||||
db.query(schema).drop().table("airplane").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryFixture, "Select statement with foreign key and for single entity", "[session][join_left][find]") {
|
||||
schema.attach<airplane>("airplane");
|
||||
schema.attach<flight>("flight");
|
||||
db.query(schema).create()
|
||||
.table<airplane>("airplane")
|
||||
.execute();
|
||||
|
||||
db.query(schema).create()
|
||||
.table<flight>("flight")
|
||||
.execute();
|
||||
|
||||
std::vector<entity<airplane>> planes{
|
||||
make_entity<airplane>(1, "Airbus", "A380"),
|
||||
make_entity<airplane>(2, "Boeing", "707"),
|
||||
make_entity<airplane>(3, "Boeing", "747")
|
||||
};
|
||||
|
||||
for (const auto &plane: planes) {
|
||||
auto res = db
|
||||
.query(schema)
|
||||
.insert()
|
||||
.into("airplane", column_generator::generate<airplane>(schema, true))
|
||||
.values(*plane)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
}
|
||||
|
||||
auto count = db
|
||||
.query(schema)
|
||||
.select({count_all()})
|
||||
.from("airplane")
|
||||
.fetch_value<int>().value();
|
||||
REQUIRE(count == 3);
|
||||
|
||||
std::vector<entity<flight>> flights{
|
||||
make_entity<flight>(4, planes.at(0), "hans"),
|
||||
make_entity<flight>(5, planes.at(0), "otto"),
|
||||
make_entity<flight>(6, planes.at(1), "george"),
|
||||
make_entity<flight>(7, planes.at(2), "paul")
|
||||
};
|
||||
|
||||
for (const auto &f: flights) {
|
||||
auto res = db.query(schema)
|
||||
.insert()
|
||||
.into("flight", column_generator::generate<flight>(schema, true))
|
||||
.values(*f)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
}
|
||||
|
||||
auto f = db.query(schema)
|
||||
.select(column_generator::generate<flight>(schema, true))
|
||||
.from("flight")
|
||||
.fetch_one();
|
||||
REQUIRE(f.has_value());
|
||||
REQUIRE(f->at(0).as<unsigned long>() == 4);
|
||||
REQUIRE(f->at(1).as<unsigned long>() == 1);
|
||||
REQUIRE(f->at(2).as<std::string>() == "hans");
|
||||
|
||||
auto result = db
|
||||
.query(schema)
|
||||
.select({"f.id", "f.airplane_id", "ap.brand", "ap.model", "f.pilot_name"})
|
||||
.from({"flight", "f"})
|
||||
.join_left({"airplane", "ap"})
|
||||
.on("f.airplane_id"_col == "ap.id"_col)
|
||||
.where("f.id"_col == 4)
|
||||
.fetch_one<flight>();
|
||||
|
||||
auto expected_flight = flights[0];
|
||||
|
||||
REQUIRE(result);
|
||||
REQUIRE(result->id == expected_flight->id);
|
||||
REQUIRE(result->pilot_name == expected_flight->pilot_name);
|
||||
REQUIRE(result->airplane.get());
|
||||
REQUIRE(result->airplane->id == 1);
|
||||
REQUIRE(result->airplane->model == "A380");
|
||||
REQUIRE(result->airplane->brand == "Airbus");
|
||||
|
||||
db.query(schema).drop().table("flight").execute();
|
||||
db.query(schema).drop().table("airplane").execute();
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(QueryFixture, "Select statement with many to many relationship", "[session][join][many_to_many]") {
|
||||
schema.attach<recipe>("recipes");
|
||||
schema.attach<ingredient>("ingredients");
|
||||
schema.attach<recipe_ingredient>("recipe_ingredients");
|
||||
db.query(schema).create()
|
||||
.table<recipe>("recipes")
|
||||
.execute();
|
||||
|
||||
db.query(schema).create()
|
||||
.table<ingredient>("ingredients")
|
||||
.execute();
|
||||
|
||||
db.query(schema).create()
|
||||
.table<recipe_ingredient>("recipe_ingredients")
|
||||
.execute();
|
||||
|
||||
std::vector<ingredient> ingredients {
|
||||
{1, "Apple"},
|
||||
{2, "Strawberry"},
|
||||
{3, "Pineapple"},
|
||||
{4, "Sugar"},
|
||||
{5, "Flour"},
|
||||
{6, "Butter"},
|
||||
{7, "Beans"}
|
||||
};
|
||||
|
||||
for (const auto &i: ingredients) {
|
||||
auto res = db
|
||||
.query(schema)
|
||||
.insert()
|
||||
.into("ingredients", column_generator::generate<ingredient>(schema, true))
|
||||
.values(i)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
}
|
||||
|
||||
std::vector<recipe> recipes{
|
||||
{7, "Apple Crumble"},
|
||||
{8, "Beans Chili"},
|
||||
{9, "Fruit Salad"}
|
||||
};
|
||||
|
||||
for (const auto &r: recipes) {
|
||||
auto res = db
|
||||
.query(schema)
|
||||
.insert()
|
||||
.into("recipes", column_generator::generate<recipe>(schema, true))
|
||||
.values(r)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
}
|
||||
|
||||
std::vector<std::pair<int, int>> recipe_ingredients {
|
||||
{ 7, 1 },
|
||||
{ 7, 4 },
|
||||
{ 7, 5 },
|
||||
{ 8, 6 },
|
||||
{ 8, 7 },
|
||||
{ 9, 1 },
|
||||
{ 9, 2 },
|
||||
{ 9, 3 }
|
||||
};
|
||||
|
||||
for (const auto &ri: recipe_ingredients) {
|
||||
auto res = db
|
||||
.query(schema)
|
||||
.insert()
|
||||
.into("recipe_ingredients", column_generator::generate<recipe_ingredient>(schema, true))
|
||||
.values({ri.first, ri.second})
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
}
|
||||
|
||||
auto result = db
|
||||
.query(schema)
|
||||
.select({"r.id", "r.name", "ri.ingredient_id"})
|
||||
.from({"recipes", "r"})
|
||||
.join_left({"recipe_ingredients", "ri"})
|
||||
.on("r.id"_col == "ri.recipe_id"_col)
|
||||
.fetch_all();
|
||||
|
||||
std::vector<std::tuple<unsigned long, std::string, unsigned long>> expected_result_one_join {
|
||||
{7, "Apple Crumble", 1},
|
||||
{7, "Apple Crumble", 4},
|
||||
{7, "Apple Crumble", 5},
|
||||
{8, "Beans Chili", 6},
|
||||
{8, "Beans Chili", 7},
|
||||
{9, "Fruit Salad", 1},
|
||||
{9, "Fruit Salad", 2},
|
||||
{9, "Fruit Salad", 3}
|
||||
};
|
||||
size_t index{0};
|
||||
for (const auto &r: result) {
|
||||
REQUIRE(r.size() == 3);
|
||||
REQUIRE(r.at(0).as<unsigned long>().value() == std::get<0>(expected_result_one_join[index]));
|
||||
REQUIRE(r.at(1).as<std::string>().value() == std::get<1>(expected_result_one_join[index]));
|
||||
REQUIRE(r.at(2).as<unsigned long>().value() == std::get<2>(expected_result_one_join[index]));
|
||||
++index;
|
||||
}
|
||||
|
||||
result = db
|
||||
.query(schema)
|
||||
.select({"r.id", "r.name", "ri.ingredient_id", "i.name"})
|
||||
.from({"recipes", "r"})
|
||||
.join_left({"recipe_ingredients", "ri"}).on("r.id"_col == "ri.recipe_id"_col)
|
||||
.join_left({"ingredients", "i"}).on("ri.ingredient_id"_col == "i.id"_col)
|
||||
.fetch_all();
|
||||
|
||||
std::vector<std::tuple<unsigned long, std::string, unsigned long, std::string>> expected_result_two_joins {
|
||||
{7, "Apple Crumble", 1, "Apple"},
|
||||
{7, "Apple Crumble", 4, "Sugar"},
|
||||
{7, "Apple Crumble", 5, "Flour"},
|
||||
{8, "Beans Chili", 6, "Butter"},
|
||||
{8, "Beans Chili", 7, "Beans"},
|
||||
{9, "Fruit Salad", 1, "Apple"},
|
||||
{9, "Fruit Salad", 2, "Strawberry"},
|
||||
{9, "Fruit Salad", 3, "Pineapple"}
|
||||
};
|
||||
index = 0;
|
||||
for (const auto &r: result) {
|
||||
REQUIRE(r.size() == 4);
|
||||
REQUIRE(r.at(0).as<unsigned long>().value() == std::get<0>(expected_result_two_joins[index]));
|
||||
REQUIRE(r.at(1).as<std::string>().value() == std::get<1>(expected_result_two_joins[index]));
|
||||
REQUIRE(r.at(2).as<unsigned long>().value() == std::get<2>(expected_result_two_joins[index]));
|
||||
REQUIRE(r.at(3).as<std::string>().value() == std::get<3>(expected_result_two_joins[index]));
|
||||
++index;
|
||||
}
|
||||
|
||||
result = db
|
||||
.query(schema)
|
||||
.select({"r.id", "r.name", "ri.ingredient_id", "i.name"})
|
||||
.from({"recipes", "r"})
|
||||
.join_left({"recipe_ingredients", "ri"}).on("r.id"_col == "ri.recipe_id"_col)
|
||||
.join_left({"ingredients", "i"}).on("ri.ingredient_id"_col == "i.id"_col)
|
||||
.where("r.id"_col == 8)
|
||||
.fetch_all();
|
||||
|
||||
index = 3;
|
||||
for (const auto &r: result) {
|
||||
REQUIRE(r.size() == 4);
|
||||
REQUIRE(r.at(0).as<unsigned long>().value() == std::get<0>(expected_result_two_joins[index]));
|
||||
REQUIRE(r.at(1).as<std::string>().value() == std::get<1>(expected_result_two_joins[index]));
|
||||
REQUIRE(r.at(2).as<unsigned long>().value() == std::get<2>(expected_result_two_joins[index]));
|
||||
REQUIRE(r.at(3).as<std::string>().value() == std::get<3>(expected_result_two_joins[index]));
|
||||
++index;
|
||||
}
|
||||
|
||||
db.query(schema).drop().table("recipe_ingredients").execute();
|
||||
db.query(schema).drop().table("recipes").execute();
|
||||
db.query(schema).drop().table("ingredients").execute();
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
#include "catch2/catch_test_macros.hpp"
|
||||
|
||||
#include "connection.hpp"
|
||||
|
||||
#include "matador/sql/session.hpp"
|
||||
|
||||
#include "models/airplane.hpp"
|
||||
#include "models/flight.hpp"
|
||||
|
||||
class SessionFixture
|
||||
{
|
||||
public:
|
||||
SessionFixture()
|
||||
: pool(matador::test::connection::dns, 4)
|
||||
, ses(pool)
|
||||
{}
|
||||
|
||||
~SessionFixture()
|
||||
{
|
||||
drop_table_if_exists("flights");
|
||||
drop_table_if_exists("airplanes");
|
||||
}
|
||||
|
||||
protected:
|
||||
matador::sql::connection_pool<matador::sql::connection> pool;
|
||||
matador::sql::session ses;
|
||||
|
||||
private:
|
||||
void drop_table_if_exists(const std::string &table_name)
|
||||
{
|
||||
if (ses.table_exists(table_name)) {
|
||||
ses.drop_table(table_name);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
using namespace matador;
|
||||
|
||||
TEST_CASE_METHOD(SessionFixture, "Session relation test", "[session][relation]") {
|
||||
using namespace matador;
|
||||
ses.attach<test::airplane>("airplanes");
|
||||
ses.attach<test::flight>("flights");
|
||||
ses.create_schema();
|
||||
auto plane = ses.insert<test::airplane>(1, "Boeing", "A380");
|
||||
auto f = ses.insert<test::flight>(2, plane, "sully");
|
||||
|
||||
auto result = ses.find<test::flight>(2);
|
||||
REQUIRE(result.is_ok());
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(SessionFixture, "Use session to find object with id", "[session][find]") {
|
||||
using namespace matador::test;
|
||||
ses.attach<airplane>("airplanes");
|
||||
ses.create_schema();
|
||||
auto a380 = ses.insert<airplane>(1, "Boeing", "A380");
|
||||
|
||||
auto result = ses.find<airplane>(2);
|
||||
REQUIRE(!result.is_ok());
|
||||
REQUIRE((result.err() == sql::session_error::FailedToFindObject));
|
||||
|
||||
result = ses.find<airplane>(1);
|
||||
|
||||
REQUIRE(result);
|
||||
auto read_a380 = result.value();
|
||||
REQUIRE(a380->id == read_a380->id);
|
||||
}
|
||||
|
||||
TEST_CASE_METHOD(SessionFixture, "Use session to find all objects", "[session][find]") {
|
||||
using namespace matador::test;
|
||||
ses.attach<airplane>("airplanes");
|
||||
ses.create_schema();
|
||||
|
||||
std::vector<std::unique_ptr<airplane>> planes;
|
||||
planes.emplace_back(new airplane(1, "Airbus", "A380"));
|
||||
planes.emplace_back(new airplane(2, "Boeing", "707"));
|
||||
planes.emplace_back(new airplane(3, "Boeing", "747"));
|
||||
|
||||
for (auto &&plane: planes) {
|
||||
ses.insert(plane.release());
|
||||
}
|
||||
|
||||
auto result = ses.find<airplane>();
|
||||
|
||||
std::vector<std::tuple<int, std::string, std::string>> expected_result {
|
||||
{1, "Airbus", "A380"},
|
||||
{2, "Boeing", "707"},
|
||||
{3, "Boeing", "747"}
|
||||
};
|
||||
REQUIRE(result);
|
||||
auto all_planes = result.release();
|
||||
size_t index {0};
|
||||
for (const auto &i: all_planes) {
|
||||
REQUIRE(i.id == std::get<0>(expected_result[index]));
|
||||
REQUIRE(i.brand == std::get<1>(expected_result[index]));
|
||||
REQUIRE(i.model == std::get<2>(expected_result[index]));
|
||||
++index;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
#include "matador/sql/column_definition.hpp"
|
||||
#include "matador/sql/condition.hpp"
|
||||
#include "matador/sql/connection.hpp"
|
||||
|
||||
#include "connection.hpp"
|
||||
|
||||
#include "models/airplane.hpp"
|
||||
|
||||
using namespace matador::sql;
|
||||
using namespace matador::test;
|
||||
|
||||
class StatementTestFixture
|
||||
{
|
||||
public:
|
||||
StatementTestFixture()
|
||||
: db(matador::test::connection::dns)
|
||||
, schema(db.dialect().default_schema_name())
|
||||
{
|
||||
db.open();
|
||||
db.query(schema).create().table<airplane>("airplane").execute();
|
||||
}
|
||||
|
||||
~StatementTestFixture()
|
||||
{
|
||||
drop_table_if_exists("airplane");
|
||||
}
|
||||
|
||||
protected:
|
||||
matador::sql::connection db;
|
||||
matador::sql::schema schema;
|
||||
|
||||
std::vector<entity<airplane>> planes{
|
||||
make_entity<airplane>(1, "Airbus", "A380"),
|
||||
make_entity<airplane>(2, "Boeing", "707"),
|
||||
make_entity<airplane>(3, "Boeing", "747")
|
||||
};
|
||||
|
||||
private:
|
||||
void drop_table_if_exists(const std::string &table_name) {
|
||||
if (db.exists(table_name)) {
|
||||
db.query(schema).drop().table(table_name).execute();
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
TEST_CASE_METHOD(StatementTestFixture, "Create prepared statement", "[statement]")
|
||||
{
|
||||
schema.attach<airplane>("airplane");
|
||||
table ap{"airplane"};
|
||||
SECTION("Insert with prepared statement and placeholder") {
|
||||
auto stmt = db.query(schema).insert()
|
||||
.into("airplane", column_generator::generate<airplane>(schema, true))
|
||||
.values<airplane>()
|
||||
.prepare();
|
||||
|
||||
for (const auto &plane: planes) {
|
||||
auto res = stmt.bind(*plane).execute();
|
||||
REQUIRE(res == 1);
|
||||
stmt.reset();
|
||||
}
|
||||
|
||||
auto result = db.query(schema)
|
||||
.select(column_generator::generate<airplane>(schema, true))
|
||||
.from(ap)
|
||||
.fetch_all<airplane>();
|
||||
|
||||
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 = db.query(schema)
|
||||
.insert()
|
||||
.into("airplane", column_generator::generate<airplane>(schema, true))
|
||||
.values(*plane)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
}
|
||||
|
||||
auto stmt = db.query(schema)
|
||||
.select(column_generator::generate<airplane>(schema, true))
|
||||
.from(ap)
|
||||
.where("brand"_col == _)
|
||||
.prepare();
|
||||
|
||||
stmt.bind(0, "Airbus");
|
||||
|
||||
auto result = stmt.fetch<airplane>();
|
||||
|
||||
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();
|
||||
|
||||
stmt.bind(0, "Boeing");
|
||||
|
||||
result = stmt.fetch<airplane>();
|
||||
|
||||
size_t index{1};
|
||||
for (const auto &i: result) {
|
||||
REQUIRE(i.id == planes[index]->id);
|
||||
REQUIRE(i.brand == planes[index]->brand);
|
||||
REQUIRE(i.model == planes[index++]->model);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
#include "matador/sql/connection.hpp"
|
||||
#include "matador/sql/column_generator.hpp"
|
||||
|
||||
#include "matador/utils/enum_mapper.hpp"
|
||||
|
||||
#include "connection.hpp"
|
||||
|
||||
#include "models/location.hpp"
|
||||
|
||||
using namespace matador::sql;
|
||||
using namespace matador::test;
|
||||
|
||||
class TypeTraitsTestFixture
|
||||
{
|
||||
public:
|
||||
TypeTraitsTestFixture()
|
||||
: db(matador::test::connection::dns)
|
||||
, schema(db.dialect().default_schema_name())
|
||||
{
|
||||
db.open();
|
||||
db.query(schema).create()
|
||||
.table<location>("location")
|
||||
.execute();
|
||||
}
|
||||
|
||||
~TypeTraitsTestFixture()
|
||||
{
|
||||
db.query(schema).drop().table("location").execute();
|
||||
}
|
||||
|
||||
protected:
|
||||
matador::sql::connection db;
|
||||
matador::sql::schema schema;
|
||||
|
||||
private:
|
||||
void drop_table_if_exists(const std::string &table_name) {
|
||||
if (db.exists(table_name)) {
|
||||
db.query(schema).drop().table(table_name).execute();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static const matador::utils::enum_mapper<Color> color_enum({
|
||||
{Color::Green, "green"},
|
||||
{Color::Red, "red"},
|
||||
{Color::Blue, "blue"},
|
||||
{Color::Yellow, "yellow"},
|
||||
{Color::Black, "black"},
|
||||
{Color::White, "white"},
|
||||
{Color::Brown, "brown"}
|
||||
});
|
||||
|
||||
template<>
|
||||
struct matador::sql::data_type_traits<Color, void>
|
||||
{
|
||||
inline static data_type_t builtin_type(std::size_t size)
|
||||
{ return data_type_traits<std::string>::builtin_type(size); }
|
||||
|
||||
static void read_value(query_result_reader &reader, const char *id, size_t index, Color &value)
|
||||
{
|
||||
std::string enum_string;
|
||||
reader.read_value(id, index, enum_string, 64);
|
||||
if (const auto enum_opt = color_enum.to_enum(enum_string)) {
|
||||
value = enum_opt.value();
|
||||
}
|
||||
}
|
||||
|
||||
static any_type create_value(const Color &value)
|
||||
{
|
||||
return color_enum.to_string(value);
|
||||
}
|
||||
|
||||
static void bind_value(parameter_binder &binder, size_t index, Color &value)
|
||||
{
|
||||
binder.bind(index, color_enum.to_string(value));
|
||||
}
|
||||
};
|
||||
|
||||
TEST_CASE_METHOD(TypeTraitsTestFixture, "Special handling of attributes with type traits", "[typetraits]")
|
||||
{
|
||||
schema.attach<location>("location");
|
||||
SECTION("Insert and select with direct execution") {
|
||||
location loc{1, "center", {1, 2, 3}, Color::Black};
|
||||
|
||||
auto res = db
|
||||
.query(schema)
|
||||
.insert()
|
||||
.into("location", column_generator::generate<location>(schema, true))
|
||||
.values(loc)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto result = db
|
||||
.query(schema)
|
||||
.select(column_generator::generate<location>(schema, true))
|
||||
.from("location")
|
||||
.fetch_all<location>();
|
||||
|
||||
for (const auto &l: result) {
|
||||
REQUIRE(l.name == "center");
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("Insert and select with prepared statement") {
|
||||
location loc{1, "center", {1, 2, 3}, Color::Black};
|
||||
|
||||
auto stmt = db
|
||||
.query(schema)
|
||||
.insert()
|
||||
.into("location", column_generator::generate<location>(schema, true))
|
||||
.values<location>()
|
||||
.prepare();
|
||||
|
||||
auto res = stmt
|
||||
.bind(loc)
|
||||
.execute();
|
||||
REQUIRE(res == 1);
|
||||
|
||||
auto result = db
|
||||
.query(schema)
|
||||
.select(column_generator::generate<location>(schema, true))
|
||||
.from("location")
|
||||
.fetch_all<location>();
|
||||
|
||||
for (const auto &l: result) {
|
||||
REQUIRE(l.name == "center");
|
||||
}
|
||||
}
|
||||
}
|
||||
+1269
File diff suppressed because it is too large
Load Diff
@@ -1,129 +0,0 @@
|
||||
# - Find mysqlclient
|
||||
# Find the native MySQL includes and library
|
||||
#
|
||||
# MYSQL_INCLUDE_DIR - where to find mysql.h, etc.
|
||||
# MYSQL_LIBRARY - List of libraries when using MySQL.
|
||||
# MYSQL_FOUND - True if MySQL found.
|
||||
|
||||
IF (MYSQL_INCLUDE_DIR)
|
||||
# Already in cache, be silent
|
||||
SET(MYSQL_FIND_QUIETLY TRUE)
|
||||
ENDIF (MYSQL_INCLUDE_DIR)
|
||||
|
||||
if(WIN32)
|
||||
find_path(MYSQL_INCLUDE_DIR mysql.h
|
||||
PATHS
|
||||
$ENV{MYSQL_INCLUDE_DIR}
|
||||
$ENV{MYSQL_DIR}/include
|
||||
$ENV{ProgramFiles}/MySQL/*/include
|
||||
$ENV{SystemDrive}/MySQL/*/include
|
||||
$ENV{ProgramW6432}/MySQL/*/include
|
||||
$ENV{ProgramFiles}/MariaDB/*/include
|
||||
$ENV{SystemDrive}/MariaDB/*/include
|
||||
$ENV{ProgramW6432}/MariaDB/*/include
|
||||
)
|
||||
else(WIN32)
|
||||
find_path(MYSQL_INCLUDE_DIR mysql.h
|
||||
PATHS
|
||||
$ENV{MYSQL_DIR}/include
|
||||
$ENV{MYSQL_INCLUDE_DIR}
|
||||
/usr/local/mysql/include
|
||||
/opt/mysql/mysql/include
|
||||
PATH_SUFFIXES
|
||||
mysql
|
||||
)
|
||||
endif(WIN32)
|
||||
|
||||
if(WIN32)
|
||||
if (${CMAKE_BUILD_TYPE})
|
||||
STRING(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_TOLOWER)
|
||||
endif()
|
||||
|
||||
# path suffix for debug/release mode
|
||||
# binary_dist: mysql binary distribution
|
||||
# build_dist: custom build
|
||||
if(CMAKE_BUILD_TYPE_TOLOWER MATCHES "debug")
|
||||
SET(binary_dist debug)
|
||||
SET(build_dist Debug)
|
||||
else(CMAKE_BUILD_TYPE_TOLOWER MATCHES "debug")
|
||||
ADD_DEFINITIONS(-DDBUG_OFF)
|
||||
SET(binary_dist opt)
|
||||
SET(build_dist Release)
|
||||
endif(CMAKE_BUILD_TYPE_TOLOWER MATCHES "debug")
|
||||
|
||||
FIND_LIBRARY(MYSQL_LIBRARY NAMES libmysql libmariadb
|
||||
PATHS
|
||||
$ENV{MYSQL_DIR}/lib
|
||||
# $ENV{MYSQL_DIR}/lib/${binary_dist}
|
||||
# $ENV{MYSQL_DIR}/libmysql/${build_dist}
|
||||
# $ENV{MYSQL_DIR}/client/${build_dist}
|
||||
# $ENV{ProgramFiles}/MySQL/*/lib/${binary_dist}
|
||||
$ENV{ProgramFiles}/MySQL/*/lib
|
||||
$ENV{SystemDrive}/MySQL/*/lib
|
||||
$ENV{ProgramW6432}/MySQL/*/lib
|
||||
$ENV{ProgramFiles}/MariaDB/*/lib
|
||||
$ENV{SystemDrive}/MariaDB/*/lib
|
||||
$ENV{ProgramW6432}/MariaDB/*/lib
|
||||
# $ENV{SystemDrive}/MySQL/*/lib/${binary_dist}
|
||||
# $ENV{ProgramFiles}/MariaDB/*/lib/${binary_dist}
|
||||
# $ENV{SystemDrive}/MariaDB/*/lib/${binary_dist}
|
||||
# $ENV{MYSQL_DIR}/lib/opt
|
||||
# $ENV{MYSQL_DIR}/client/release
|
||||
# $ENV{ProgramFiles}/MySQL/*/lib/opt
|
||||
# $ENV{SystemDrive}/MySQL/*/lib/opt
|
||||
# $ENV{ProgramW6432}/MySQL/*/lib
|
||||
# $ENV{ProgramFiles}/MariaDB/*/lib/opt
|
||||
# $ENV{SystemDrive}/MariaDB/*/lib/opt
|
||||
# $ENV{ProgramW6432}/MariaDB/*/lib
|
||||
)
|
||||
else(WIN32)
|
||||
find_library(MYSQL_LIBRARY NAMES libmysql
|
||||
PATHS
|
||||
$ENV{MYSQL_DIR}/libmysql_r/.libs
|
||||
$ENV{MYSQL_DIR}/lib
|
||||
$ENV{MYSQL_DIR}/lib/mysql
|
||||
/usr/local/mysql/lib
|
||||
/opt/mysql/mysql/lib
|
||||
PATH_SUFFIXES
|
||||
mysql
|
||||
)
|
||||
endif(WIN32)
|
||||
|
||||
if(WIN32)
|
||||
else(WIN32)
|
||||
set(MYSQL_LIB_PATHS
|
||||
$ENV{MYSQL_DIR}/libmysql_r/.libs
|
||||
$ENV{MYSQL_DIR}/lib
|
||||
$ENV{MYSQL_DIR}/lib/mysql
|
||||
/usr/local/mysql/lib
|
||||
/opt/mysql/mysql/lib
|
||||
PATH_SUFFIXES
|
||||
mysql
|
||||
)
|
||||
find_library(MYSQL_LIBRARY NAMES mysqlclient
|
||||
PATHS
|
||||
${MYSQL_LIB_PATHS}
|
||||
)
|
||||
endif(WIN32)
|
||||
|
||||
IF (MYSQL_INCLUDE_DIR)
|
||||
MESSAGE(STATUS "MariaDB include ${MYSQL_INCLUDE_DIR}")
|
||||
ELSE (MYSQL_INCLUDE_DIR)
|
||||
MESSAGE(STATUS "MariaDB include dir not found")
|
||||
ENDIF (MYSQL_INCLUDE_DIR)
|
||||
|
||||
IF (MYSQL_LIBRARY)
|
||||
MESSAGE(STATUS "MariaDB libs ${MYSQL_LIBRARY}")
|
||||
ELSE (MYSQL_LIBRARY)
|
||||
MESSAGE(STATUS "MariaDB libs dir not found")
|
||||
ENDIF (MYSQL_LIBRARY)
|
||||
|
||||
|
||||
IF (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
|
||||
SET(MYSQL_FOUND TRUE)
|
||||
ELSE (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
|
||||
SET(MYSQL_FOUND FALSE)
|
||||
SET(MYSQL_LIBRARY)
|
||||
ENDIF (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)
|
||||
|
||||
MARK_AS_ADVANCED(MYSQL_LIBRARY MYSQL_INCLUDE_DIR)
|
||||
+2
-1
@@ -2,7 +2,8 @@
|
||||
|
||||
add_executable(demo main.cpp)
|
||||
target_link_libraries(demo PRIVATE
|
||||
matador
|
||||
matador-core
|
||||
matador-orm
|
||||
${CMAKE_DL_LIBS}
|
||||
${SQLite3_LIBRARIES}
|
||||
)
|
||||
|
||||
+148
-158
@@ -1,19 +1,24 @@
|
||||
#include "matador/sql/column.hpp"
|
||||
#include "matador/sql/condition.hpp"
|
||||
#include "matador/sql/schema.hpp"
|
||||
#include "matador/sql/connection.hpp"
|
||||
#include "matador/sql/entity.hpp"
|
||||
#include "matador/sql/query_macro.hpp"
|
||||
|
||||
#include "matador/query/condition.hpp"
|
||||
|
||||
#include "matador/object/object_ptr.hpp"
|
||||
#include "matador/object/schema.hpp"
|
||||
|
||||
#include "matador/utils/access.hpp"
|
||||
#include "matador/utils/default_type_traits.hpp"
|
||||
#include "matador/utils/enum_mapper.hpp"
|
||||
#include "matador/utils/types.hpp"
|
||||
|
||||
#include "matador/sql/query_helper.hpp"
|
||||
#include "matador/sql/query_macro.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
struct author {
|
||||
unsigned long id{};
|
||||
unsigned int id{};
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
std::string date_of_birth;
|
||||
@@ -22,7 +27,7 @@ struct author {
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::utils::access;
|
||||
namespace field = matador::access;
|
||||
field::primary_key( op, "id", id );
|
||||
field::attribute( op, "first_name", first_name, 63 );
|
||||
field::attribute( op, "last_name", last_name, 63 );
|
||||
@@ -33,14 +38,14 @@ struct author {
|
||||
};
|
||||
|
||||
struct book {
|
||||
unsigned long id{};
|
||||
matador::sql::entity<author> book_author;
|
||||
unsigned int id{};
|
||||
matador::object::object_ptr<author> book_author;
|
||||
std::string title;
|
||||
unsigned short published_in{};
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::utils::access;
|
||||
namespace field = matador::access;
|
||||
field::primary_key( op, "id", id );
|
||||
field::attribute( op, "title", title, 511 );
|
||||
field::has_one( op, "author_id", book_author, matador::utils::default_foreign_attributes );
|
||||
@@ -49,11 +54,11 @@ struct book {
|
||||
};
|
||||
|
||||
struct payload {
|
||||
unsigned long id{};
|
||||
unsigned int id{};
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::utils::access;
|
||||
namespace field = matador::access;
|
||||
field::primary_key( op, "id", id );
|
||||
}
|
||||
};
|
||||
@@ -72,8 +77,8 @@ struct job {
|
||||
Background
|
||||
};
|
||||
|
||||
unsigned long id{};
|
||||
matador::sql::entity<payload> payload;
|
||||
unsigned int id{};
|
||||
matador::object::object_ptr<payload> data;
|
||||
std::string type;
|
||||
std::string description;
|
||||
job_state state;
|
||||
@@ -81,9 +86,9 @@ struct job {
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::utils::access;
|
||||
namespace field = matador::access;
|
||||
field::primary_key( op, "id", id );
|
||||
field::belongs_to( op, "payload", payload, matador::utils::default_foreign_attributes );
|
||||
field::belongs_to( op, "payload", data, matador::utils::default_foreign_attributes );
|
||||
field::attribute( op, "type", type, 511 );
|
||||
field::attribute( op, "description", description, 511 );
|
||||
field::attribute( op, "state", state );
|
||||
@@ -105,13 +110,10 @@ static const matador::utils::enum_mapper<job::job_mode> job_mode_enum({
|
||||
});
|
||||
|
||||
template<>
|
||||
struct matador::sql::data_type_traits<job::job_state, void>
|
||||
{
|
||||
inline static data_type_t builtin_type(std::size_t size)
|
||||
{ return data_type_traits<std::string>::builtin_type(size); }
|
||||
struct matador::utils::data_type_traits<job::job_state, void> {
|
||||
static basic_type type(const std::size_t size) { return data_type_traits<std::string>::type(size); }
|
||||
|
||||
static void read_value(query_result_reader &reader, const char *id, size_t index, job::job_state &value)
|
||||
{
|
||||
static void read_value(attribute_reader &reader, const char *id, const size_t index, job::job_state &value) {
|
||||
std::string enum_string;
|
||||
reader.read_value(id, index, enum_string, 64);
|
||||
if (const auto enum_opt = job_state_enum.to_enum(enum_string)) {
|
||||
@@ -119,25 +121,16 @@ struct matador::sql::data_type_traits<job::job_state, void>
|
||||
}
|
||||
}
|
||||
|
||||
static any_type create_value(const job::job_state &value)
|
||||
{
|
||||
return job_state_enum.to_string(value);
|
||||
}
|
||||
|
||||
static void bind_value(parameter_binder &binder, size_t index, job::job_state &value)
|
||||
{
|
||||
binder.bind(index, job_state_enum.to_string(value));
|
||||
static void write_value(attribute_writer &binder, const size_t index, const job::job_state &value) {
|
||||
binder.write_value(index, job_state_enum.to_string(value));
|
||||
}
|
||||
};
|
||||
|
||||
template<>
|
||||
struct matador::sql::data_type_traits<job::job_mode, void>
|
||||
{
|
||||
inline static data_type_t builtin_type(std::size_t size)
|
||||
{ return data_type_traits<std::string>::builtin_type(size); }
|
||||
struct matador::utils::data_type_traits<job::job_mode, void> {
|
||||
static basic_type type( const std::size_t size) { return data_type_traits<std::string>::type(size); }
|
||||
|
||||
static void read_value(query_result_reader &reader, const char *id, size_t index, job::job_mode &value)
|
||||
{
|
||||
static void read_value(attribute_reader &reader, const char *id, const size_t index, job::job_mode &value) {
|
||||
std::string enum_string;
|
||||
reader.read_value(id, index, enum_string, 64);
|
||||
if (const auto enum_opt = job_mode_enum.to_enum(enum_string)) {
|
||||
@@ -145,14 +138,8 @@ struct matador::sql::data_type_traits<job::job_mode, void>
|
||||
}
|
||||
}
|
||||
|
||||
static any_type create_value(const job::job_mode &value)
|
||||
{
|
||||
return job_mode_enum.to_string(value);
|
||||
}
|
||||
|
||||
static void bind_value(parameter_binder &binder, size_t index, job::job_mode &value)
|
||||
{
|
||||
binder.bind(index, job_mode_enum.to_string(value));
|
||||
static void bind_value(attribute_writer &binder, const size_t index, const job::job_mode &value) {
|
||||
binder.write_value(index, job_mode_enum.to_string(value));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -168,128 +155,131 @@ QUERY_HELPER( temporary_table, id );
|
||||
|
||||
int main() {
|
||||
using namespace matador::sql;
|
||||
using namespace matador;
|
||||
using namespace matador::object;
|
||||
using namespace matador::utils;
|
||||
|
||||
const std::string env_var{"MATADOR_BACKENDS_PATH"};
|
||||
|
||||
std::string dns{"sqlite://demo.db"};
|
||||
schema s( "main" );
|
||||
s.attach<author>( "authors" );
|
||||
s.attach<book>( "books" );
|
||||
auto result = s.attach<author>( "authors" ).and_then( [&s] {
|
||||
return s.attach<book>( "books" );
|
||||
} );
|
||||
// s.attach<book>( "books" );
|
||||
|
||||
connection c( dns );
|
||||
c.open();
|
||||
s.create( c );
|
||||
|
||||
auto create_authors_sql = c.query( s )
|
||||
.create()
|
||||
.table<author>( qh::authors )
|
||||
.execute();
|
||||
|
||||
c.query( s )
|
||||
.create()
|
||||
.table<book>( qh::books )
|
||||
.execute();
|
||||
|
||||
std::cout << "SQL: " << create_authors_sql << "\n";
|
||||
|
||||
author mc;
|
||||
mc.id = 1;
|
||||
mc.first_name = "Michael";
|
||||
mc.last_name = "Crichton";
|
||||
mc.date_of_birth = "19.8.1954";
|
||||
mc.year_of_birth = 1954;
|
||||
mc.distinguished = true;
|
||||
auto insert_authors_sql = c.query( s )
|
||||
.insert()
|
||||
.into( qh::authors )
|
||||
.values( mc )
|
||||
.execute();
|
||||
|
||||
std::cout << "SQL: " << insert_authors_sql << "\n";
|
||||
|
||||
auto result = c.query( s )
|
||||
.select( qh::authors.columns )
|
||||
.from( qh::authors )
|
||||
.fetch_all();
|
||||
|
||||
for (const auto& row: result) { std::cout << "Author " << row.at( qh::authors.first_name ) << "\n"; }
|
||||
|
||||
auto update_authors_sql = c.query( s )
|
||||
.update( qh::authors )
|
||||
.set( {{qh::authors.first_name, "Stephen"},
|
||||
{qh::authors.last_name, "King"}} )
|
||||
.where( qh::authors.last_name == "Crichton" )
|
||||
.execute();
|
||||
|
||||
std::cout << "SQL: " << update_authors_sql << "\n";
|
||||
|
||||
auto authors = c.query( s )
|
||||
.select( qh::authors.columns )
|
||||
.from( qh::authors )
|
||||
.fetch_all<author>();
|
||||
|
||||
for (const auto& a: authors) { std::cout << "Author " << a.first_name << "\n"; }
|
||||
|
||||
c.query( s )
|
||||
.insert()
|
||||
.into( qh::books )
|
||||
.values( {2, "It", mc.id, 1980} )
|
||||
.execute();
|
||||
|
||||
c.query( s )
|
||||
.insert()
|
||||
.into( qh::books )
|
||||
.values( {3, "Misery", mc.id, 1984} )
|
||||
.execute();
|
||||
|
||||
auto select_books_sql = c.query( s )
|
||||
.select( qh::books.columns, {qh::authors.last_name} )
|
||||
.from( qh::books )
|
||||
.join_left( qh::authors )
|
||||
.on( qh::books.author_id == qh::authors.id )
|
||||
.where( qh::books.published_in < 2008 && qh::authors.last_name == "King" )
|
||||
.group_by( qh::books.published_in )
|
||||
.order_by( qh::books.title ).asc()
|
||||
.limit( 5 )
|
||||
.offset( 2 )
|
||||
.fetch_all();
|
||||
|
||||
for (const auto& r: select_books_sql) { std::cout << "R: " << r.at( qh::books.title ) << ", " << r.at( qh::authors.last_name ) << "\n"; }
|
||||
// SELECT book.title, book.id, book.author_id, book.published_in, author.name
|
||||
// FROM book
|
||||
// INNER JOIN author ON book.author_id = author.id
|
||||
// WHERE book.published_in < 2008 AND author.name = "Michael Crichton"
|
||||
// ORDER BY "book.title" ASC
|
||||
// OFFSET 2 LIMIT 5
|
||||
|
||||
c.query( s ).drop().table( qh::books ).execute();
|
||||
|
||||
auto drop_authors_sql = c.query( s )
|
||||
.drop()
|
||||
.table( qh::authors )
|
||||
.execute();
|
||||
|
||||
std::cout << "SQL: " << drop_authors_sql << "\n";
|
||||
|
||||
auto res = c.query( s )
|
||||
.select( {qh::payload.id} )
|
||||
.from( qh::payload )
|
||||
.join_left( qh::job )
|
||||
.on( qh::job.payload == qh::payload.id )
|
||||
.where(
|
||||
in( qh::payload.id, c.query( s )
|
||||
.select( {qh::job.state} )
|
||||
.from( qh::job )
|
||||
.where( qh::job.state == job::job_state::Running )
|
||||
) &&
|
||||
in( qh::payload.id, c.query( s )
|
||||
.select( {qh::temporary_table.id} )
|
||||
.from( qh::temporary_table ) )
|
||||
)
|
||||
.build();
|
||||
// .fetch_value<unsigned long>();
|
||||
std::cout << "SQL: " << res.sql << "\n";
|
||||
result = c.open();
|
||||
// s.create( c );
|
||||
//
|
||||
// auto create_authors_sql = c.query( s )
|
||||
// .create()
|
||||
// .table<author>( qh::authors )
|
||||
// .execute();
|
||||
//
|
||||
// c.query( s )
|
||||
// .create()
|
||||
// .table<book>( qh::books )
|
||||
// .execute();
|
||||
//
|
||||
// std::cout << "SQL: " << create_authors_sql << "\n";
|
||||
//
|
||||
// author mc;
|
||||
// mc.id = 1;
|
||||
// mc.first_name = "Michael";
|
||||
// mc.last_name = "Crichton";
|
||||
// mc.date_of_birth = "19.8.1954";
|
||||
// mc.year_of_birth = 1954;
|
||||
// mc.distinguished = true;
|
||||
// auto insert_authors_sql = c.query( s )
|
||||
// .insert()
|
||||
// .into( qh::authors )
|
||||
// .values( mc )
|
||||
// .execute();
|
||||
//
|
||||
// std::cout << "SQL: " << insert_authors_sql << "\n";
|
||||
//
|
||||
// auto result = c.query( s )
|
||||
// .select( qh::authors.columns )
|
||||
// .from( qh::authors )
|
||||
// .fetch_all();
|
||||
//
|
||||
// for (const auto& row: result) { std::cout << "Author " << row.at( qh::authors.first_name ) << "\n"; }
|
||||
//
|
||||
// auto update_authors_sql = c.query( s )
|
||||
// .update( qh::authors )
|
||||
// .set( {{qh::authors.first_name, "Stephen"},
|
||||
// {qh::authors.last_name, "King"}} )
|
||||
// .where( qh::authors.last_name == "Crichton" )
|
||||
// .execute();
|
||||
//
|
||||
// std::cout << "SQL: " << update_authors_sql << "\n";
|
||||
//
|
||||
// auto authors = c.query( s )
|
||||
// .select( qh::authors.columns )
|
||||
// .from( qh::authors )
|
||||
// .fetch_all<author>();
|
||||
//
|
||||
// for (const auto& a: authors) { std::cout << "Author " << a.first_name << "\n"; }
|
||||
//
|
||||
// c.query( s )
|
||||
// .insert()
|
||||
// .into( qh::books )
|
||||
// .values( {2, "It", mc.id, 1980} )
|
||||
// .execute();
|
||||
//
|
||||
// c.query( s )
|
||||
// .insert()
|
||||
// .into( qh::books )
|
||||
// .values( {3, "Misery", mc.id, 1984} )
|
||||
// .execute();
|
||||
//
|
||||
// auto select_books_sql = c.query( s )
|
||||
// .select( qh::books.columns, {qh::authors.last_name} )
|
||||
// .from( qh::books )
|
||||
// .join_left( qh::authors )
|
||||
// .on( qh::books.author_id == qh::authors.id )
|
||||
// .where( qh::books.published_in < 2008 && qh::authors.last_name == "King" )
|
||||
// .group_by( qh::books.published_in )
|
||||
// .order_by( qh::books.title ).asc()
|
||||
// .limit( 5 )
|
||||
// .offset( 2 )
|
||||
// .fetch_all();
|
||||
//
|
||||
// for (const auto& r: select_books_sql) { std::cout << "R: " << r.at( qh::books.title ) << ", " << r.at( qh::authors.last_name ) << "\n"; }
|
||||
// // SELECT book.title, book.id, book.author_id, book.published_in, author.name
|
||||
// // FROM book
|
||||
// // INNER JOIN author ON book.author_id = author.id
|
||||
// // WHERE book.published_in < 2008 AND author.name = "Michael Crichton"
|
||||
// // ORDER BY "book.title" ASC
|
||||
// // OFFSET 2 LIMIT 5
|
||||
//
|
||||
// c.query( s ).drop().table( qh::books ).execute();
|
||||
//
|
||||
// auto drop_authors_sql = c.query( s )
|
||||
// .drop()
|
||||
// .table( qh::authors )
|
||||
// .execute();
|
||||
//
|
||||
// std::cout << "SQL: " << drop_authors_sql << "\n";
|
||||
//
|
||||
// auto res = c.query( s )
|
||||
// .select( {qh::payload.id} )
|
||||
// .from( qh::payload )
|
||||
// .join_left( qh::job )
|
||||
// .on( qh::job.payload == qh::payload.id )
|
||||
// .where(
|
||||
// in( qh::payload.id, c.query( s )
|
||||
// .select( {qh::job.state} )
|
||||
// .from( qh::job )
|
||||
// .where( qh::job.state == job::job_state::Running )
|
||||
// ) &&
|
||||
// in( qh::payload.id, c.query( s )
|
||||
// .select( {qh::temporary_table.id} )
|
||||
// .from( qh::temporary_table ) )
|
||||
// )
|
||||
// .build();
|
||||
// // .fetch_value<unsigned long>();
|
||||
// std::cout << "SQL: " << res.sql << "\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
#include "work/admin/CollectionCenter.hpp"
|
||||
#include "work/admin/InternalUserDirectory.hpp"
|
||||
#include "work/admin/LdapGroupSchemaSettings.hpp"
|
||||
#include "work/admin/LdapImportSettings.hpp"
|
||||
#include "work/admin/LdapUserDirectory.hpp"
|
||||
#include "work/admin/LdapUserSchemaSettings.hpp"
|
||||
#include "work/admin/LoginHistory.hpp"
|
||||
#include "work/admin/Scenario.hpp"
|
||||
#include "work/admin/User.hpp"
|
||||
#include "work/admin/UserDirectory.hpp"
|
||||
#include "work/admin/UserSession.hpp"
|
||||
|
||||
#include "work/jobs/Job.hpp"
|
||||
#include "work/jobs/Task.hpp""
|
||||
#include "work/jobs/Payload.hpp"
|
||||
#include "work/jobs/IdPayload.hpp"
|
||||
#include "work/jobs/IdListPayload.hpp"
|
||||
|
||||
#include "matador/object/schema.hpp"
|
||||
|
||||
#include "matador/sql/connection.hpp"
|
||||
|
||||
#include "matador/orm/session.hpp"
|
||||
|
||||
using namespace matador;
|
||||
using namespace work::models;
|
||||
|
||||
int main() {
|
||||
object::schema schema("Administration");
|
||||
|
||||
auto result = schema.attach<admin::CollectionCenter>("collection_center")
|
||||
.and_then([&schema] { return schema.attach<admin::InternalUserDirectory>("internal_user_directory"); })
|
||||
.and_then([&schema] { return schema.attach<admin::LdapGroupSchemaSettings>("ldap_group_schema_settings"); })
|
||||
.and_then([&schema] { return schema.attach<admin::LdapImportSettings>("ldap_import_settings"); })
|
||||
.and_then([&schema] { return schema.attach<admin::LdapUserDirectory>("ldap_user_directory"); } )
|
||||
.and_then([&schema] { return schema.attach<admin::LdapUserSchemaSettings>("ldap_user_schema_settings"); })
|
||||
.and_then([&schema] { return schema.attach<admin::LoginHistory>("login_history"); })
|
||||
.and_then([&schema] { return schema.attach<admin::Scenario>("scenario"); })
|
||||
.and_then([&schema] { return schema.attach<admin::User>("user"); })
|
||||
.and_then([&schema] { return schema.attach<admin::UserDirectory>("user_directory"); })
|
||||
.and_then([&schema] { return schema.attach<admin::UserSession>("user_session"); })
|
||||
.and_then([&schema] { return schema.attach<jobs::Job>("jobs"); })
|
||||
.and_then([&schema] { return schema.attach<jobs::Payload>("id_payloads"); })
|
||||
.and_then([&schema] { return schema.attach<jobs::IdPayload>("id_list_payloads"); })
|
||||
.and_then([&schema] { return schema.attach<jobs::IdListPayload>("payloads"); })
|
||||
.and_then([&schema] { return schema.attach<jobs::Task>("tasks"); });
|
||||
|
||||
if (!result.is_ok()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const std::string dns{"sqlite://demo.db"};
|
||||
sql::connection c(dns);
|
||||
|
||||
result = c.open();
|
||||
|
||||
// orm::session s()
|
||||
if (!result.is_ok()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// registering table 'collection_center' (pk field: 'id')
|
||||
// registering relation table 'collection_center_users' (first fk field: 'collection_center_id', second fk field: 'user_id')
|
||||
// registering table 'internal_user_directory' (pk field: 'id')
|
||||
//
|
||||
@@ -0,0 +1,47 @@
|
||||
#ifndef COLLECTION_CENTER_HPP
|
||||
#define COLLECTION_CENTER_HPP
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
|
||||
#include "matador/object/collection.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
#include "matador/utils/enum_mapper.hpp"
|
||||
#include "matador/utils/fetch_type.hpp"
|
||||
#include "matador/utils/types.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
struct User;
|
||||
|
||||
enum class CollectionCenterType : uint8_t {
|
||||
NoType,
|
||||
Core,
|
||||
Unit
|
||||
};
|
||||
|
||||
static const matador::utils::enum_mapper<CollectionCenterType> CollectionCenterTypeEnum({
|
||||
{CollectionCenterType::NoType, "NoType"},
|
||||
{CollectionCenterType::Core, "Core"},
|
||||
{CollectionCenterType::Unit, "Unit"}
|
||||
});
|
||||
|
||||
struct CollectionCenter : core::Model {
|
||||
std::string name;
|
||||
matador::utils::blob symbol;
|
||||
CollectionCenterType type{CollectionCenterType::NoType};
|
||||
matador::object::collection<User> users;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "name", name, 511 );
|
||||
field::attribute( op, "symbol", symbol );
|
||||
field::attribute( op, "type", type );
|
||||
field::has_many( op, "collection_center_users", users, "collection_center_id", matador::utils::fetch_type::LAZY );
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //COLLECTION_CENTER_HPP
|
||||
@@ -0,0 +1,18 @@
|
||||
#ifndef INTERNAL_USER_DIRECTORY_HPP
|
||||
#define INTERNAL_USER_DIRECTORY_HPP
|
||||
|
||||
#include "UserDirectory.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
struct InternalUserDirectory : UserDirectory {
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<UserDirectory>( this ) );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //INTERNALUSERDIRECTORY_HPP
|
||||
@@ -0,0 +1,25 @@
|
||||
#ifndef LDAP_GROUP_SCHEMA_SETTINGS_HPP
|
||||
#define LDAP_GROUP_SCHEMA_SETTINGS_HPP
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
|
||||
struct LdapGroupSchemaSettings : core::Model {
|
||||
std::string group_object_filter;
|
||||
std::string user_member_attribute;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "group_object_filter", group_object_filter, 511 );
|
||||
field::attribute( op, "user_member_attribute", user_member_attribute, 511 );
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //LDAP_GROUP_SCHEMA_SETTINGS_HPP
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef LDAP_IMPORT_SETTINGS_HPP
|
||||
#define LDAP_IMPORT_SETTINGS_HPP
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
|
||||
struct LdapImportSettings : core::Model {
|
||||
std::string default_role;
|
||||
unsigned int sync_interval;
|
||||
unsigned int network_timeout;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "default_role", default_role, 511 );
|
||||
field::attribute( op, "sync_interval", sync_interval );
|
||||
field::attribute( op, "network_timeout", network_timeout );
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //LDAP_IMPORT_SETTINGS_HPP
|
||||
@@ -0,0 +1,28 @@
|
||||
#ifndef LDAP_USER_DIRECTORY_HPP
|
||||
#define LDAP_USER_DIRECTORY_HPP
|
||||
|
||||
#include "UserDirectory.hpp"
|
||||
|
||||
#include "matador/object/collection.hpp"
|
||||
#include "matador/object/object_ptr.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
struct LdapUserDirectory : UserDirectory {
|
||||
std::string schema_base_dn;
|
||||
std::string additional_user_base_dn;
|
||||
std::string additional_group_base_dn;
|
||||
matador::object::collection<std::string> users;
|
||||
matador::object::collection<std::string> groups;
|
||||
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<UserDirectory>( this ) );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //LDAP_USER_DIRECTORY_HPP
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef LDAP_USER_SCHEMA_SETTINGS_HPP
|
||||
#define LDAP_USER_SCHEMA_SETTINGS_HPP
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
|
||||
struct LdapUserSchemaSettings : core::Model {
|
||||
std::string user_object_filter;
|
||||
std::string user_unique_id_attribute;
|
||||
std::string user_member_of_attribute;
|
||||
std::string user_name_attribute;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "user_object_filter", user_object_filter, 511 );
|
||||
field::attribute( op, "user_unique_id_attribute", user_unique_id_attribute, 511 );
|
||||
field::attribute( op, "user_member_of_attribute", user_member_of_attribute, 511 );
|
||||
field::attribute( op, "user_name_attribute", user_name_attribute, 511 );
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //LDAP_USER_SCHEMA_SETTINGS_HPP
|
||||
@@ -0,0 +1,21 @@
|
||||
#ifndef LOCKTYPE_HPP
|
||||
#define LOCKTYPE_HPP
|
||||
|
||||
#include "matador/utils/enum_mapper.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
enum class LockType : uint8_t {
|
||||
NoLock,
|
||||
AdminLock,
|
||||
SystemLock
|
||||
};
|
||||
|
||||
static const matador::utils::enum_mapper<LockType> LockTypeEnum({
|
||||
{LockType::NoLock, "NoLock"},
|
||||
{LockType::AdminLock, "AdminLock"},
|
||||
{LockType::SystemLock, "SystemLock"}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
#endif //LOCKTYPE_HPP
|
||||
@@ -0,0 +1,63 @@
|
||||
#ifndef LOGIN_HISTORY_HPP
|
||||
#define LOGIN_HISTORY_HPP
|
||||
|
||||
#include "CollectionCenter.hpp"
|
||||
#include "Scenario.hpp"
|
||||
#include "User.hpp"
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
|
||||
#include "matador/object/object_ptr.hpp""
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
#include "matador/utils/enum_mapper.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
|
||||
enum class FailReason : uint8_t {
|
||||
NoFailReason,
|
||||
InternalError,
|
||||
NoPermissionToLogin,
|
||||
NoScenarioForUser,
|
||||
UnknownUserName,
|
||||
UserLockedByAdmin,
|
||||
UserLockedBySystem,
|
||||
UserLockedByAdminAndSystem,
|
||||
WrongPassword
|
||||
};
|
||||
|
||||
static const matador::utils::enum_mapper<FailReason> FailReasonEnum({
|
||||
{FailReason::NoFailReason, "NoFailReason"},
|
||||
{FailReason::InternalError, "InternalError"},
|
||||
{FailReason::NoPermissionToLogin, "NoPermissionToLogin"},
|
||||
{FailReason::NoScenarioForUser, "NoScenarioForUser"},
|
||||
{FailReason::UnknownUserName, "UnknownUserName"},
|
||||
{FailReason::UserLockedByAdmin, "UserLockedByAdmin"},
|
||||
{FailReason::UserLockedBySystem, "UserLockedBySystem"},
|
||||
{FailReason::UserLockedByAdminAndSystem, "UserLockedByAdminAndSystem"},
|
||||
{FailReason::WrongPassword, "WrongPassword"}
|
||||
});
|
||||
|
||||
struct LoginHistory : core::Model {
|
||||
matador::object::object_ptr<User> user;
|
||||
matador::object::object_ptr<Scenario> scenario;
|
||||
matador::object::object_ptr<CollectionCenter> collection_center;
|
||||
std::string login_name;
|
||||
FailReason fail_reason{FailReason::NoFailReason};
|
||||
core::timestamp login_time;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::belongs_to( op, "user", user, matador::utils::default_foreign_attributes );
|
||||
field::belongs_to( op, "scenario", scenario, matador::utils::default_foreign_attributes );
|
||||
field::belongs_to( op, "collection_center", collection_center, matador::utils::default_foreign_attributes );
|
||||
field::attribute( op, "login_name", login_name, 511 );
|
||||
field::attribute( op, "fail_reason", fail_reason );
|
||||
field::attribute( op, "login_time", login_time );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //LOGIN_HISTORY_HPP
|
||||
@@ -0,0 +1,61 @@
|
||||
#ifndef SCENARIO_HPP
|
||||
#define SCENARIO_HPP
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
|
||||
#include "matador/object/collection.hpp"
|
||||
#include "matador/object/object_ptr.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
#include "matador/utils/enum_mapper.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
struct CollectionCenter;
|
||||
|
||||
enum class ScenarioMode : uint8_t {
|
||||
InvalidMode,
|
||||
Exercise,
|
||||
Operation,
|
||||
};
|
||||
|
||||
static const matador::utils::enum_mapper<ScenarioMode> ScenarioModeEnum({
|
||||
{ScenarioMode::InvalidMode, "InvalidMode"},
|
||||
{ScenarioMode::Exercise, "Exercise"},
|
||||
{ScenarioMode::Operation, "Operation"}
|
||||
});
|
||||
|
||||
enum class ScenarioState : uint8_t {
|
||||
InvalidState,
|
||||
Active,
|
||||
Inactive
|
||||
};
|
||||
|
||||
static const matador::utils::enum_mapper<ScenarioState> ScenarioStateEnum({
|
||||
{ScenarioState::InvalidState, "InvalidState"},
|
||||
{ScenarioState::Active, "Active"},
|
||||
{ScenarioState::Inactive, "Inactive"}
|
||||
});
|
||||
|
||||
struct Scenario : core::Model {
|
||||
std::string name;
|
||||
ScenarioMode mode{ScenarioMode::InvalidMode};
|
||||
std::string description;
|
||||
matador::utils::blob symbol;
|
||||
ScenarioState state{ScenarioState::InvalidState};
|
||||
matador::object::collection<CollectionCenter> collection_center;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "name", name, 511 );
|
||||
field::attribute( op, "mode", mode );
|
||||
field::attribute( op, "description", description, 511 );
|
||||
field::attribute( op, "symbol", symbol );
|
||||
field::attribute( op, "state", state );
|
||||
field::has_many( op, "collection_center", collection_center, "scenario_id", matador::utils::fetch_type::LAZY );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //SCENARIO_HPP
|
||||
@@ -0,0 +1,45 @@
|
||||
#ifndef USER_HPP
|
||||
#define USER_HPP
|
||||
|
||||
#include "LockType.hpp"
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
#include "../core/Types.hpp"
|
||||
|
||||
#include "matador/object/object_ptr.hpp""
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
#include "matador/utils/types.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
struct UserDirectory;
|
||||
|
||||
struct User : core::Model {
|
||||
std::string name;
|
||||
matador::utils::blob symbol;
|
||||
std::string salt;
|
||||
std::string password;
|
||||
LockType lock_type{LockType::NoLock};
|
||||
core::timestamp locked_at;
|
||||
std::string lock_reason;
|
||||
std::string role;
|
||||
matador::object::object_ptr<UserDirectory> user_directory;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "name", name, 511 );
|
||||
field::attribute( op, "symbol", symbol );
|
||||
field::attribute( op, "salt", salt, 511 );
|
||||
field::attribute( op, "password", password, 511 );
|
||||
field::attribute( op, "lock_type", lock_type );
|
||||
field::attribute( op, "locked_at", locked_at );
|
||||
field::attribute( op, "lock_reason", lock_reason, 511 );
|
||||
field::attribute( op, "role", role, 63 );
|
||||
field::belongs_to( op, "user_directory", user_directory, matador::utils::default_foreign_attributes );
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
#endif //USER_HPP
|
||||
@@ -0,0 +1,21 @@
|
||||
#ifndef USER_DIRECTORY_HPP
|
||||
#define USER_DIRECTORY_HPP
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
struct UserDirectory : core::Model {
|
||||
std::string name;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "name", name, 511 );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //USER_DIRECTORY_HPP
|
||||
@@ -0,0 +1,34 @@
|
||||
#ifndef USER_SESSION_HPP
|
||||
#define USER_SESSION_HPP
|
||||
|
||||
#include "CollectionCenter.hpp"
|
||||
#include "Scenario.hpp"
|
||||
#include "User.hpp"
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
#include "../core/Types.hpp"
|
||||
|
||||
#include "matador/object/object_ptr.hpp""
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::admin {
|
||||
struct UserSession : core::Model {
|
||||
matador::object::object_ptr<User> user;
|
||||
matador::object::object_ptr<Scenario> scenario;
|
||||
matador::object::object_ptr<CollectionCenter> collection_center;
|
||||
core::timestamp offline_since;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::belongs_to( op, "user", user, matador::utils::default_foreign_attributes );
|
||||
field::belongs_to( op, "scenario", scenario, matador::utils::default_foreign_attributes );
|
||||
field::belongs_to( op, "collection_center", collection_center, matador::utils::default_foreign_attributes );
|
||||
field::attribute( op, "offline_since", offline_since );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //USER_SESSION_HPP
|
||||
@@ -0,0 +1,19 @@
|
||||
#ifndef MODEL_HPP
|
||||
#define MODEL_HPP
|
||||
|
||||
#include "matador/utils/access.hpp"
|
||||
|
||||
namespace work::core {
|
||||
struct Model {
|
||||
unsigned long long id;
|
||||
unsigned long long version;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::primary_key( op, "id", id );
|
||||
field::revision( op, "version", version );
|
||||
}
|
||||
};
|
||||
}
|
||||
#endif //MODEL_HPP
|
||||
@@ -0,0 +1,9 @@
|
||||
#ifndef TYPES_HPP
|
||||
#define TYPES_HPP
|
||||
|
||||
#include <chrono>
|
||||
|
||||
namespace work::core {
|
||||
using timestamp = std::chrono::system_clock::time_point;
|
||||
}
|
||||
#endif //TYPES_HPP
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef USERINFO_HPP
|
||||
#define USERINFO_HPP
|
||||
|
||||
#include "matador/utils/access.hpp"
|
||||
|
||||
namespace work::core {
|
||||
struct UserInfo {
|
||||
unsigned long long user_session_id;
|
||||
std::string user_role;
|
||||
std::string database_name;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::attribute( op, "user_session_id", user_session_id );
|
||||
field::attribute( op, "user_role", user_role, 255 );
|
||||
field::attribute( op, "database_name", database_name, 255 );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //USERINFO_HPP
|
||||
@@ -0,0 +1,20 @@
|
||||
#ifndef ID_LIST_PAYLOAD_HPP
|
||||
#define ID_LIST_PAYLOAD_HPP
|
||||
|
||||
#include "Payload.hpp"
|
||||
|
||||
#include "matador/object/collection.hpp"
|
||||
|
||||
namespace work::models::jobs {
|
||||
struct IdListPayload : Payload {
|
||||
matador::object::collection<unsigned long long> ids;
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Payload>( this ) );
|
||||
field::has_many( op, "payload_ids", ids );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //ID_LIST_PAYLOAD_HPP
|
||||
@@ -0,0 +1,18 @@
|
||||
#ifndef ID_PAYLOAD_HPP
|
||||
#define ID_PAYLOAD_HPP
|
||||
|
||||
#include "Payload.hpp"
|
||||
|
||||
namespace work::models::jobs {
|
||||
struct IdPayload : Payload {
|
||||
unsigned long long id;
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Payload>( this ) );
|
||||
field::attribute( op, "id", id );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //ID_PAYLOAD_HPP
|
||||
@@ -0,0 +1,46 @@
|
||||
#ifndef JOB_HPP
|
||||
#define JOB_HPP
|
||||
|
||||
#include "JobMode.hpp"
|
||||
#include "JobState.hpp"
|
||||
#include "Payload.hpp"
|
||||
#include "Task.hpp"
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
#include "../core/Types.hpp"
|
||||
#include "../core/UserInfo.hpp"
|
||||
|
||||
#include "matador/object/object_ptr.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::jobs {
|
||||
|
||||
struct Job : core::Model {
|
||||
std::string name;
|
||||
std::string description;
|
||||
JobState state;
|
||||
JobMode mode;
|
||||
core::timestamp created_at;
|
||||
matador::object::object_ptr<Payload> payload;
|
||||
matador::object::object_ptr<Task> task;
|
||||
core::UserInfo user_info;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "name", name, 511 );
|
||||
field::attribute( op, "description", description, 511 );
|
||||
field::attribute( op, "state", state );
|
||||
field::attribute( op, "mode", mode );
|
||||
field::attribute( op, "created_at", created_at );
|
||||
field::belongs_to( op, "payload", payload, matador::utils::default_foreign_attributes );
|
||||
field::belongs_to( op, "task", task, matador::utils::default_foreign_attributes );
|
||||
field::attribute( op, "user_info", user_info );
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //JOB_HPP
|
||||
@@ -0,0 +1,20 @@
|
||||
#ifndef JOB_MODE_HPP
|
||||
#define JOB_MODE_HPP
|
||||
|
||||
#include "matador/utils/enum_mapper.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace work::models::jobs {
|
||||
enum class JobMode : uint8_t {
|
||||
Background,
|
||||
Foreground
|
||||
};
|
||||
|
||||
static const matador::utils::enum_mapper<JobMode> JobModeEnum({
|
||||
{JobMode::Background, "Background"},
|
||||
{JobMode::Foreground, "Foreground"}
|
||||
});
|
||||
}
|
||||
|
||||
#endif //JOB_MODE_HPP
|
||||
@@ -0,0 +1,28 @@
|
||||
#ifndef JOB_STATE_HPP
|
||||
#define JOB_STATE_HPP
|
||||
|
||||
#include "matador/utils/enum_mapper.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace work::models::jobs {
|
||||
enum class JobState : uint8_t {
|
||||
Pending,
|
||||
Running,
|
||||
Succeeded,
|
||||
Failed,
|
||||
Cancelled
|
||||
};
|
||||
|
||||
static const matador::utils::enum_mapper<JobState> JobStateEnum({
|
||||
{JobState::Pending, "Pending"},
|
||||
{JobState::Running, "Running"},
|
||||
{JobState::Succeeded, "Succeeded"},
|
||||
{JobState::Failed, "Failed"},
|
||||
{JobState::Cancelled, "Cancelled"}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
#endif //JOB_STATE_HPP
|
||||
@@ -0,0 +1,20 @@
|
||||
#ifndef PAYLOAD_HPP
|
||||
#define PAYLOAD_HPP
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::jobs {
|
||||
struct Payload : core::Model {
|
||||
std::string type;
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "type", type, 255 );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //PAYLOAD_HPP
|
||||
@@ -0,0 +1,42 @@
|
||||
#ifndef TASK_HPP
|
||||
#define TASK_HPP
|
||||
|
||||
#include "TaskState.hpp"
|
||||
|
||||
#include "../core/Model.hpp"
|
||||
#include "../core/Types.hpp"
|
||||
|
||||
#include "matador/object/object_ptr.hpp"
|
||||
|
||||
#include "matador/utils/base_class.hpp"
|
||||
|
||||
namespace work::models::jobs {
|
||||
struct Task : core::Model {
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::string job_name;
|
||||
TaskState state;
|
||||
matador::object::object_ptr<Payload> payload;
|
||||
JobMode job_mode;
|
||||
core::timestamp start_delay;
|
||||
core::timestamp interval;
|
||||
unsigned long long user_session_id;
|
||||
|
||||
template<typename Operator>
|
||||
void process( Operator& op ) {
|
||||
namespace field = matador::access;
|
||||
field::process( op, *matador::base_class<Model>( this ) );
|
||||
field::attribute( op, "name", name, 511 );
|
||||
field::attribute( op, "description", description, 511 );
|
||||
field::attribute( op, "job_name", job_name, 511 );
|
||||
field::attribute( op, "state", state );
|
||||
field::belongs_to( op, "payload", payload, matador::utils::default_foreign_attributes );
|
||||
field::attribute( op, "job_mode", job_mode );
|
||||
field::attribute( op, "start_delay", start_delay );
|
||||
field::attribute( op, "interval", interval );
|
||||
field::attribute( op, "user_session_id", user_session_id );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#endif //TASK_HPP
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef TASK_STATE_HPP
|
||||
#define TASK_STATE_HPP
|
||||
|
||||
#include "matador/utils/enum_mapper.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace work::models::jobs {
|
||||
enum class TaskState : uint8_t {
|
||||
Active,
|
||||
Inactive
|
||||
};
|
||||
|
||||
static const matador::utils::enum_mapper<TaskState> TaskStateEnum({
|
||||
{TaskState::Active, "Active"},
|
||||
{TaskState::Inactive, "Inactive"}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
#endif //TASK_STATE_HPP
|
||||
@@ -0,0 +1,206 @@
|
||||
#ifndef QUERY_COLUMN_DEFINITION_HPP
|
||||
#define QUERY_COLUMN_DEFINITION_HPP
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "matador/utils/basic_types.hpp"
|
||||
#include "matador/utils/default_type_traits.hpp"
|
||||
#include "matador/utils/field_attributes.hpp"
|
||||
#include "matador/utils/value.hpp"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
enum class null_option : uint8_t {
|
||||
NULLABLE, NOT_NULL
|
||||
};
|
||||
|
||||
class attribute_definition {
|
||||
public:
|
||||
explicit attribute_definition(const char *name); // NOLINT(*-explicit-constructor)
|
||||
explicit attribute_definition(std::string name); // NOLINT(*-explicit-constructor)
|
||||
|
||||
attribute_definition(const attribute_definition&) = default;
|
||||
attribute_definition& operator=(const attribute_definition&) = default;
|
||||
attribute_definition(attribute_definition&&) noexcept = default;
|
||||
attribute_definition& operator=(attribute_definition&&) noexcept = default;
|
||||
|
||||
template<typename Type>
|
||||
explicit attribute_definition(std::string name, std::string table_name, const utils::field_attributes& attr)
|
||||
: attribute_definition(std::move(name), std::move(table_name), utils::data_type_traits<Type>::type(attr.size()), attr)
|
||||
{}
|
||||
|
||||
attribute_definition(std::string name, std::string table_name, utils::basic_type type, const utils::field_attributes& attr);
|
||||
|
||||
template<typename Type>
|
||||
explicit attribute_definition(std::string name, const utils::field_attributes& attr)
|
||||
: attribute_definition(std::move(name), utils::data_type_traits<Type>::type(attr.size()), attr)
|
||||
{}
|
||||
|
||||
template<typename Type>
|
||||
attribute_definition(std::string name, const Type &, const utils::field_attributes& attr, null_option null_opt)
|
||||
: attribute_definition(std::move(name), utils::data_type_traits<Type>::type(attr.size()), attr, null_opt)
|
||||
{}
|
||||
|
||||
template<size_t SIZE>
|
||||
attribute_definition(std::string name, const char (&)[SIZE], const utils::field_attributes& attr, const null_option null_opt)
|
||||
: attribute_definition(std::move(name), utils::data_type_traits<const char*>::type(attr.size()), attr, null_opt)
|
||||
{}
|
||||
|
||||
attribute_definition(std::string name, utils::basic_type type, const utils::field_attributes&, null_option null_opt, size_t index = 0);
|
||||
attribute_definition(std::string name, std::string table_name, utils::basic_type type, const utils::field_attributes&, null_option null_opt, size_t index = 0);
|
||||
|
||||
template<typename Type>
|
||||
attribute_definition(std::string name, const std::shared_ptr<attribute_definition> &ref_column, const utils::field_attributes& attr, null_option null_opt)
|
||||
: attribute_definition(std::move(name), utils::data_type_traits<Type>::type(attr.size()), ref_column, attr, null_opt)
|
||||
{}
|
||||
|
||||
attribute_definition(std::string name, utils::basic_type type, size_t index, const std::shared_ptr<attribute_definition> &ref_column, const utils::field_attributes& attr, null_option null_opt);
|
||||
|
||||
[[nodiscard]] const std::string& name() const;
|
||||
void name(const std::string& n);
|
||||
[[nodiscard]] std::string full_name() const;
|
||||
[[nodiscard]] std::string table_name() const;
|
||||
[[nodiscard]] int index() const;
|
||||
[[nodiscard]] const utils::field_attributes& attributes() const;
|
||||
[[nodiscard]] bool is_nullable() const;
|
||||
[[nodiscard]] utils::basic_type type() const;
|
||||
[[nodiscard]] std::shared_ptr<attribute_definition> reference_column() const;
|
||||
[[nodiscard]] bool is_foreign_reference() const;
|
||||
|
||||
[[nodiscard]] bool is_integer() const;
|
||||
[[nodiscard]] bool is_floating_point() const;
|
||||
[[nodiscard]] bool is_bool() const;
|
||||
[[nodiscard]] bool is_string() const;
|
||||
[[nodiscard]] bool is_varchar() const;
|
||||
[[nodiscard]] bool is_date() const;
|
||||
[[nodiscard]] bool is_time() const;
|
||||
[[nodiscard]] bool is_blob() const;
|
||||
[[nodiscard]] bool is_null() const;
|
||||
|
||||
void type(utils::basic_type type);
|
||||
|
||||
template< typename Type >
|
||||
[[nodiscard]] bool is_type_of() const {
|
||||
return std::holds_alternative<Type>(value_);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::string str() const;
|
||||
|
||||
template<typename Type>
|
||||
void set(const Type &value, const utils::field_attributes &attr = utils::null_attributes)
|
||||
{
|
||||
attributes_ = attr;
|
||||
value_ = value;
|
||||
}
|
||||
|
||||
void set(const std::string &value, const utils::field_attributes &attr)
|
||||
{
|
||||
value_ = value;
|
||||
attributes_ = attr;
|
||||
}
|
||||
|
||||
void set(const char *value, const utils::field_attributes &attr)
|
||||
{
|
||||
value_ = std::string(value);
|
||||
attributes_ = attr;
|
||||
}
|
||||
|
||||
template<class Type>
|
||||
std::optional<Type> as() const
|
||||
{
|
||||
return value_.as<Type>();
|
||||
}
|
||||
|
||||
friend std::ostream& operator<<(std::ostream &out, const attribute_definition &col);
|
||||
|
||||
private:
|
||||
template<class Operator>
|
||||
void process(Operator &op)
|
||||
{
|
||||
op.on_attribute(name_.c_str(), value_, attributes_);
|
||||
}
|
||||
|
||||
using data_type_index = std::vector<utils::basic_type>;
|
||||
|
||||
private:
|
||||
static const data_type_index data_type_index_;
|
||||
|
||||
std::string name_;
|
||||
std::string table_;
|
||||
int index_{-1};
|
||||
utils::field_attributes attributes_;
|
||||
null_option null_option_{null_option::NOT_NULL};
|
||||
utils::value value_;
|
||||
std::shared_ptr<attribute_definition> reference_column_;
|
||||
};
|
||||
|
||||
/**
|
||||
* User defined literal to have a shortcut creating a column object
|
||||
* @param name Name of the column
|
||||
* @param type
|
||||
* @param attr Length of the column name
|
||||
* @param null_opt
|
||||
* @return A column object with given name
|
||||
*/
|
||||
attribute_definition make_column(const std::string &name, utils::basic_type type, utils::field_attributes attr = utils::null_attributes, null_option null_opt = null_option::NOT_NULL);
|
||||
|
||||
template < typename Type >
|
||||
attribute_definition make_column(const std::string &name, utils::field_attributes attr = utils::null_attributes, null_option null_opt = null_option::NOT_NULL)
|
||||
{
|
||||
return make_column(name, utils::data_type_traits<Type>::type(0), attr, null_opt);
|
||||
}
|
||||
template <>
|
||||
attribute_definition make_column<std::string>(const std::string &name, utils::field_attributes attr, null_option null_opt);
|
||||
|
||||
template < typename Type >
|
||||
attribute_definition make_pk_column(const std::string &name, size_t size = 0)
|
||||
{
|
||||
return make_column<Type>(name, { size, utils::constraints::PRIMARY_KEY });
|
||||
}
|
||||
|
||||
template <>
|
||||
attribute_definition make_pk_column<std::string>(const std::string &name, size_t size);
|
||||
|
||||
template < typename Type >
|
||||
attribute_definition make_fk_column(const std::string &name, size_t size, const std::shared_ptr<attribute_definition> &ref_column) {
|
||||
return {name, utils::data_type_traits<Type>::type(size), ref_column, { size, utils::constraints::FOREIGN_KEY }};
|
||||
}
|
||||
|
||||
template < typename Type >
|
||||
[[maybe_unused]] attribute_definition make_fk_column(const std::string &name, const std::shared_ptr<attribute_definition> &ref_column)
|
||||
{
|
||||
return {name, utils::data_type_traits<Type>::type(0), 0, ref_column, { 0, utils::constraints::FOREIGN_KEY }, null_option::NOT_NULL};
|
||||
}
|
||||
|
||||
template <>
|
||||
[[maybe_unused]] attribute_definition make_fk_column<std::string>(const std::string &name, size_t size, const std::shared_ptr<attribute_definition> &ref_column);
|
||||
|
||||
template < typename Type >
|
||||
[[maybe_unused]] attribute_definition make_fk_column(const std::string &name, size_t size, const std::string &ref_table_name, const std::string &ref_column_name) {
|
||||
return {
|
||||
name, utils::data_type_traits<Type>::type(size), 0,
|
||||
std::make_shared<attribute_definition>(ref_column_name, ref_table_name, utils::data_type_traits<Type>::type(size), utils::constraints::FOREIGN_KEY),
|
||||
{ 0, utils::constraints::FOREIGN_KEY }, null_option::NOT_NULL
|
||||
};
|
||||
}
|
||||
|
||||
template < typename Type >
|
||||
[[maybe_unused]] attribute_definition make_fk_column(const std::string &name, const std::string &ref_table_name, const std::string &ref_column_name) {
|
||||
return {
|
||||
name, utils::data_type_traits<Type>::type(0), 0,
|
||||
std::make_shared<attribute_definition>(ref_column_name, ref_table_name, utils::data_type_traits<Type>::type(0), utils::constraints::FOREIGN_KEY),
|
||||
{ 0, utils::constraints::FOREIGN_KEY }, null_option::NOT_NULL
|
||||
};
|
||||
}
|
||||
|
||||
template <>
|
||||
[[maybe_unused]] attribute_definition make_fk_column<std::string>(const std::string &name, const std::string &ref_table_name, const std::string &ref_column_name);
|
||||
|
||||
template <>
|
||||
[[maybe_unused]] attribute_definition make_fk_column<std::string>(const std::string &name, size_t size, const std::string &ref_table_name, const std::string &ref_column_name);
|
||||
|
||||
}
|
||||
|
||||
#endif //QUERY_COLUMN_DEFINITION_HPP
|
||||
@@ -0,0 +1,140 @@
|
||||
#ifndef QUERY_COLUMN_DEFINITION_GENERATOR_HPP
|
||||
#define QUERY_COLUMN_DEFINITION_GENERATOR_HPP
|
||||
|
||||
#include "attribute_definition.hpp"
|
||||
|
||||
#include "matador/utils/access.hpp"
|
||||
#include "matador/utils/data_type_traits.hpp"
|
||||
#include "matador/utils/error.hpp"
|
||||
#include "matador/utils/field_attributes.hpp"
|
||||
#include "matador/utils/foreign_attributes.hpp"
|
||||
|
||||
#include <typeindex>
|
||||
#include <vector>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
class schema;
|
||||
|
||||
class fk_attribute_generator
|
||||
{
|
||||
public:
|
||||
fk_attribute_generator() = default;
|
||||
|
||||
template<class Type>
|
||||
attribute_definition generate(const char *id, Type &x, const std::shared_ptr<attribute_definition> &ref_column) {
|
||||
access::process(*this, x);
|
||||
return attribute_definition{id, type_, 0, ref_column, {utils::constraints::FOREIGN_KEY }, null_option::NOT_NULL};
|
||||
}
|
||||
|
||||
template<typename ValueType>
|
||||
void on_primary_key(const char *, ValueType &/*pk*/, std::enable_if_t<std::is_integral_v<ValueType> && !std::is_same_v<bool, ValueType>>* = nullptr) {
|
||||
type_ = utils::data_type_traits<ValueType>::type(0);
|
||||
}
|
||||
void on_primary_key(const char * /*id*/, std::string &/*pk*/, size_t size);
|
||||
static void on_revision(const char * /*id*/, unsigned long long &/*rev*/) {}
|
||||
template < class Type >
|
||||
static void on_attribute(const char * /*id*/, Type &/*x*/, const utils::field_attributes &/*attr*/ = utils::null_attributes) {}
|
||||
static void on_attribute(const char * /*id*/, char * /*x*/, const utils::field_attributes &/*attr*/ = utils::null_attributes) {}
|
||||
template<class Pointer>
|
||||
static void on_belongs_to(const char * /*id*/, Pointer &/*x*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class Pointer>
|
||||
static void on_has_one(const char * /*id*/, Pointer &/*x*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class ContainerType>
|
||||
static void on_has_many(const char * /*id*/, ContainerType &, const char *, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class ContainerType>
|
||||
static void on_has_many_to_many(const char * /*id*/, ContainerType & /*cont*/, const char * /*join_column*/, const char * /*inverse_join_column*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class ContainerType>
|
||||
static void on_has_many_to_many(const char * /*id*/, ContainerType & /*cont*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
|
||||
private:
|
||||
utils::basic_type type_{};
|
||||
};
|
||||
|
||||
class attribute_definition_generator final {
|
||||
private:
|
||||
attribute_definition_generator(std::vector<attribute_definition> &columns, const schema &repo);
|
||||
|
||||
public:
|
||||
~attribute_definition_generator() = default;
|
||||
|
||||
template < class Type >
|
||||
static std::vector<attribute_definition> generate(const schema &repo)
|
||||
{
|
||||
std::vector<attribute_definition> columns;
|
||||
attribute_definition_generator gen(columns, repo);
|
||||
Type obj;
|
||||
access::process(gen, obj);
|
||||
return columns;
|
||||
}
|
||||
|
||||
template < class V >
|
||||
void on_primary_key(const char *, V &x, std::enable_if_t<std::is_integral_v<V> && !std::is_same_v<bool, V>>* = nullptr);
|
||||
void on_primary_key(const char *id, std::string &pk, size_t size);
|
||||
void on_revision(const char *id, uint64_t &rev);
|
||||
|
||||
template<typename Type>
|
||||
void on_attribute(const char *id, Type &x, const utils::field_attributes &attr = utils::null_attributes);
|
||||
|
||||
template<typename Type>
|
||||
void on_attribute(const char *id, std::optional<Type> &x, const utils::field_attributes &attr = utils::null_attributes);
|
||||
|
||||
template<class Pointer>
|
||||
void on_belongs_to(const char *id, Pointer &x, const utils::foreign_attributes &/*attr*/) {
|
||||
on_foreign_key(id, x);
|
||||
}
|
||||
template<class Pointer>
|
||||
void on_has_one(const char *id, Pointer &x, const utils::foreign_attributes &/*attr*/) {
|
||||
on_foreign_key(id, x);
|
||||
}
|
||||
|
||||
template <class Pointer>
|
||||
void on_foreign_key(const char *id, Pointer &x) {
|
||||
if (const auto result = determine_foreign_ref(std::type_index(typeid(typename Pointer::value_type)))) {
|
||||
if (x.empty()) {
|
||||
typename Pointer::value_type temp_val;
|
||||
columns_.push_back(fk_column_generator_.generate(id, temp_val, *result));
|
||||
} else {
|
||||
columns_.push_back(fk_column_generator_.generate(id, *x, *result));
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
template<class ContainerType>
|
||||
static void on_has_many(const char * /*id*/, ContainerType &, const char *, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class ContainerType>
|
||||
static void on_has_many_to_many(const char * /*id*/, ContainerType & /*cont*/, const char * /*join_column*/, const char * /*inverse_join_column*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class ContainerType>
|
||||
static void on_has_many_to_many(const char * /*id*/, ContainerType & /*cont*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
|
||||
private:
|
||||
[[nodiscard]] utils::result<std::shared_ptr<attribute_definition>, utils::error> determine_foreign_ref(const std::type_index &ti) const;
|
||||
|
||||
private:
|
||||
size_t index_ = 0;
|
||||
std::vector<attribute_definition> &columns_;
|
||||
const schema &repo_;
|
||||
|
||||
fk_attribute_generator fk_column_generator_;
|
||||
};
|
||||
|
||||
template<typename V>
|
||||
void attribute_definition_generator::on_primary_key(const char *id, V &x, std::enable_if_t<std::is_integral_v<V> && !std::is_same_v<bool, V>>*)
|
||||
{
|
||||
on_attribute(id, x, { utils::constraints::PRIMARY_KEY });
|
||||
}
|
||||
|
||||
template<typename Type>
|
||||
void attribute_definition_generator::on_attribute(const char *id, Type &x, const utils::field_attributes &attr)
|
||||
{
|
||||
columns_.emplace_back(id, x, attr, null_option::NOT_NULL);
|
||||
}
|
||||
|
||||
template<typename Type>
|
||||
void attribute_definition_generator::on_attribute(const char *id, std::optional<Type> & /*x*/, const utils::field_attributes &attr)
|
||||
{
|
||||
columns_.emplace_back(id, utils::data_type_traits<Type>::type(attr.size()), attr, null_option::NULLABLE);
|
||||
}
|
||||
|
||||
}
|
||||
#endif //QUERY_COLUMN_DEFINITION_GENERATOR_HPP
|
||||
@@ -0,0 +1,39 @@
|
||||
#ifndef BASIC_PROTOTYPE_INFO_HPP
|
||||
#define BASIC_PROTOTYPE_INFO_HPP
|
||||
|
||||
#include "matador/object/object_definition.hpp"
|
||||
#include "matador/utils/identifier.hpp"
|
||||
|
||||
#include <string>
|
||||
#include <typeindex>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
class schema_node;
|
||||
|
||||
class basic_object_info {
|
||||
public:
|
||||
virtual ~basic_object_info() = default;
|
||||
|
||||
[[nodiscard]] std::type_index type_index() const;
|
||||
[[nodiscard]] std::string name() const;
|
||||
[[nodiscard]] const object_definition& definition() const;
|
||||
[[nodiscard]] std::shared_ptr<attribute_definition> reference_column() const;
|
||||
|
||||
protected:
|
||||
basic_object_info(std::shared_ptr<schema_node> node, std::type_index type_index, utils::identifier &&pk, std::shared_ptr<attribute_definition> &&pk_column, object_definition &&definition);
|
||||
basic_object_info(std::shared_ptr<schema_node> node, std::type_index type_index, utils::identifier &&pk, std::shared_ptr<attribute_definition> &&pk_column);
|
||||
|
||||
protected:
|
||||
std::shared_ptr<schema_node> node_; /**< prototype node of the represented object type */
|
||||
std::type_index type_index_; /**< type index of the represented object type */
|
||||
object_definition definition_;
|
||||
std::optional<utils::identifier> identifier_;
|
||||
std::shared_ptr<attribute_definition> pk_column_;
|
||||
};
|
||||
|
||||
using basic_object_info_ref = std::reference_wrapper<const basic_object_info>;
|
||||
|
||||
}
|
||||
|
||||
#endif //BASIC_PROTOTYPE_INFO_HPP
|
||||
@@ -0,0 +1,17 @@
|
||||
#ifndef COLLECTION_HPP
|
||||
#define COLLECTION_HPP
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
template < class Type >
|
||||
class collection {
|
||||
public:
|
||||
|
||||
private:
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
#endif //COLLECTION_HPP
|
||||
@@ -0,0 +1,14 @@
|
||||
#ifndef DICTIONARY_HPP
|
||||
#define DICTIONARY_HPP
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
template < class Key, class Value >
|
||||
class dictionary {
|
||||
public:
|
||||
|
||||
private:
|
||||
};
|
||||
|
||||
}
|
||||
#endif //DICTIONARY_HPP
|
||||
@@ -0,0 +1,32 @@
|
||||
#ifndef OBJECT_ERROR_CODE_HPP
|
||||
#define OBJECT_ERROR_CODE_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <system_error>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
enum class error_code : uint8_t {
|
||||
OK = 0,
|
||||
NodeNotFound = 1,
|
||||
NodeAlreadyExists = 2,
|
||||
Failure,
|
||||
};
|
||||
|
||||
class object_category_impl final : public std::error_category
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] const char* name() const noexcept override;
|
||||
[[nodiscard]] std::string message(int ev) const override;
|
||||
};
|
||||
|
||||
const std::error_category& object_category();
|
||||
std::error_code make_error_code(error_code e);
|
||||
std::error_condition make_error_condition(error_code e);
|
||||
|
||||
}
|
||||
|
||||
template <>
|
||||
struct std::is_error_code_enum<matador::object::error_code> : true_type {};
|
||||
|
||||
#endif //OBJECT_ERROR_CODE_HPP
|
||||
@@ -0,0 +1,37 @@
|
||||
#ifndef QUERY_HAS_MANY_TO_MANY_RELATION_HPP
|
||||
#define QUERY_HAS_MANY_TO_MANY_RELATION_HPP
|
||||
|
||||
#include "matador/object/object_ptr.hpp"
|
||||
|
||||
#include "matador/utils/access.hpp"
|
||||
#include "matador/utils/foreign_attributes.hpp"
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
template < class LocalType, class ForeignType >
|
||||
class many_to_many_relation {
|
||||
public:
|
||||
many_to_many_relation() = default;
|
||||
many_to_many_relation(std::string local_name, std::string remote_name)
|
||||
: local_name_(std::move(local_name))
|
||||
, remote_name_(std::move(remote_name)) {}
|
||||
|
||||
template<class Operator>
|
||||
void process(Operator &op) {
|
||||
namespace field = matador::access;
|
||||
field::belongs_to(op, local_name_.c_str(), local_, utils::default_foreign_attributes);
|
||||
field::belongs_to(op, remote_name_.c_str(), remote_, utils::default_foreign_attributes);
|
||||
}
|
||||
|
||||
object_ptr<LocalType> local() const { return local_; }
|
||||
object_ptr<LocalType> remote() const { return remote_; }
|
||||
|
||||
private:
|
||||
std::string local_name_;
|
||||
std::string remote_name_;
|
||||
object_ptr<LocalType> local_;
|
||||
object_ptr<ForeignType> remote_;
|
||||
};
|
||||
|
||||
}
|
||||
#endif //QUERY_HAS_MANY_TO_MANY_RELATION_HPP
|
||||
@@ -0,0 +1,70 @@
|
||||
#ifndef QUERY_TABLE_DEFINITION_HPP
|
||||
#define QUERY_TABLE_DEFINITION_HPP
|
||||
|
||||
#include "matador/object/attribute_definition.hpp"
|
||||
|
||||
#include <unordered_map>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
class object_definition final {
|
||||
private:
|
||||
using column_by_index = std::vector<attribute_definition>;
|
||||
using column_index_pair = std::pair<std::reference_wrapper<attribute_definition>, column_by_index::difference_type>;
|
||||
using column_by_name_map = std::unordered_map<std::string, column_index_pair>;
|
||||
|
||||
public:
|
||||
using iterator = column_by_index::iterator;
|
||||
using const_iterator = column_by_index::const_iterator;
|
||||
|
||||
object_definition() = default;
|
||||
object_definition(std::initializer_list<attribute_definition> columns);
|
||||
explicit object_definition(const std::vector<attribute_definition> &columns);
|
||||
object_definition(const object_definition &x);
|
||||
object_definition& operator=(const object_definition &x);
|
||||
object_definition(object_definition&&) noexcept = default;
|
||||
object_definition& operator=(object_definition&&) noexcept = default;
|
||||
~object_definition() = default;
|
||||
|
||||
[[nodiscard]] bool has_primary_key() const;
|
||||
[[nodiscard]] std::optional<attribute_definition> primary_key() const;
|
||||
|
||||
template < typename Type >
|
||||
void append(const std::string &name, long size = -1) {
|
||||
append(make_column<Type>(name, size));
|
||||
}
|
||||
void append(attribute_definition col);
|
||||
|
||||
[[nodiscard]] const std::vector<attribute_definition>& columns() const;
|
||||
|
||||
[[nodiscard]] const attribute_definition& at(const std::string &name) const;
|
||||
[[nodiscard]] const attribute_definition& at(size_t index) const;
|
||||
|
||||
iterator find(const std::string &column_name);
|
||||
[[nodiscard]] const_iterator find(const std::string &column_name) const;
|
||||
|
||||
iterator begin();
|
||||
[[nodiscard]] const_iterator begin() const;
|
||||
[[nodiscard]] const_iterator cbegin() const;
|
||||
|
||||
iterator end();
|
||||
[[nodiscard]] const_iterator end() const;
|
||||
[[nodiscard]] const_iterator cend() const;
|
||||
|
||||
[[nodiscard]] size_t size() const;
|
||||
[[nodiscard]] bool empty() const;
|
||||
void clear();
|
||||
|
||||
private:
|
||||
void init();
|
||||
void add_to_map(attribute_definition &col, size_t index);
|
||||
|
||||
private:
|
||||
column_by_index columns_;
|
||||
column_by_name_map columns_by_name_;
|
||||
|
||||
int pk_index_{-1};
|
||||
};
|
||||
|
||||
}
|
||||
#endif //QUERY_TABLE_DEFINITION_HPP
|
||||
@@ -0,0 +1,41 @@
|
||||
#ifndef OBJECT_INFO_HPP
|
||||
#define OBJECT_INFO_HPP
|
||||
|
||||
#include "matador/object/basic_object_info.hpp"
|
||||
#include "matador/object/object_definition.hpp"
|
||||
|
||||
namespace matador::object {
|
||||
class schema_node;
|
||||
|
||||
template<typename Type>
|
||||
class object_info final : public basic_object_info {
|
||||
public:
|
||||
explicit object_info(const std::shared_ptr<schema_node>& node,
|
||||
std::shared_ptr<attribute_definition> &&ref_column)
|
||||
: basic_object_info(node, typeid(Type), {}, std::move(ref_column), {}) {
|
||||
}
|
||||
explicit object_info(const std::shared_ptr<schema_node>& node,
|
||||
utils::identifier &&pk,
|
||||
std::shared_ptr<attribute_definition> &&ref_column,
|
||||
object_definition &&definition)
|
||||
: basic_object_info(node, typeid(Type), std::move(pk), std::move(ref_column), std::move(definition)) {
|
||||
}
|
||||
|
||||
const Type &prototype() const { return prototype_; }
|
||||
|
||||
private:
|
||||
Type prototype_;
|
||||
};
|
||||
|
||||
template<typename Type>
|
||||
using object_info_ref = std::reference_wrapper<const object_info<Type>>;
|
||||
|
||||
namespace detail {
|
||||
struct null_type {
|
||||
};
|
||||
}
|
||||
|
||||
using null_info = object_info<detail::null_type>;
|
||||
}
|
||||
|
||||
#endif //OBJECT_INFO_HPP
|
||||
@@ -0,0 +1,42 @@
|
||||
#ifndef OBJECT_PROXY_HPP
|
||||
#define OBJECT_PROXY_HPP
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
class basic_object_proxy {
|
||||
public:
|
||||
virtual ~basic_object_proxy() = default;
|
||||
|
||||
[[nodiscard]] virtual void *get() const = 0;
|
||||
};
|
||||
|
||||
template<class Type>
|
||||
class object_proxy : public basic_object_proxy {
|
||||
public:
|
||||
object_proxy() = default;
|
||||
explicit object_proxy(Type* obj)
|
||||
: obj_(obj) {}
|
||||
explicit object_proxy(std::unique_ptr<Type> obj)
|
||||
: obj_(std::move(obj)) {}
|
||||
|
||||
[[nodiscard]] void *get() const override { return static_cast<void*>(obj_.get()); }
|
||||
|
||||
Type* operator->() const { return obj_.get(); }
|
||||
Type& operator*() { return *obj_; }
|
||||
const Type& operator*() const { return *obj_; }
|
||||
|
||||
Type* pointer() const { return obj_.get(); }
|
||||
|
||||
Type& ref() { return *obj_; }
|
||||
const Type& ref() const { return *obj_; }
|
||||
|
||||
void reset(Type* obj) { obj_.reset(obj); }
|
||||
|
||||
private:
|
||||
std::unique_ptr<Type> obj_{};
|
||||
};
|
||||
|
||||
}
|
||||
#endif //OBJECT_PROXY_HPP
|
||||
@@ -0,0 +1,50 @@
|
||||
#ifndef OBJECT_PTR_HPP
|
||||
#define OBJECT_PTR_HPP
|
||||
|
||||
#include "matador/utils/identifier.hpp"
|
||||
|
||||
#include "matador/object/object_proxy.hpp"
|
||||
#include "matador/object/primary_key_resolver.hpp"
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace matador::object {
|
||||
template <typename Type>
|
||||
class object_ptr {
|
||||
public:
|
||||
object_ptr()
|
||||
: ptr_(std::make_shared<object_proxy<Type>>()) {}
|
||||
explicit object_ptr(Type *obj)
|
||||
: ptr_(std::make_shared<object_proxy<Type>>(obj))
|
||||
, pk_(primary_key_resolver::resolve_object(*obj).pk) {}
|
||||
object_ptr(const object_ptr &other) : ptr_(other.ptr_) {}
|
||||
object_ptr(object_ptr &&other) noexcept : ptr_(std::move(other.ptr_)) {}
|
||||
object_ptr &operator=(const object_ptr &other) = default;
|
||||
object_ptr &operator=(object_ptr &&other) = default;
|
||||
|
||||
using value_type = Type;
|
||||
Type* operator->() const { return ptr_->pointer(); }
|
||||
Type& operator*() { return ptr_->ref(); }
|
||||
const Type& operator*() const { return ptr_->ref(); }
|
||||
|
||||
[[nodiscard]] bool empty() const { return ptr_->pointer() == nullptr; }
|
||||
void reset(Type *obj) {
|
||||
ptr_->reset(obj);
|
||||
pk_ = primary_key_resolver::resolve_object(*obj).pk;
|
||||
}
|
||||
|
||||
Type* get() const { return static_cast<Type*>(ptr_->pointer()); }
|
||||
|
||||
operator bool() { return valid(); }
|
||||
bool valid() { return ptr_ != nullptr; }
|
||||
|
||||
[[nodiscard]] const utils::identifier& primary_key() const { return pk_; }
|
||||
void primary_key(const utils::identifier &pk) { pk_ = pk; }
|
||||
private:
|
||||
std::shared_ptr<object_proxy<Type>> ptr_{};
|
||||
utils::identifier pk_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif //OBJECT_PTR_HPP
|
||||
@@ -0,0 +1,72 @@
|
||||
#ifndef PRIMARY_KEY_RESOLVER_HPP
|
||||
#define PRIMARY_KEY_RESOLVER_HPP
|
||||
|
||||
#include "matador/utils/access.hpp"
|
||||
#include "matador/utils/field_attributes.hpp"
|
||||
#include "matador/utils/foreign_attributes.hpp"
|
||||
#include "matador/utils/identifier.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
struct primary_key_info {
|
||||
std::string pk_column_name;
|
||||
utils::basic_type type;
|
||||
utils::identifier pk;
|
||||
};
|
||||
|
||||
class primary_key_resolver final {
|
||||
public:
|
||||
template <typename Type>
|
||||
primary_key_info resolve() {
|
||||
Type obj;
|
||||
|
||||
return resolve(obj);
|
||||
}
|
||||
|
||||
template <typename Type>
|
||||
primary_key_info resolve(const Type& obj) {
|
||||
access::process(*this, obj);
|
||||
|
||||
return primary_key_info_;
|
||||
}
|
||||
|
||||
template <typename Type>
|
||||
static primary_key_info resolve_object(const Type& obj) {
|
||||
primary_key_resolver resolver;
|
||||
return resolver.resolve(obj);
|
||||
}
|
||||
|
||||
template < class Type >
|
||||
void on_primary_key(const char *id, Type &pk, std::enable_if_t<std::is_integral_v<Type> && !std::is_same_v<bool, Type>>* = nullptr) {
|
||||
primary_key_info_.pk_column_name = id;
|
||||
primary_key_info_.type = utils::data_type_traits<Type>::type();
|
||||
primary_key_info_.pk = pk;
|
||||
}
|
||||
|
||||
void on_primary_key(const char *id, const std::string &pk, size_t size);
|
||||
|
||||
static void on_revision(const char * /*id*/, uint64_t &/*rev*/) {}
|
||||
template<typename Type>
|
||||
static void on_attribute(const char * /*id*/, Type &/*val*/, const utils::field_attributes &/*attr*/ = utils::null_attributes) {}
|
||||
template<class Pointer>
|
||||
static void on_belongs_to(const char * /*id*/, Pointer &/*val*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class Pointer>
|
||||
static void on_has_one(const char * /*id*/, Pointer &/*val*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class ContainerType>
|
||||
static void on_has_many(const char * /*id*/, ContainerType &/*col*/, const char *, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class ContainerType>
|
||||
static void on_has_many_to_many(const char * /*id*/, ContainerType &/*col*/, const char * /*join_column*/, const char * /*inverse_join_column*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class ContainerType>
|
||||
static void on_has_many_to_many(const char * /*id*/, ContainerType &/*col*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
|
||||
private:
|
||||
primary_key_info primary_key_info_{};
|
||||
};
|
||||
|
||||
}
|
||||
#endif //PRIMARY_KEY_RESOLVER_HPP
|
||||
@@ -0,0 +1,222 @@
|
||||
#ifndef SCHEMA_HPP
|
||||
#define SCHEMA_HPP
|
||||
|
||||
#include "matador/object/primary_key_resolver.hpp"
|
||||
#include "matador/object/error_code.hpp"
|
||||
#include "matador/object/schema_node.hpp"
|
||||
#include "matador/object/schema_node_iterator.hpp"
|
||||
|
||||
#include "matador/utils/result.hpp"
|
||||
#include "matador/utils/error.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <stack>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
utils::error make_error(error_code ec, const std::string& msg);
|
||||
|
||||
class schema;
|
||||
|
||||
template<typename Type>
|
||||
class type_analyzer final {
|
||||
public:
|
||||
using value_type = Type;
|
||||
|
||||
static void prepare_expected_nodes(schema &scm) {
|
||||
type_analyzer analyzer(scm);
|
||||
|
||||
Type obj;
|
||||
access::process(analyzer, obj);
|
||||
}
|
||||
|
||||
template < class PrimaryKeyType >
|
||||
void on_primary_key(const char * /*id*/, PrimaryKeyType &/*pk*/, std::enable_if_t<std::is_integral_v<PrimaryKeyType> && !std::is_same_v<bool, PrimaryKeyType>>* = nullptr) {}
|
||||
void on_primary_key(const char * /*id*/, std::string &/*pk*/, size_t /*size*/) {}
|
||||
void on_revision(const char * /*id*/, uint64_t &/*rev*/) {}
|
||||
|
||||
template<typename AttributeType>
|
||||
void on_attribute(const char * /*id*/, AttributeType &/*val*/, const utils::field_attributes &/*attr*/ = utils::null_attributes) {}
|
||||
|
||||
template<typename AttributeType>
|
||||
void on_attribute(const char * /*id*/, std::optional<AttributeType> &/*val*/, const utils::field_attributes &/*attr*/ = utils::null_attributes) {}
|
||||
|
||||
template<class ForeignPointerType>
|
||||
void on_belongs_to(const char * /*id*/, ForeignPointerType &/*obj*/, const utils::foreign_attributes &/*attr*/) {
|
||||
on_foreign_key<ForeignPointerType>();
|
||||
}
|
||||
template<class ForeignPointerType>
|
||||
void on_has_one(const char * /*id*/, ForeignPointerType &/*obj*/, const utils::foreign_attributes &/*attr*/) {
|
||||
on_foreign_key<ForeignPointerType>();
|
||||
}
|
||||
|
||||
template<class CollectionType>
|
||||
void on_has_many(const char * /*id*/, CollectionType &, const char *, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class CollectionType>
|
||||
void on_has_many_to_many(const char * /*id*/, CollectionType &/*col*/, const char * /*join_column*/, const char * /*inverse_join_column*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
template<class ContainerType>
|
||||
void on_has_many_to_many(const char * /*id*/, ContainerType &/*col*/, const utils::foreign_attributes &/*attr*/) {}
|
||||
|
||||
private:
|
||||
template<class ForeignPointerType>
|
||||
void on_foreign_key();
|
||||
|
||||
private:
|
||||
explicit type_analyzer(schema& schema)
|
||||
: schema_(schema) {};
|
||||
|
||||
|
||||
private:
|
||||
schema &schema_;
|
||||
};
|
||||
|
||||
|
||||
class schema {
|
||||
public:
|
||||
typedef const_schema_node_iterator const_iterator; /**< Shortcut for the list const iterator. */
|
||||
|
||||
/**
|
||||
* Creates an empty schema
|
||||
*/
|
||||
explicit schema( std::string name = "");
|
||||
|
||||
template <typename Type>
|
||||
[[nodiscard]] utils::result<void, utils::error> attach(const std::string& name, const std::string &parent = "") {
|
||||
if (has_node(name)) {
|
||||
return utils::failure(make_error(error_code::NodeAlreadyExists, "Node '" + name + "' already exists"));
|
||||
}
|
||||
if (const auto it = expected_node_map_.find(typeid(Type)); it != expected_node_map_.end()) {
|
||||
const auto node = it->second;
|
||||
expected_node_map_.erase(it);
|
||||
|
||||
node->update_name(name);
|
||||
|
||||
node_map_.insert({node->name(), node})/*.first*/;
|
||||
type_index_node_map_.insert({node->type_index(), node});
|
||||
} else {
|
||||
// analyze node (collect unknown types by type index)
|
||||
type_analyzer<Type>::prepare_expected_nodes(*this);
|
||||
|
||||
const auto node = schema_node::make_node<Type>(*this, name);
|
||||
if (auto result = attach_node(node, parent); !result) {
|
||||
return utils::failure(result.err());
|
||||
}
|
||||
}
|
||||
return utils::ok<void>();
|
||||
}
|
||||
|
||||
template <typename Type, typename ParentType>
|
||||
[[nodiscard]] utils::result<void, utils::error> attach(const std::string name) {
|
||||
const auto ti = std::type_index(typeid(ParentType));
|
||||
auto result = find_node(ti);
|
||||
if (!result) {
|
||||
return utils::failure(make_error(error_code::NodeNotFound, "Parent node '" + std::string(ti.name()) + "' not found"));
|
||||
}
|
||||
|
||||
return attach<Type>(name, (*result)->name());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the first schema node.
|
||||
*
|
||||
* @return The first schema node iterator.
|
||||
*/
|
||||
[[nodiscard]] const_iterator begin() const;
|
||||
|
||||
/**
|
||||
* Return the last schema node.
|
||||
*
|
||||
* @return The last schema node iterator.
|
||||
*/
|
||||
[[nodiscard]] const_iterator end() const;
|
||||
|
||||
/**
|
||||
* Returns true if the schema contains
|
||||
* no schema nodes.
|
||||
*
|
||||
* @return True if the schema is empty
|
||||
*/
|
||||
[[nodiscard]] bool empty() const;
|
||||
|
||||
/**
|
||||
* Returns the current number of the schema node.
|
||||
*
|
||||
* @return Number of schema nodes
|
||||
*/
|
||||
[[nodiscard]] size_t size() const;
|
||||
|
||||
/**
|
||||
* Returns the name of the schema.
|
||||
*
|
||||
* @return The name of the schema
|
||||
*/
|
||||
[[nodiscard]] std::string name() const;
|
||||
|
||||
template <typename Type>
|
||||
[[nodiscard]] utils::result<object_info_ref<Type>, utils::error> info() const {
|
||||
auto result = find_node(std::type_index(typeid(Type)));
|
||||
if (!result) {
|
||||
return utils::failure(result.err());
|
||||
}
|
||||
|
||||
return utils::ok(result.value()->info<Type>());
|
||||
}
|
||||
|
||||
template <typename Type>
|
||||
[[nodiscard]] utils::result<basic_object_info_ref, utils::error> basic_info() const {
|
||||
auto result = find_node(std::type_index(typeid(Type)));
|
||||
if (!result) {
|
||||
return utils::failure(result.err());
|
||||
}
|
||||
|
||||
return utils::ok(basic_object_info_ref{result.value()->basic_info()});
|
||||
}
|
||||
|
||||
[[nodiscard]] utils::result<std::shared_ptr<attribute_definition>, utils::error> reference(const std::type_index &type_index) const;
|
||||
|
||||
private:
|
||||
using node_ptr = std::shared_ptr<schema_node>;
|
||||
using t_node_map = std::unordered_map<std::string, node_ptr>;
|
||||
using t_type_index_node_map = std::unordered_map<std::type_index, node_ptr>;
|
||||
|
||||
[[nodiscard]] utils::result<std::shared_ptr<schema_node>, utils::error> attach_node(const std::shared_ptr<schema_node> &node,
|
||||
const std::string &parent);
|
||||
[[nodiscard]] utils::result<std::shared_ptr<schema_node>, utils::error> attach_node(const std::shared_ptr<schema_node> &node,
|
||||
const std::type_index &type_index);
|
||||
[[nodiscard]] utils::result<std::shared_ptr<schema_node>, utils::error> find_node(const std::string &name) const;
|
||||
[[nodiscard]] utils::result<std::shared_ptr<schema_node>, utils::error> find_node(const std::type_index &type_index) const;
|
||||
|
||||
[[nodiscard]] bool has_node(const std::string &name) const;
|
||||
[[nodiscard]] bool has_node(const std::type_index& index) const;
|
||||
[[nodiscard]] bool has_node(const std::type_index& index, const std::string &name) const;
|
||||
|
||||
static void push_back_child(const node_ptr &parent, const node_ptr &child);
|
||||
|
||||
private:
|
||||
template <typename Type>
|
||||
friend class type_analyzer;
|
||||
|
||||
std::string name_;
|
||||
std::shared_ptr<schema_node> root_;
|
||||
|
||||
t_node_map node_map_;
|
||||
t_type_index_node_map type_index_node_map_;
|
||||
t_type_index_node_map expected_node_map_;
|
||||
};
|
||||
|
||||
template<typename Type>
|
||||
template<class ForeignPointerType>
|
||||
void type_analyzer<Type>::on_foreign_key() {
|
||||
auto ti = std::type_index(typeid(typename ForeignPointerType::value_type));
|
||||
if (schema_.has_node(ti) || schema_.expected_node_map_.count(ti) > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
schema_.expected_node_map_.insert({ti, schema_node::make_node<typename ForeignPointerType::value_type>(schema_, ti.name())});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif //SCHEMA_HPP
|
||||
@@ -0,0 +1,81 @@
|
||||
#ifndef SCHEMA_NODE_HPP
|
||||
#define SCHEMA_NODE_HPP
|
||||
|
||||
#include "matador/object/attribute_definition_generator.hpp"
|
||||
#include "matador/object/object_info.hpp"
|
||||
#include "matador/object/primary_key_resolver.hpp"
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
class basic_object_info;
|
||||
class schema;
|
||||
|
||||
class schema_node final {
|
||||
public:
|
||||
using node_ptr = std::shared_ptr<schema_node>;
|
||||
|
||||
template < typename Type >
|
||||
static std::shared_ptr<schema_node> make_node(schema& tree, const std::string& name) {
|
||||
auto node = std::shared_ptr<schema_node>(new schema_node(tree, name));
|
||||
|
||||
primary_key_resolver resolver;
|
||||
auto pk_info = resolver.resolve<Type>();
|
||||
auto info = std::make_unique<object_info<Type>>(
|
||||
node,
|
||||
std::move(pk_info.pk),
|
||||
std::make_shared<attribute_definition>(pk_info.pk_column_name, name, pk_info.type, utils::constraints::FOREIGN_KEY),
|
||||
object_definition{attribute_definition_generator::generate<Type>(tree)}
|
||||
);
|
||||
node->info_ = std::move(info);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
static std::shared_ptr<schema_node> make_null_node(schema& tree);
|
||||
|
||||
schema_node(const schema_node& other) = delete;
|
||||
schema_node(schema_node&& other) = default;
|
||||
schema_node& operator=(const schema_node& other) = delete;
|
||||
schema_node& operator=(schema_node&& other) = delete;
|
||||
~schema_node() = default;
|
||||
|
||||
[[nodiscard]] std::string name() const;
|
||||
[[nodiscard]] std::type_index type_index() const;
|
||||
|
||||
[[nodiscard]] node_ptr next() const;
|
||||
[[nodiscard]] node_ptr prev() const;
|
||||
|
||||
[[nodiscard]] const basic_object_info& basic_info() const;
|
||||
|
||||
void update_name(const std::string& name);
|
||||
|
||||
template <typename Type>
|
||||
object_info_ref<Type> info() const {
|
||||
return std::ref(static_cast<const object_info<Type>&>(*info_));
|
||||
}
|
||||
|
||||
private:
|
||||
explicit schema_node(schema& tree);
|
||||
schema_node(schema& tree, std::string name);
|
||||
|
||||
private:
|
||||
friend class schema;
|
||||
friend class const_schema_node_iterator;
|
||||
|
||||
object::schema &schema_;
|
||||
std::unique_ptr<basic_object_info> info_;
|
||||
|
||||
std::shared_ptr<schema_node> parent_;
|
||||
std::shared_ptr<schema_node> previous_sibling_;
|
||||
std::shared_ptr<schema_node> next_sibling_;
|
||||
std::shared_ptr<schema_node> first_child_;
|
||||
std::shared_ptr<schema_node> last_child_;
|
||||
|
||||
std::string name_;
|
||||
size_t depth_{0};
|
||||
};
|
||||
|
||||
}
|
||||
#endif //SCHEMA_NODE_HPP
|
||||
@@ -0,0 +1,130 @@
|
||||
#ifndef SCHEMA_NODE_ITERATOR_HPP
|
||||
#define SCHEMA_NODE_ITERATOR_HPP
|
||||
|
||||
#include "matador/object/schema_node.hpp"
|
||||
|
||||
#include <iterator>
|
||||
|
||||
namespace matador::object {
|
||||
|
||||
class const_schema_node_iterator {
|
||||
public:
|
||||
using iterator_category = std::bidirectional_iterator_tag;
|
||||
using difference_type = std::ptrdiff_t;
|
||||
using value_type = schema_node;
|
||||
using pointer = value_type*;
|
||||
using reference = value_type&;
|
||||
|
||||
/**
|
||||
* Creates an empty iterator
|
||||
*/
|
||||
const_schema_node_iterator() = default;
|
||||
|
||||
/**
|
||||
* @brief Creates an iterator for a concrete type.
|
||||
*
|
||||
* This constructor creates an iterator for a concrete
|
||||
* type and a concrete object.
|
||||
*
|
||||
* @param node The schema node of the object
|
||||
*/
|
||||
explicit const_schema_node_iterator(std::shared_ptr<value_type> node);
|
||||
|
||||
/**
|
||||
* Copy from a given const_object_view_iterator.
|
||||
*
|
||||
* @param x The prototype_iterator to copy from.
|
||||
*/
|
||||
const_schema_node_iterator(const const_schema_node_iterator &x) = default;
|
||||
|
||||
/**
|
||||
* Assign from a given prototype_iterator.
|
||||
*
|
||||
* @param x The prototype_iterator to assign from.
|
||||
* @return The assigned prototype_iterator.
|
||||
*/
|
||||
const_schema_node_iterator& operator=(const const_schema_node_iterator &x) = default;
|
||||
|
||||
~const_schema_node_iterator() = default;
|
||||
|
||||
/**
|
||||
* @brief Compares this with another iterators.
|
||||
*
|
||||
* Compares this with another iterators. Returns true
|
||||
* if the iterators node prototype_type are the same.
|
||||
*
|
||||
* @param i The iterator to compare with.
|
||||
* @return True if the iterators are the same.
|
||||
*/
|
||||
bool operator==(const const_schema_node_iterator &i) const;
|
||||
|
||||
/**
|
||||
* @brief Compares this with another iterators.
|
||||
*
|
||||
* Compares this with another iterators. Returns true
|
||||
* if the iterators node prototype_node are not the same.
|
||||
*
|
||||
* @param i The iterator to compare with.
|
||||
* @return True if the iterators are not the same.
|
||||
*/
|
||||
bool operator!=(const const_schema_node_iterator &i) const;
|
||||
|
||||
/**
|
||||
* Pre increments the iterator
|
||||
*
|
||||
* @return Returns iterators successor.
|
||||
*/
|
||||
const_schema_node_iterator& operator++();
|
||||
|
||||
/**
|
||||
* Post increments the iterator
|
||||
*
|
||||
* @return Returns iterator before incrementing.
|
||||
*/
|
||||
const_schema_node_iterator operator++( int );
|
||||
|
||||
/**
|
||||
* Pre increments the iterator
|
||||
*
|
||||
* @return Returns iterators predecessor.
|
||||
*/
|
||||
const_schema_node_iterator& operator--();
|
||||
|
||||
/**
|
||||
* Post decrements the iterator
|
||||
*
|
||||
* @return Returns iterator before decrementing.
|
||||
*/
|
||||
const_schema_node_iterator operator--(int);
|
||||
|
||||
/**
|
||||
* Returns the pointer to the node.
|
||||
*
|
||||
* @return The pointer to the node.
|
||||
*/
|
||||
pointer operator->() const;
|
||||
|
||||
/**
|
||||
* Returns the node.
|
||||
*
|
||||
* @return The iterators underlying node.
|
||||
*/
|
||||
const reference operator*() const;
|
||||
|
||||
/**
|
||||
* Returns the pointer to the node.
|
||||
*
|
||||
* @return The pointer to the node.
|
||||
*/
|
||||
[[nodiscard]] pointer get() const;
|
||||
|
||||
private:
|
||||
void increment();
|
||||
void decrement();
|
||||
|
||||
private:
|
||||
std::shared_ptr<value_type> node_;
|
||||
};
|
||||
|
||||
}
|
||||
#endif //SCHEMA_NODE_ITERATOR_HPP
|
||||
@@ -0,0 +1,33 @@
|
||||
#ifndef ERROR_CODE_HPP
|
||||
#define ERROR_CODE_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <system_error>
|
||||
|
||||
namespace matador::orm {
|
||||
|
||||
enum class error_code : uint8_t {
|
||||
Ok = 0,
|
||||
NoConnectionAvailable,
|
||||
UnknownType,
|
||||
FailedToBuildQuery,
|
||||
FailedToFindObject
|
||||
};
|
||||
|
||||
class orm_category_impl final : public std::error_category
|
||||
{
|
||||
public:
|
||||
[[nodiscard]] const char* name() const noexcept override;
|
||||
[[nodiscard]] std::string message(int ev) const override;
|
||||
};
|
||||
|
||||
const std::error_category& orm_category();
|
||||
std::error_code make_error_code(error_code e);
|
||||
std::error_condition make_error_condition(error_code e);
|
||||
|
||||
}
|
||||
|
||||
template <>
|
||||
struct std::is_error_code_enum<matador::orm::error_code> : true_type {};
|
||||
|
||||
#endif //ERROR_CODE_HPP
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user