From 3070504e2f08aa161afd2b70a8cbea34dea61160 Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Wed, 18 Nov 2020 16:55:51 +0000 Subject: Clang format --- libdbpp/column.cpp | 81 ++++---- libdbpp/column.h | 216 ++++++++++++---------- libdbpp/command.cpp | 12 +- libdbpp/command.h | 305 +++++++++++++++---------------- libdbpp/command_fwd.h | 4 +- libdbpp/connection.cpp | 16 +- libdbpp/connection.h | 221 +++++++++++----------- libdbpp/connectionPool.cpp | 10 +- libdbpp/connectionPool.h | 57 +++--- libdbpp/connection_fwd.h | 1 - libdbpp/createMockDb.cpp | 17 +- libdbpp/dbTypes.cpp | 7 +- libdbpp/dbTypes.h | 48 ++--- libdbpp/error.h | 32 ++-- libdbpp/mockDatabase.cpp | 116 ++++++------ libdbpp/mockDatabase.h | 41 +++-- libdbpp/modifycommand.cpp | 6 +- libdbpp/modifycommand.h | 11 +- libdbpp/selectcommand.cpp | 41 ++--- libdbpp/selectcommand.h | 185 +++++++++---------- libdbpp/selectcommandUtil.impl.h | 66 ++++--- libdbpp/sqlParse.h | 67 ++++--- libdbpp/sqlParseImpl.cpp | 89 +++++---- libdbpp/sqlWriter.cpp | 6 +- libdbpp/sqlWriter.h | 45 +++-- libdbpp/tablepatch.cpp | 253 +++++++++++++------------ libdbpp/tablepatch.h | 81 ++++---- libdbpp/testCore.cpp | 160 +++++++++------- libdbpp/testCore.h | 22 +-- libdbpp/unittests/libdbpp-mysql | 2 +- libdbpp/unittests/libdbpp-odbc | 2 +- libdbpp/unittests/libdbpp-postgresql | 2 +- libdbpp/unittests/libdbpp-sqlite | 2 +- libdbpp/unittests/mockdb.cpp | 6 +- libdbpp/unittests/mockdb.h | 35 ++-- libdbpp/unittests/testConnection.cpp | 41 ++--- libdbpp/unittests/testConnectionPool.cpp | 18 +- libdbpp/unittests/testMock.cpp | 37 ++-- libdbpp/unittests/testParse.cpp | 107 +++++------ libdbpp/unittests/testPatch.cpp | 124 +++++++------ libdbpp/unittests/testUtils.cpp | 109 +++++------ 41 files changed, 1340 insertions(+), 1361 deletions(-) diff --git a/libdbpp/column.cpp b/libdbpp/column.cpp index 512d083..0f862de 100644 --- a/libdbpp/column.cpp +++ b/libdbpp/column.cpp @@ -1,49 +1,46 @@ #include "column.h" -#include #include -#include #include +#include +#include namespace DB { -Column::Column(const Glib::ustring & n, unsigned int i) : - colNo(i), - name(n.collate_key()) -{ -} - -Column::~Column() = default; - -static -std::string -demangle(const char * const mangled) -{ - std::unique_ptr r(abi::__cxa_demangle(mangled, nullptr, nullptr, nullptr), &free); - return &*r; -}; - -InvalidConversion::InvalidConversion(const char * const f, const char * const t) : from(demangle(f)), to(demangle(t)) { } + Column::Column(const Glib::ustring & n, unsigned int i) : colNo(i), name(n.collate_key()) { } + + Column::~Column() = default; + + static std::string + demangle(const char * const mangled) + { + std::unique_ptr r(abi::__cxa_demangle(mangled, nullptr, nullptr, nullptr), &free); + return &*r; + }; + + InvalidConversion::InvalidConversion(const char * const f, const char * const t) : + from(demangle(f)), to(demangle(t)) + { + } + + AdHocFormatter(InvalidConversionMsg, "Invalid conversion from column type (%?) to value type (%?)"); + std::string + InvalidConversion::message() const noexcept + { + return InvalidConversionMsg::get(from, to); + } + + UnexpectedNullValue::UnexpectedNullValue(const char * const t) : to(t) { } + + AdHocFormatter(UnexpectedNullValueMsg, "Unexpected null value in column expecting type (%?)"); + std::string + UnexpectedNullValue::message() const noexcept + { + return InvalidConversionMsg::get(to, to); + } + + void + DB::HandleField::blob(const DB::Blob &) + { + throw DB::ColumnTypeNotSupported(); + } -AdHocFormatter(InvalidConversionMsg, "Invalid conversion from column type (%?) to value type (%?)"); -std::string -InvalidConversion::message() const noexcept -{ - return InvalidConversionMsg::get(from, to); } - -UnexpectedNullValue::UnexpectedNullValue(const char * const t) : to(t) { } - -AdHocFormatter(UnexpectedNullValueMsg, "Unexpected null value in column expecting type (%?)"); -std::string -UnexpectedNullValue::message() const noexcept -{ - return InvalidConversionMsg::get(to, to); -} - -void -DB::HandleField::blob(const DB::Blob &) -{ - throw DB::ColumnTypeNotSupported(); -} - -} - diff --git a/libdbpp/column.h b/libdbpp/column.h index ecb1e41..4008a81 100644 --- a/libdbpp/column.h +++ b/libdbpp/column.h @@ -1,124 +1,152 @@ #ifndef DB_COLUMN_H #define DB_COLUMN_H -#include +#include "dbTypes.h" +#include "error.h" #include +#include +#include +#include #include #include #include -#include -#include "dbTypes.h" -#include "error.h" -#include namespace DB { /// Abstract class for something that can handle field data. See Column::apply. class DLL_PUBLIC HandleField { - public: - /// The field is null. - virtual void null() = 0; - /// The field contains text data. - virtual void string(std::string_view) = 0; - /// The field is an integer. - virtual void integer(int64_t) = 0; - /// The field is a boolean/bit. - virtual void boolean(bool) = 0; - /// The field is floating point/fixed point/numeric. - virtual void floatingpoint(double) = 0; - /// The field is an interval/duration/time span. - virtual void interval(const boost::posix_time::time_duration &) = 0; - /// The field is a timestamp/date/datetime. - virtual void timestamp(const boost::posix_time::ptime &) = 0; - /// The field is a BLOB. - virtual void blob(const Blob &); + public: + /// The field is null. + virtual void null() = 0; + /// The field contains text data. + virtual void string(std::string_view) = 0; + /// The field is an integer. + virtual void integer(int64_t) = 0; + /// The field is a boolean/bit. + virtual void boolean(bool) = 0; + /// The field is floating point/fixed point/numeric. + virtual void floatingpoint(double) = 0; + /// The field is an interval/duration/time span. + virtual void interval(const boost::posix_time::time_duration &) = 0; + /// The field is a timestamp/date/datetime. + virtual void timestamp(const boost::posix_time::ptime &) = 0; + /// The field is a BLOB. + virtual void blob(const Blob &); }; class Command; /// Represents a column in a result set and provides access to the current rows data. class DLL_PUBLIC Column { - public: - /// Creates a new column with the given name and ordinal. - Column(const Glib::ustring &, unsigned int); - virtual ~Column() = 0; - /// Standard special members - SPECIAL_MEMBERS_MOVE_RO(Column); + public: + /// Creates a new column with the given name and ordinal. + Column(const Glib::ustring &, unsigned int); + virtual ~Column() = 0; + /// Standard special members + SPECIAL_MEMBERS_MOVE_RO(Column); - /// Test if the current value is null. - [[nodiscard]] virtual bool isNull() const = 0; - /// Apply a field handler (any sub-class of HandleField) - virtual void apply(HandleField &) const = 0; + /// Test if the current value is null. + [[nodiscard]] virtual bool isNull() const = 0; + /// Apply a field handler (any sub-class of HandleField) + virtual void apply(HandleField &) const = 0; - /// Column handler dealing with trivial (sensible) type conversions - template - class Extract : public DB::HandleField { - private: - template struct is_optional { - static constexpr bool value = false; - static constexpr bool is_arithmetic = std::is_arithmetic::value; - }; - template struct is_optional> { - static constexpr bool value = true; - static constexpr bool is_arithmetic = std::is_arithmetic::value; - }; + /// Column handler dealing with trivial (sensible) type conversions + template class Extract : public DB::HandleField { + private: + template struct is_optional { + static constexpr bool value = false; + static constexpr bool is_arithmetic = std::is_arithmetic::value; + }; + template struct is_optional> { + static constexpr bool value = true; + static constexpr bool is_arithmetic = std::is_arithmetic::value; + }; - public: - /// Create an extrator given a target variable. - explicit Extract(T & t) : target(t) { } + public: + /// Create an extrator given a target variable. + explicit Extract(T & t) : target(t) { } - void floatingpoint(double v) override { (*this)(v); } - void integer(int64_t v) override { (*this)(v); } - void boolean(bool v) override { (*this)(v); } - void string(const std::string_view v) override { (*this)(v); } - void timestamp(const boost::posix_time::ptime & v) override { (*this)(v); } - void interval(const boost::posix_time::time_duration & v) override { (*this)(v); } - void blob(const Blob & v) override { (*this)(v); } - void null() override - { - if constexpr (is_optional::value) { - target.reset(); - } - else { - throw UnexpectedNullValue(typeid(T).name()); - } - } + void + floatingpoint(double v) override + { + (*this)(v); + } + void + integer(int64_t v) override + { + (*this)(v); + } + void + boolean(bool v) override + { + (*this)(v); + } + void + string(const std::string_view v) override + { + (*this)(v); + } + void + timestamp(const boost::posix_time::ptime & v) override + { + (*this)(v); + } + void + interval(const boost::posix_time::time_duration & v) override + { + (*this)(v); + } + void + blob(const Blob & v) override + { + (*this)(v); + } + void + null() override + { + if constexpr (is_optional::value) { + target.reset(); + } + else { + throw UnexpectedNullValue(typeid(T).name()); + } + } - /// Default call operation to [convert and] assign field value to target. - template - inline - void operator()(const D & v) - { - if constexpr (is_optional::is_arithmetic == std::is_arithmetic::value) { - if constexpr (std::is_assignable::value) { - target = v; - return; - } - if constexpr (std::is_convertible::value) { - target = (T)v; - return; - } - } - throw InvalidConversion(typeid(D).name(), typeid(T).name()); + /// Default call operation to [convert and] assign field value to target. + template + inline void + operator()(const D & v) + { + if constexpr (is_optional::is_arithmetic == std::is_arithmetic::value) { + if constexpr (std::is_assignable::value) { + target = v; + return; } + if constexpr (std::is_convertible::value) { + target = (T)v; + return; + } + } + throw InvalidConversion(typeid(D).name(), typeid(T).name()); + } - private: - T & target; - }; + private: + T & target; + }; - /// STL like extractor. - template - void operator>>(T & v) const - { - Extract e(v); - apply(e); - } + /// STL like extractor. + template + void + operator>>(T & v) const + { + Extract e(v); + apply(e); + } - /// This column's ordinal. - const unsigned int colNo; - /// This column's name. - const std::string name; + /// This column's ordinal. + const unsigned int colNo; + /// This column's name. + const std::string name; }; using ColumnPtr = std::unique_ptr; } #endif - diff --git a/libdbpp/command.cpp b/libdbpp/command.cpp index de2563d..b4eec6b 100644 --- a/libdbpp/command.cpp +++ b/libdbpp/command.cpp @@ -6,17 +6,11 @@ INSTANTIATEFACTORY(DB::CommandOptions, std::size_t, const DB::CommandOptionsMap NAMEDFACTORY("", DB::CommandOptions, DB::CommandOptionsFactory); PLUGINRESOLVER(DB::CommandOptionsFactory, DB::Connection::resolvePlugin); -DB::Command::Command(std::string s) : - sql(std::move(s)) -{ -} +DB::Command::Command(std::string s) : sql(std::move(s)) { } DB::Command::~Command() = default; -DB::CommandOptions::CommandOptions(std::size_t h, const CommandOptionsMap &) : - hash(h) -{ -} +DB::CommandOptions::CommandOptions(std::size_t h, const CommandOptionsMap &) : hash(h) { } bool DB::CommandOptions::isSet(const CommandOptionsMap & map, const std::string & key) @@ -35,7 +29,6 @@ DB::Command::bindParamS(unsigned int i, const char * const o) } } - void DB::Command::bindParamS(unsigned int i, char * const o) { @@ -52,4 +45,3 @@ DB::Command::bindParamBLOB(unsigned int, const Blob &) { throw ParameterTypeNotSupported(); } - diff --git a/libdbpp/command.h b/libdbpp/command.h index 4820569..1468e2b 100644 --- a/libdbpp/command.h +++ b/libdbpp/command.h @@ -2,16 +2,16 @@ #define DB_COMMAND_H #include "command_fwd.h" -#include +#include "dbTypes.h" +#include "error.h" #include -#include #include -#include +#include #include +#include +#include #include -#include "dbTypes.h" -#include "error.h" -#include +#include namespace DB { /// Exception thrown when binding a parameter of type the connector doesn't support. @@ -24,172 +24,169 @@ namespace DB { /// Represents the basic options that can be passed when creating new commands. class DLL_PUBLIC CommandOptions { - public: - CommandOptions() = default; - /// Constructor which populates the hash value only. - explicit CommandOptions(std::size_t hash, const CommandOptionsMap & = CommandOptionsMap()); - virtual ~CommandOptions() = default; - /// Standard special members - SPECIAL_MEMBERS_DEFAULT(CommandOptions); - - /// An (optional) hash of the SQL statement. - std::optional hash; - - protected: - /// Helper function to extract values from a CommandOptionsMap - template - static X get(const CommandOptionsMap & map, const Y & key, const X & def) - { - if (auto i = map.find(key); i != map.end()) { - if constexpr (std::is_convertible::value) { - return i->second; - } - else { - return boost::lexical_cast(i->second); - } + public: + CommandOptions() = default; + /// Constructor which populates the hash value only. + explicit CommandOptions(std::size_t hash, const CommandOptionsMap & = CommandOptionsMap()); + virtual ~CommandOptions() = default; + /// Standard special members + SPECIAL_MEMBERS_DEFAULT(CommandOptions); + + /// An (optional) hash of the SQL statement. + std::optional hash; + + protected: + /// Helper function to extract values from a CommandOptionsMap + template + static X + get(const CommandOptionsMap & map, const Y & key, const X & def) + { + if (auto i = map.find(key); i != map.end()) { + if constexpr (std::is_convertible::value) { + return i->second; + } + else { + return boost::lexical_cast(i->second); } - return def; } - /// Helper function to test if a value is set in a CommandOptionsMap - static bool isSet(const CommandOptionsMap & map, const std::string & key); + return def; + } + /// Helper function to test if a value is set in a CommandOptionsMap + static bool isSet(const CommandOptionsMap & map, const std::string & key); }; /// Represents the basics of any command to be executed against a database. class DLL_PUBLIC Command { - public: - /// Creates a new command from the given SQL. - explicit Command(std::string sql); - virtual ~Command() = 0; - - /// Standard special members - SPECIAL_MEMBERS_COPY_RO(Command); - - /// Bind an integer to parameter i. - virtual void bindParamI(unsigned int i, int val) = 0; - /// Bind an integer to parameter i. - virtual void bindParamI(unsigned int i, long val) = 0; - /// Bind an integer to parameter i. - virtual void bindParamI(unsigned int i, long long val) = 0; - /// Bind an integer to parameter i. - virtual void bindParamI(unsigned int i, unsigned int val) = 0; - /// Bind an integer to parameter i. - virtual void bindParamI(unsigned int i, unsigned long int val) = 0; - /// Bind an integer to parameter i. - virtual void bindParamI(unsigned int i, unsigned long long int val) = 0; - - /// Bind a boolean to parameter i. - virtual void bindParamB(unsigned int i, bool val) = 0; - - /// Bind a floating point number to parameter i. - virtual void bindParamF(unsigned int i, double val) = 0; - /// Bind a floating point number to parameter i. - virtual void bindParamF(unsigned int i, float val) = 0; - - /// Bind a string to parameter i. - virtual void bindParamS(unsigned int i, const Glib::ustring &) = 0; - /// Bind a string_view to parameter i. - virtual void bindParamS(unsigned int i, const std::string_view &) = 0; - /// Bind a string to parameter i (wraps string_view). - inline void bindParamS(unsigned int i, const std::string & v) - { - bindParamS(i, std::string_view(v)); + public: + /// Creates a new command from the given SQL. + explicit Command(std::string sql); + virtual ~Command() = 0; + + /// Standard special members + SPECIAL_MEMBERS_COPY_RO(Command); + + /// Bind an integer to parameter i. + virtual void bindParamI(unsigned int i, int val) = 0; + /// Bind an integer to parameter i. + virtual void bindParamI(unsigned int i, long val) = 0; + /// Bind an integer to parameter i. + virtual void bindParamI(unsigned int i, long long val) = 0; + /// Bind an integer to parameter i. + virtual void bindParamI(unsigned int i, unsigned int val) = 0; + /// Bind an integer to parameter i. + virtual void bindParamI(unsigned int i, unsigned long int val) = 0; + /// Bind an integer to parameter i. + virtual void bindParamI(unsigned int i, unsigned long long int val) = 0; + + /// Bind a boolean to parameter i. + virtual void bindParamB(unsigned int i, bool val) = 0; + + /// Bind a floating point number to parameter i. + virtual void bindParamF(unsigned int i, double val) = 0; + /// Bind a floating point number to parameter i. + virtual void bindParamF(unsigned int i, float val) = 0; + + /// Bind a string to parameter i. + virtual void bindParamS(unsigned int i, const Glib::ustring &) = 0; + /// Bind a string_view to parameter i. + virtual void bindParamS(unsigned int i, const std::string_view &) = 0; + /// Bind a string to parameter i (wraps string_view). + inline void + bindParamS(unsigned int i, const std::string & v) + { + bindParamS(i, std::string_view(v)); + } + + /// Bind a duration to parameter i. + virtual void bindParamT(unsigned int i, const boost::posix_time::time_duration &) = 0; + /// Bind a date time to parameter i. + virtual void bindParamT(unsigned int i, const boost::posix_time::ptime &) = 0; + + /// Bind a BLOB to parameter i. + virtual void bindParamBLOB(unsigned int i, const Blob &); + + /// Bind null to parameter i. + virtual void bindNull(unsigned int i) = 0; + + /// The SQL statement. + const std::string sql; + + /// Bind a parameter by type based on C++ traits to parameter i. + template + inline void + bindParam(unsigned int i, const O & o) + { + if constexpr (std::is_null_pointer::value || std::is_same::value) { + bindNull(i); } - - /// Bind a duration to parameter i. - virtual void bindParamT(unsigned int i, const boost::posix_time::time_duration &) = 0; - /// Bind a date time to parameter i. - virtual void bindParamT(unsigned int i, const boost::posix_time::ptime &) = 0; - - /// Bind a BLOB to parameter i. - virtual void bindParamBLOB(unsigned int i, const Blob &); - - /// Bind null to parameter i. - virtual void bindNull(unsigned int i) = 0; - - /// The SQL statement. - const std::string sql; - - /// Bind a parameter by type based on C++ traits to parameter i. - template - inline void bindParam(unsigned int i, const O & o) - { - if constexpr (std::is_null_pointer::value || - std::is_same::value) { - bindNull(i); - } - else if constexpr (std::is_same::value) { - bindParamB(i, o); - } - else if constexpr (std::is_floating_point::value) { - bindParamF(i, o); - } - else if constexpr (std::is_same::value || - std::is_same::value) { - bindParamT(i, o); - } - else if constexpr (std::is_same::value || std::is_convertible::value) { - bindParamBLOB(i, o); - } - else if constexpr (std::is_integral::value && !std::is_pointer::value) { - bindParamI(i, o); - } - else if constexpr (std::is_convertible::value && - std::is_pointer::value) { - if (o) { - bindParamS(i, o); - } - else { - bindNull(i); - } - } - else if constexpr (std::is_same::value || - std::is_convertible::value) { - // NOLINTNEXTLINE(hicpp-no-array-decay) + else if constexpr (std::is_same::value) { + bindParamB(i, o); + } + else if constexpr (std::is_floating_point::value) { + bindParamF(i, o); + } + else if constexpr (std::is_same::value + || std::is_same::value) { + bindParamT(i, o); + } + else if constexpr (std::is_same::value || std::is_convertible::value) { + bindParamBLOB(i, o); + } + else if constexpr (std::is_integral::value && !std::is_pointer::value) { + bindParamI(i, o); + } + else if constexpr (std::is_convertible::value && std::is_pointer::value) { + if (o) { bindParamS(i, o); } - else if constexpr (std::is_constructible::value) { - if (o) { - bindParam(i, *o); - } - else { - bindNull(i); - } + else { + bindNull(i); + } + } + else if constexpr (std::is_same::value + || std::is_convertible::value) { + // NOLINTNEXTLINE(hicpp-no-array-decay) + bindParamS(i, o); + } + else if constexpr (std::is_constructible::value) { + if (o) { + bindParam(i, *o); } else { - static_assert(std::is_void_v, "No suitable trait"); + bindNull(i); } } + else { + static_assert(std::is_void_v, "No suitable trait"); + } + } #define OPTWRAPPER(func) \ - template \ - inline auto \ - func(unsigned int i, const O & o) -> typename std::enable_if< \ - std::is_constructible_v \ - && !std::is_void_v \ - >::type\ - { \ - bool nn(o); \ - if (nn) \ - func(i, *o); \ - else \ - bindNull(i); \ - } - /// @cond - OPTWRAPPER(bindParamI); - OPTWRAPPER(bindParamF); - // NOLINTNEXTLINE(hicpp-no-array-decay) - OPTWRAPPER(bindParamS); - OPTWRAPPER(bindParamB); - OPTWRAPPER(bindParamT); - /// @endcond + template \ + inline auto func(unsigned int i, const O & o) \ + ->typename std::enable_if && !std::is_void_v>::type \ + { \ + bool nn(o); \ + if (nn) \ + func(i, *o); \ + else \ + bindNull(i); \ + } + /// @cond + OPTWRAPPER(bindParamI); + OPTWRAPPER(bindParamF); + // NOLINTNEXTLINE(hicpp-no-array-decay) + OPTWRAPPER(bindParamS); + OPTWRAPPER(bindParamB); + OPTWRAPPER(bindParamT); + /// @endcond #undef OPTWRAPPER - /// Bind a (possibly null) c-string to parameter i. - void bindParamS(unsigned int, const char * const); - /// Bind a (possibly null) c-string to parameter i. - void bindParamS(unsigned int, char * const); + /// Bind a (possibly null) c-string to parameter i. + void bindParamS(unsigned int, const char * const); + /// Bind a (possibly null) c-string to parameter i. + void bindParamS(unsigned int, char * const); }; using CommandOptionsFactory = AdHoc::Factory; } #endif - diff --git a/libdbpp/command_fwd.h b/libdbpp/command_fwd.h index 6547705..92b9d47 100644 --- a/libdbpp/command_fwd.h +++ b/libdbpp/command_fwd.h @@ -1,9 +1,9 @@ #ifndef DB_COMMAND_FWD_H #define DB_COMMAND_FWD_H -#include #include #include +#include namespace DB { using CommandOptionsMap = std::map>; @@ -18,6 +18,4 @@ namespace DB { using SelectCommandPtr = std::shared_ptr; } - #endif - diff --git a/libdbpp/connection.cpp b/libdbpp/connection.cpp index cc70af6..e281aaf 100644 --- a/libdbpp/connection.cpp +++ b/libdbpp/connection.cpp @@ -1,16 +1,13 @@ #include "connection.h" +#include "error.h" #include "modifycommand.h" #include "selectcommand.h" -#include "error.h" -#include #include +#include #include #include -DB::ConnectionError::ConnectionError() : - FailureTime(time(nullptr)) -{ -} +DB::ConnectionError::ConnectionError() : FailureTime(time(nullptr)) { } std::string DB::TransactionStillOpen::message() const noexcept @@ -135,7 +132,7 @@ DB::Connection::bulkUploadData(std::istream & in) const } std::array buf {}; size_t total = 0; - for (std::streamsize r; (r = in.readsome(buf.data(), buf.size())) > 0; ) { + for (std::streamsize r; (r = in.readsome(buf.data(), buf.size())) > 0;) { bulkUploadData(buf.data(), r); total += r; } @@ -158,7 +155,6 @@ DB::Connection::bulkUploadData(FILE * in) const throw std::system_error(-r, std::system_category()); } return total; - } AdHocFormatter(PluginLibraryFormat, "libdbpp-%?.so"); @@ -180,8 +176,7 @@ DB::TransactionRequired::message() const noexcept return "A transaction must be opened before performing this operation"; } -DB::TransactionScope::TransactionScope(DB::Connection & c) : - conn(&c) +DB::TransactionScope::TransactionScope(DB::Connection & c) : conn(&c) { conn->beginTx(); } @@ -205,4 +200,3 @@ DB::TransactionScope::~TransactionScope() noexcept INSTANTIATEFACTORY(DB::Connection, std::string); PLUGINRESOLVER(DB::ConnectionFactory, DB::Connection::resolvePlugin); - diff --git a/libdbpp/connection.h b/libdbpp/connection.h index b58a536..9cd96e0 100644 --- a/libdbpp/connection.h +++ b/libdbpp/connection.h @@ -1,18 +1,18 @@ #ifndef DB_CONNECTION_H #define DB_CONNECTION_H -#include "connection_fwd.h" #include "command_fwd.h" -#include -#include -#include +#include "connection_fwd.h" +#include "error.h" +#include #include -#include +#include #include #include #include -#include "error.h" -#include +#include +#include +#include namespace AdHoc { class Buffer; @@ -50,134 +50,134 @@ namespace DB { /// Base class for database connectivity errors. class DLL_PUBLIC ConnectionError : public Error { - public: - /// Default constructor, sets FailureTime to now. - ConnectionError(); + public: + /// Default constructor, sets FailureTime to now. + ConnectionError(); - /// The time of connectivity failure. - const time_t FailureTime; + /// The time of connectivity failure. + const time_t FailureTime; }; /// Exception thrown when finishing a connection that still has a transaction open. class DLL_PUBLIC TransactionStillOpen : public AdHoc::StdException { - private: - std::string message() const noexcept override; + private: + std::string message() const noexcept override; }; /// Exception thrown when attempting to open a transaction when one is already open. class DLL_PUBLIC TransactionAlreadyOpen : public AdHoc::StdException { - private: - std::string message() const noexcept override; + private: + std::string message() const noexcept override; }; /// Exception thrown when attempting to perform a table patch with invalid settings. class DLL_PUBLIC PatchCheckFailure : public AdHoc::StdException { - private: - std::string message() const noexcept override; + private: + std::string message() const noexcept override; }; /// Exception thrown when attempting to perform an action that requires a transaction when one is not open. class DLL_PUBLIC TransactionRequired : public AdHoc::StdException { - private: - std::string message() const noexcept override; + private: + std::string message() const noexcept override; }; /// Base class for connections to a database. class DLL_PUBLIC Connection : public std::enable_shared_from_this { - public: - virtual ~Connection() = default; - /// Standard special members - SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(Connection); - - /// Perform final checks before closing. - void finish() const; - /// Open a new transaction. - void beginTx(); - /// Commit an open transaction. - void commitTx(); - /// Rollback an open transaction. - void rollbackTx(); - /// Test to see if a transaction is currently open. - bool inTx() const; - /// Create a named save point. - virtual void savepoint(const std::string &); - /// Rollback to a named save point. - virtual void rollbackToSavepoint(const std::string &); - /// Release a named save point. - virtual void releaseSavepoint(const std::string &); - /// Test server connection availability. - virtual void ping() const = 0; - /// @cond - virtual BulkDeleteStyle bulkDeleteStyle() const = 0; - virtual BulkUpdateStyle bulkUpdateStyle() const = 0; - /// @endcond - - /// Straight up execute a statement (no access to result set) - virtual void execute(const std::string & sql, const CommandOptionsCPtr & = nullptr); - /// Execute a script from a stream. - /// @param f the script. - /// @param s the location of the script. - virtual void executeScript(std::istream & f, const std::filesystem::path & s); - /// Create a new select command with the given SQL. - virtual SelectCommandPtr select(const std::string & sql, const CommandOptionsCPtr & = nullptr) = 0; - /// Create a new modify command with the given SQL. - virtual ModifyCommandPtr modify(const std::string & sql, const CommandOptionsCPtr & = nullptr) = 0; - - /// Begin a bulk upload operation. - /// @param table the target table. - /// @param opts database specific options to the load command. - virtual void beginBulkUpload(const char * table, const char * opts); - /// Finish a bulk upload operation. - virtual void endBulkUpload(const char *); - /// Load data for the current bulk load operation. - virtual size_t bulkUploadData(const char *, size_t) const; - /// Load bulk data from a file (wrapper) - size_t bulkUploadData(std::istream &) const; - /// Load bulk data from a file (wrapper) - size_t bulkUploadData(FILE *) const; - - /// Return the Id used in the last insert - virtual int64_t insertId(); - - /// Patch one table's contents into another. - PatchResult patchTable(TablePatch * tp); - - /// AdHoc plugin resolver helper for database connectors. - static std::optional resolvePlugin(const std::type_info &, const std::string_view &); - - protected: - /// Create a new connection. - Connection() = default; - - /// Internal begin transaction. - virtual void beginTxInt() = 0; - /// Internal commit transaction. - virtual void commitTxInt() = 0; - /// Internal rollbacj transaction. - virtual void rollbackTxInt() = 0; - - /// Internal perform table patch delete operations. - virtual unsigned int patchDeletes(TablePatch * tp); - /// Internal perform table patch update operations. - virtual unsigned int patchUpdates(TablePatch * tp); - /// Internal perform table patch insert operations. - virtual unsigned int patchInserts(TablePatch * tp); - - private: - unsigned int txOpenDepth { 0 }; + public: + virtual ~Connection() = default; + /// Standard special members + SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(Connection); + + /// Perform final checks before closing. + void finish() const; + /// Open a new transaction. + void beginTx(); + /// Commit an open transaction. + void commitTx(); + /// Rollback an open transaction. + void rollbackTx(); + /// Test to see if a transaction is currently open. + bool inTx() const; + /// Create a named save point. + virtual void savepoint(const std::string &); + /// Rollback to a named save point. + virtual void rollbackToSavepoint(const std::string &); + /// Release a named save point. + virtual void releaseSavepoint(const std::string &); + /// Test server connection availability. + virtual void ping() const = 0; + /// @cond + virtual BulkDeleteStyle bulkDeleteStyle() const = 0; + virtual BulkUpdateStyle bulkUpdateStyle() const = 0; + /// @endcond + + /// Straight up execute a statement (no access to result set) + virtual void execute(const std::string & sql, const CommandOptionsCPtr & = nullptr); + /// Execute a script from a stream. + /// @param f the script. + /// @param s the location of the script. + virtual void executeScript(std::istream & f, const std::filesystem::path & s); + /// Create a new select command with the given SQL. + virtual SelectCommandPtr select(const std::string & sql, const CommandOptionsCPtr & = nullptr) = 0; + /// Create a new modify command with the given SQL. + virtual ModifyCommandPtr modify(const std::string & sql, const CommandOptionsCPtr & = nullptr) = 0; + + /// Begin a bulk upload operation. + /// @param table the target table. + /// @param opts database specific options to the load command. + virtual void beginBulkUpload(const char * table, const char * opts); + /// Finish a bulk upload operation. + virtual void endBulkUpload(const char *); + /// Load data for the current bulk load operation. + virtual size_t bulkUploadData(const char *, size_t) const; + /// Load bulk data from a file (wrapper) + size_t bulkUploadData(std::istream &) const; + /// Load bulk data from a file (wrapper) + size_t bulkUploadData(FILE *) const; + + /// Return the Id used in the last insert + virtual int64_t insertId(); + + /// Patch one table's contents into another. + PatchResult patchTable(TablePatch * tp); + + /// AdHoc plugin resolver helper for database connectors. + static std::optional resolvePlugin(const std::type_info &, const std::string_view &); + + protected: + /// Create a new connection. + Connection() = default; + + /// Internal begin transaction. + virtual void beginTxInt() = 0; + /// Internal commit transaction. + virtual void commitTxInt() = 0; + /// Internal rollbacj transaction. + virtual void rollbackTxInt() = 0; + + /// Internal perform table patch delete operations. + virtual unsigned int patchDeletes(TablePatch * tp); + /// Internal perform table patch update operations. + virtual unsigned int patchUpdates(TablePatch * tp); + /// Internal perform table patch insert operations. + virtual unsigned int patchInserts(TablePatch * tp); + + private: + unsigned int txOpenDepth {0}; }; /// Helper class for beginning/committing/rolling back transactions in accordance with scope and exceptions. class DLL_PUBLIC TransactionScope { - public: - /// Create a new helper and associated transaction on the given connection. - explicit TransactionScope(Connection &); - ~TransactionScope() noexcept; - /// Standard special members - SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(TransactionScope); - - private: - Connection * conn; + public: + /// Create a new helper and associated transaction on the given connection. + explicit TransactionScope(Connection &); + ~TransactionScope() noexcept; + /// Standard special members + SPECIAL_MEMBERS_DEFAULT_MOVE_NO_COPY(TransactionScope); + + private: + Connection * conn; }; using ConnectionFactory = AdHoc::Factory; @@ -185,4 +185,3 @@ namespace DB { } #endif - diff --git a/libdbpp/connectionPool.cpp b/libdbpp/connectionPool.cpp index d61a1a4..5ee4f32 100644 --- a/libdbpp/connectionPool.cpp +++ b/libdbpp/connectionPool.cpp @@ -5,15 +5,10 @@ template class AdHoc::ResourcePool; template class AdHoc::ResourceHandle; namespace DB { - BasicConnectionPool::BasicConnectionPool(unsigned int m, unsigned int k) : - ResourcePool(m, k) - { - } + BasicConnectionPool::BasicConnectionPool(unsigned int m, unsigned int k) : ResourcePool(m, k) { } ConnectionPool::ConnectionPool(unsigned int m, unsigned int k, const std::string & t, std::string cs) : - BasicConnectionPool(m, k), - factory(ConnectionFactory::get(t)), - connectionString(std::move(cs)) + BasicConnectionPool(m, k), factory(ConnectionFactory::get(t)), connectionString(std::move(cs)) { } @@ -35,4 +30,3 @@ namespace DB { c->ping(); } } - diff --git a/libdbpp/connectionPool.h b/libdbpp/connectionPool.h index 1955f21..877781e 100644 --- a/libdbpp/connectionPool.h +++ b/libdbpp/connectionPool.h @@ -1,48 +1,47 @@ #ifndef DB_CONNECTIONPOOL_H #define DB_CONNECTIONPOOL_H +#include "connection.h" +#include #include #include -#include -#include "connection.h" namespace DB { /// Specialisation of AdHoc::ResourcePool for database connections. class DLL_PUBLIC BasicConnectionPool : public AdHoc::ResourcePool { - public: - /// Create a new connection pool. - /// @param max Maximum number of concurrent database connections. - /// @param keep Number of connections to keep open after use. - BasicConnectionPool(unsigned int max, unsigned int keep); - - protected: - /// Ping a connection. - void returnTestResource(Connection const *) const override; - /// Ping a connection. - void testResource(Connection const *) const override; + public: + /// Create a new connection pool. + /// @param max Maximum number of concurrent database connections. + /// @param keep Number of connections to keep open after use. + BasicConnectionPool(unsigned int max, unsigned int keep); + + protected: + /// Ping a connection. + void returnTestResource(Connection const *) const override; + /// Ping a connection. + void testResource(Connection const *) const override; }; /// Standard specialisation of AdHoc::ResourcePool for database connections given a type and connection string. class DLL_PUBLIC ConnectionPool : public BasicConnectionPool { - public: - /// Create a new connection pool. - /// @param max Maximum number of concurrent database connections. - /// @param keep Number of connections to keep open after use. - /// @param type Database connection factory name. - /// @param connectionString Connection string to pass to the connection factory. - ConnectionPool(unsigned int max, unsigned int keep, const std::string & type, std::string connectionString); - - protected: - /// Create a new connection. - ConnectionPtr createResource() const override; - - private: - const ConnectionFactoryCPtr factory; - const std::string connectionString; + public: + /// Create a new connection pool. + /// @param max Maximum number of concurrent database connections. + /// @param keep Number of connections to keep open after use. + /// @param type Database connection factory name. + /// @param connectionString Connection string to pass to the connection factory. + ConnectionPool(unsigned int max, unsigned int keep, const std::string & type, std::string connectionString); + + protected: + /// Create a new connection. + ConnectionPtr createResource() const override; + + private: + const ConnectionFactoryCPtr factory; + const std::string connectionString; }; using ConnectionPoolPtr = std::shared_ptr; } #endif - diff --git a/libdbpp/connection_fwd.h b/libdbpp/connection_fwd.h index c8f9e73..74ce21e 100644 --- a/libdbpp/connection_fwd.h +++ b/libdbpp/connection_fwd.h @@ -10,4 +10,3 @@ namespace DB { } #endif - diff --git a/libdbpp/createMockDb.cpp b/libdbpp/createMockDb.cpp index f690f6c..d54dae8 100644 --- a/libdbpp/createMockDb.cpp +++ b/libdbpp/createMockDb.cpp @@ -1,15 +1,19 @@ -#include +#include "mockDatabase.h" #include -#include #include -#include "mockDatabase.h" +#include +#include namespace po = boost::program_options; namespace fs = std::filesystem; -void emptyHandler(int) { } +void +emptyHandler(int) +{ +} -void createFailHandler() +void +createFailHandler() { try { if (auto eptr = std::current_exception()) { @@ -30,6 +34,7 @@ main(int argc, char ** argv) std::string connector, master, database; bool drop; + // clang-format off opts.add_options() ("help,h", "Show this help message") ("drop,X", po::bool_switch(&drop)->default_value(false), "Drop immediately after creation (don't wait for signal)") @@ -38,6 +43,7 @@ main(int argc, char ** argv) ("master,m", po::value(&master), "Master connection string") ("database,d", po::value(&database)->default_value("mock"), "Database name prefix to use") ; + // clang-format on po::positional_options_description p; p.add("script", -1); @@ -70,4 +76,3 @@ main(int argc, char ** argv) std::cout << " done." << std::endl; return 0; } - diff --git a/libdbpp/dbTypes.cpp b/libdbpp/dbTypes.cpp index 6dd8605..7c4a87a 100644 --- a/libdbpp/dbTypes.cpp +++ b/libdbpp/dbTypes.cpp @@ -1,15 +1,10 @@ #include "dbTypes.h" #include -DB::Blob::Blob(const void * d, size_t l) : - data(d), - len(l) -{ -} +DB::Blob::Blob(const void * d, size_t l) : data(d), len(l) { } bool DB::Blob::operator==(const DB::Blob b) const { return this->len == b.len && memcmp(this->data, b.data, this->len) == 0; } - diff --git a/libdbpp/dbTypes.h b/libdbpp/dbTypes.h index 6589784..ba79b06 100644 --- a/libdbpp/dbTypes.h +++ b/libdbpp/dbTypes.h @@ -1,43 +1,35 @@ #ifndef DB_TYPES_H #define DB_TYPES_H -#include #include #include +#include namespace DB { /// Wrapper class for reference an existing block of binary data. class DLL_PUBLIC Blob { - public: - /// Construct a default blob pointing to no data. - Blob() = default; - /// Construct a reference using C-style pointer and length. - Blob(const void * data, size_t len); - /// Construct a reference using C++ template pointer to an object. - template - explicit Blob(const T * t) : - data(t), - len(sizeof(T)) - { - } - /// Construct a reference using C++ vector pointer to a collection of objects. - template - // NOLINTNEXTLINE(hicpp-explicit-conversions) - Blob(const std::vector & v) : - data(&v.front()), - len(sizeof(T) * v.size()) - { - } + public: + /// Construct a default blob pointing to no data. + Blob() = default; + /// Construct a reference using C-style pointer and length. + Blob(const void * data, size_t len); + /// Construct a reference using C++ template pointer to an object. + template explicit Blob(const T * t) : data(t), len(sizeof(T)) { } + /// Construct a reference using C++ vector pointer to a collection of objects. + template + // NOLINTNEXTLINE(hicpp-explicit-conversions) + Blob(const std::vector & v) : data(&v.front()), len(sizeof(T) * v.size()) + { + } - /// Byte-wise equality operation. - bool operator==(const DB::Blob b) const; + /// Byte-wise equality operation. + bool operator==(const DB::Blob b) const; - /// The beginning of the binary data. - const void * data { nullptr }; - /// The length of the binary data. - size_t len { 0 }; + /// The beginning of the binary data. + const void * data {nullptr}; + /// The length of the binary data. + size_t len {0}; }; } #endif - diff --git a/libdbpp/error.h b/libdbpp/error.h index 6c162f9..8245ea9 100644 --- a/libdbpp/error.h +++ b/libdbpp/error.h @@ -20,27 +20,27 @@ namespace DB { /// Exception thrown on an attempt to convert betweem incompatible types. class DLL_PUBLIC InvalidConversion : public AdHoc::Exception { - public: - /// Create a new InvalidConversion exception with the names of the conversion types. - /// @param from Source type - /// @param to Destination type - InvalidConversion(const char * const from, const char * const to); - - private: - std::string message() const noexcept override; - const std::string from; - const std::string to; + public: + /// Create a new InvalidConversion exception with the names of the conversion types. + /// @param from Source type + /// @param to Destination type + InvalidConversion(const char * const from, const char * const to); + + private: + std::string message() const noexcept override; + const std::string from; + const std::string to; }; /// Exception thrown when a null value occurs when reading into a non-optional value. class DLL_PUBLIC UnexpectedNullValue : public AdHoc::Exception { - public: - /// Create a new UnexpectedNullValue given the source type name. - explicit UnexpectedNullValue(const char * const from); + public: + /// Create a new UnexpectedNullValue given the source type name. + explicit UnexpectedNullValue(const char * const from); - private: - std::string message() const noexcept override; - const char * to; + private: + std::string message() const noexcept override; + const char * to; }; } diff --git a/libdbpp/mockDatabase.cpp b/libdbpp/mockDatabase.cpp index f9c395b..d52413e 100644 --- a/libdbpp/mockDatabase.cpp +++ b/libdbpp/mockDatabase.cpp @@ -2,83 +2,83 @@ #define BOOST_FILESYSTEM_SOURCE #include "mockDatabase.h" #include +#include #include #include #include -#include INSTANTIATEPLUGINOF(DB::MockDatabase); -INSTANTIATEFACTORY(DB::MockDatabase, const std::string &, const std::string &, const std::vector &); +INSTANTIATEFACTORY( + DB::MockDatabase, const std::string &, const std::string &, const std::vector &); PLUGINRESOLVER(DB::MockDatabaseFactory, DB::Connection::resolvePlugin); namespace DB { -unsigned int MockDatabase::mocked = 0; - + unsigned int MockDatabase::mocked = 0; -ConnectionPtr -MockDatabase::openConnectionTo(const std::string & mockName) -{ - return AdHoc::PluginManager::getDefault()->get(mockName)->implementation()->openConnection(); -} + ConnectionPtr + MockDatabase::openConnectionTo(const std::string & mockName) + { + return AdHoc::PluginManager::getDefault()->get(mockName)->implementation()->openConnection(); + } -void -MockDatabase::PlaySchemaScripts(const std::vector & ss) const -{ - auto conn = ConnectionPtr(openConnection()); - try { - for (const auto & s : ss) { - conn->beginTx(); - PlaySchemaScript(conn.get(), s); - conn->commitTx(); + void + MockDatabase::PlaySchemaScripts(const std::vector & ss) const + { + auto conn = ConnectionPtr(openConnection()); + try { + for (const auto & s : ss) { + conn->beginTx(); + PlaySchemaScript(conn.get(), s); + conn->commitTx(); + } } - } - catch (...) { - if (conn->inTx()) { - conn->rollbackTx(); + catch (...) { + if (conn->inTx()) { + conn->rollbackTx(); + } + DropDatabase(); + throw; } - DropDatabase(); - throw; } -} -void -MockDatabase::PlaySchemaScript(DB::Connection * conn, const std::filesystem::path & s) const -{ - std::ifstream f; - f.open(s); - if (!f.good()) { - throw std::fstream::failure("Failed to open mock script: " + s.string()); + void + MockDatabase::PlaySchemaScript(DB::Connection * conn, const std::filesystem::path & s) const + { + std::ifstream f; + f.open(s); + if (!f.good()) { + throw std::fstream::failure("Failed to open mock script: " + s.string()); + } + conn->executeScript(f, s.parent_path()); + f.close(); } - conn->executeScript(f, s.parent_path()); - f.close(); -} -AdHocFormatter(MockServerDatabaseName, "libdbpp_mock_%?_%?_%?"); -MockServerDatabase::MockServerDatabase(const std::string & masterdb, const std::string & name, const std::string & type) : - master(DB::ConnectionFactory::createNew(type, masterdb)), - testDbName(MockServerDatabaseName::get(name, getpid(), ++mocked)) -{ -} + AdHocFormatter(MockServerDatabaseName, "libdbpp_mock_%?_%?_%?"); + MockServerDatabase::MockServerDatabase( + const std::string & masterdb, const std::string & name, const std::string & type) : + master(DB::ConnectionFactory::createNew(type, masterdb)), + testDbName(MockServerDatabaseName::get(name, getpid(), ++mocked)) + { + } -const std::string & -MockServerDatabase::databaseName() const -{ - return testDbName; -} + const std::string & + MockServerDatabase::databaseName() const + { + return testDbName; + } -void -MockServerDatabase::CreateNewDatabase() const -{ - DropDatabase(); - master->execute("CREATE DATABASE " + testDbName); -} + void + MockServerDatabase::CreateNewDatabase() const + { + DropDatabase(); + master->execute("CREATE DATABASE " + testDbName); + } -void -MockServerDatabase::DropDatabase() const -{ - master->execute("DROP DATABASE IF EXISTS " + testDbName); -} + void + MockServerDatabase::DropDatabase() const + { + master->execute("DROP DATABASE IF EXISTS " + testDbName); + } } - diff --git a/libdbpp/mockDatabase.h b/libdbpp/mockDatabase.h index 5435933..ed38ef8 100644 --- a/libdbpp/mockDatabase.h +++ b/libdbpp/mockDatabase.h @@ -1,16 +1,16 @@ #ifndef DB_MOCKDATABASE_H #define DB_MOCKDATABASE_H +#include "connection.h" +#include #include #include -#include -#include "connection.h" #include namespace DB { -/// MockDatabase creates, registers and destroys a database suitable for unit testing. -class DLL_PUBLIC MockDatabase : public AdHoc::AbstractPluginImplementation { + /// MockDatabase creates, registers and destroys a database suitable for unit testing. + class DLL_PUBLIC MockDatabase : public AdHoc::AbstractPluginImplementation { public: /// Open a connection to this database instance. [[nodiscard]] virtual ConnectionPtr openConnection() const = 0; @@ -30,11 +30,11 @@ class DLL_PUBLIC MockDatabase : public AdHoc::AbstractPluginImplementation { /// Internal counter of mocked databases (for unique name generation) static unsigned int mocked; -}; + }; -/// MockServerDatabase extends MockDatabase with the functionality to connect to a database service -/// and create your mock on there. -class DLL_PUBLIC MockServerDatabase : public MockDatabase { + /// MockServerDatabase extends MockDatabase with the functionality to connect to a database service + /// and create your mock on there. + class DLL_PUBLIC MockServerDatabase : public MockDatabase { public: /// Create and register a new database. /// @param masterdb connection to server with permissions to create a new database. @@ -53,18 +53,18 @@ class DLL_PUBLIC MockServerDatabase : public MockDatabase { DB::ConnectionPtr master; /// The name of the database that was created on the server. const std::string testDbName; -}; + }; -/// Helper class for creating instances of mock databases -template -class PluginMock { + /// Helper class for creating instances of mock databases + template class PluginMock { public: /// Create and register a new mock database. /// @param name the name of the mock database to register. /// @param s the collection of scripts to populate the mock database. /// @param args arguments to the mock database constructor. - template - PluginMock(const std::string & name, const std::initializer_list & s, const Args & ... args) : + template + PluginMock(const std::string & name, const std::initializer_list & s, + const Args &... args) : mockName(name) { AdHoc::PluginManager::getDefault()->create(mockName, __FILE__, __LINE__, args..., name, s); @@ -77,17 +77,20 @@ class PluginMock { SPECIAL_MEMBERS_MOVE_RO(PluginMock); /// Get the name of the mock database. - [[nodiscard]] const std::string & databaseName() const + [[nodiscard]] const std::string & + databaseName() const { - return std::dynamic_pointer_cast(AdHoc::PluginManager::getDefault()->get(mockName)->implementation())->databaseName(); + return std::dynamic_pointer_cast( + AdHoc::PluginManager::getDefault()->get(mockName)->implementation()) + ->databaseName(); } /// The name of this mocked database. const std::string mockName; -}; + }; -using MockDatabaseFactory = AdHoc::Factory &>; + using MockDatabaseFactory = AdHoc::Factory &>; } #endif - diff --git a/libdbpp/modifycommand.cpp b/libdbpp/modifycommand.cpp index 79c8244..862e4fc 100644 --- a/libdbpp/modifycommand.cpp +++ b/libdbpp/modifycommand.cpp @@ -1,7 +1,3 @@ #include "modifycommand.h" -DB::ModifyCommand::ModifyCommand(const std::string & s) : - DB::Command(s) -{ -} - +DB::ModifyCommand::ModifyCommand(const std::string & s) : DB::Command(s) { } diff --git a/libdbpp/modifycommand.h b/libdbpp/modifycommand.h index 16ed142..00d729f 100644 --- a/libdbpp/modifycommand.h +++ b/libdbpp/modifycommand.h @@ -12,14 +12,13 @@ namespace DB { /// Presents a command not expected to return any data. class DLL_PUBLIC ModifyCommand : public virtual Command { - public: - /// Creates a new command from the given SQL. - explicit ModifyCommand(const std::string & sql); + public: + /// Creates a new command from the given SQL. + explicit ModifyCommand(const std::string & sql); - /// Execute the command and return effected row count - virtual unsigned int execute(bool allowNoChange = true) = 0; + /// Execute the command and return effected row count + virtual unsigned int execute(bool allowNoChange = true) = 0; }; } #endif - diff --git a/libdbpp/selectcommand.cpp b/libdbpp/selectcommand.cpp index 568b95b..216c8f8 100644 --- a/libdbpp/selectcommand.cpp +++ b/libdbpp/selectcommand.cpp @@ -1,10 +1,10 @@ #include "selectcommand.h" #include "error.h" -#include -#include #include -#include #include +#include +#include +#include #include namespace DB { @@ -26,22 +26,20 @@ namespace DB { return ColumnDoesNotExistMsg::get(colName); } - using ColumnsBase = boost::multi_index_container>, - boost::multi_index::ordered_unique> - >>; - class SelectCommand::Columns : public ColumnsBase { }; + using ColumnsBase = boost::multi_index_container>, + boost::multi_index::ordered_unique< + boost::multi_index::member>>>; + class SelectCommand::Columns : public ColumnsBase { + }; }; -DB::SelectCommand::SelectCommand(const std::string & sql) : - DB::Command(sql), - columns(std::make_unique()) -{ -} +DB::SelectCommand::SelectCommand(const std::string & sql) : DB::Command(sql), columns(std::make_unique()) { } DB::SelectCommand::~SelectCommand() = default; -const DB::Column& +const DB::Column & DB::SelectCommand::operator[](unsigned int n) const { if (n < columns->size()) { @@ -50,11 +48,10 @@ DB::SelectCommand::operator[](unsigned int n) const throw ColumnIndexOutOfRange(n); } -const DB::Column& +const DB::Column & DB::SelectCommand::operator[](const Glib::ustring & n) const { - if (auto i = columns->get<1>().find(n.collate_key()); - i != columns->get<1>().end()) { + if (auto i = columns->get<1>().find(n.collate_key()); i != columns->get<1>().end()) { return **i; } throw ColumnDoesNotExist(n); @@ -78,20 +75,16 @@ DB::SelectCommand::insertColumn(ColumnPtr col) return *columns->insert(std::move(col)).first; } -DB::RowBase::RowBase(SelectCommand * s) : - sel(s) -{ -} +DB::RowBase::RowBase(SelectCommand * s) : sel(s) { } -const DB::Column& +const DB::Column & DB::RowBase::operator[](const Glib::ustring & n) const { return sel->operator[](n); } -const DB::Column& +const DB::Column & DB::RowBase::operator[](unsigned int col) const { return sel->operator[](col); } - diff --git a/libdbpp/selectcommand.h b/libdbpp/selectcommand.h index a0fecc0..ee85c5c 100644 --- a/libdbpp/selectcommand.h +++ b/libdbpp/selectcommand.h @@ -1,17 +1,17 @@ #ifndef DB_SELECTCOMMAND_H #define DB_SELECTCOMMAND_H -#include "command.h" #include "column.h" +#include "command.h" #include "error.h" +#include #include #include -#include #ifndef BOOST_TEST_MODULE -#define DEPRECATE __attribute__((deprecated)) +# define DEPRECATE __attribute__((deprecated)) #else -#define DEPRECATE +# define DEPRECATE #endif namespace DB { @@ -20,139 +20,130 @@ namespace DB { /// @cond class DLL_PUBLIC RowBase { - public: - explicit RowBase(SelectCommand *); + public: + explicit RowBase(SelectCommand *); - /// Get a column reference by index. - const Column & operator[](unsigned int col) const; - /// Get a column reference by name. - const Column & operator[](const Glib::ustring &) const; + /// Get a column reference by index. + const Column & operator[](unsigned int col) const; + /// Get a column reference by name. + const Column & operator[](const Glib::ustring &) const; - protected: - SelectCommand * sel; + protected: + SelectCommand * sel; }; - template - class Row : public RowBase { - public: - explicit Row(SelectCommand *); + template class Row : public RowBase { + public: + explicit Row(SelectCommand *); - template - using FieldType = typename std::tuple_element>::type; + template using FieldType = typename std::tuple_element>::type; - /// Get value of column C in current row. - template - [[nodiscard]] FieldType value() const DEPRECATE ; + /// Get value of column C in current row. + template [[nodiscard]] FieldType value() const DEPRECATE; - template - [[nodiscard]] FieldType get() const; + template [[nodiscard]] FieldType get() const; }; - template - class RowRangeIterator { - public: - explicit RowRangeIterator(SelectCommand *); + template class RowRangeIterator { + public: + explicit RowRangeIterator(SelectCommand *); - bool operator!=(const RowRangeIterator &) const; - void operator++(); - Row operator*() const; + bool operator!=(const RowRangeIterator &) const; + void operator++(); + Row operator*() const; - private: - SelectCommand * sel; - bool validRow; + private: + SelectCommand * sel; + bool validRow; }; - template - class RowRange { - public: - explicit RowRange(SelectCommand *); + template class RowRange { + public: + explicit RowRange(SelectCommand *); - RowRangeIterator begin() const; - RowRangeIterator end() const; + RowRangeIterator begin() const; + RowRangeIterator end() const; - private: - SelectCommand * sel; + private: + SelectCommand * sel; }; /// @endcond /// Exception thrown when the requested column is outside the range of the result set. class DLL_PUBLIC ColumnIndexOutOfRange : public AdHoc::Exception { - public: - /// New ColumnIndexOutOfRange exception - /// @param n Index requested - explicit ColumnIndexOutOfRange(unsigned int n); + public: + /// New ColumnIndexOutOfRange exception + /// @param n Index requested + explicit ColumnIndexOutOfRange(unsigned int n); - /// Index requested - const unsigned int colNo; + /// Index requested + const unsigned int colNo; - private: - std::string message() const noexcept override; + private: + std::string message() const noexcept override; }; /// Exception thrown when the requested column does not exist in the result set. class DLL_PUBLIC ColumnDoesNotExist : public AdHoc::Exception { - public: - /// New ColumnDoesNotExist exception - /// @param n Name requested - explicit ColumnDoesNotExist(Glib::ustring n); + public: + /// New ColumnDoesNotExist exception + /// @param n Name requested + explicit ColumnDoesNotExist(Glib::ustring n); - /// Name requested - const Glib::ustring colName; + /// Name requested + const Glib::ustring colName; - private: - std::string message() const noexcept override; + private: + std::string message() const noexcept override; }; /// Represents a command expected to return data to the client. class DLL_PUBLIC SelectCommand : public virtual Command { - public: - /// Creates a new command from the given SQL. - explicit SelectCommand(const std::string & sql); - ~SelectCommand() override; - - /// Standard special members - SPECIAL_MEMBERS_MOVE_RO(SelectCommand); - - /// Fetch the next row from the result set. Returns false when no further rows are availabile. - virtual bool fetch() = 0; - /// Execute the statement, but don't fetch the first row. - virtual void execute() = 0; - /// Get a column reference by index. - [[nodiscard]] const Column & operator[](unsigned int col) const; - /// Get a column reference by name. - [[nodiscard]] const Column & operator[](const Glib::ustring &) const; - /// Get the number of columns in the result set. - [[nodiscard]] unsigned int columnCount() const; - /// Get the index of a column by name. - [[nodiscard]] unsigned int getOrdinal(const Glib::ustring &) const; - /// Push each row through a function accepting one value per column - template> - void forEachRow(const Func & func); - /// Support for a C++ row range for - template - RowRange as(); - - protected: - /// Helper function so clients need not know about boost::multi_index_container. - const ColumnPtr & insertColumn(ColumnPtr); - - class Columns; - - /// Columns in the result set. - std::unique_ptr columns; + public: + /// Creates a new command from the given SQL. + explicit SelectCommand(const std::string & sql); + ~SelectCommand() override; + + /// Standard special members + SPECIAL_MEMBERS_MOVE_RO(SelectCommand); + + /// Fetch the next row from the result set. Returns false when no further rows are availabile. + virtual bool fetch() = 0; + /// Execute the statement, but don't fetch the first row. + virtual void execute() = 0; + /// Get a column reference by index. + [[nodiscard]] const Column & operator[](unsigned int col) const; + /// Get a column reference by name. + [[nodiscard]] const Column & operator[](const Glib::ustring &) const; + /// Get the number of columns in the result set. + [[nodiscard]] unsigned int columnCount() const; + /// Get the index of a column by name. + [[nodiscard]] unsigned int getOrdinal(const Glib::ustring &) const; + /// Push each row through a function accepting one value per column + template> void forEachRow(const Func & func); + /// Support for a C++ row range for + template RowRange as(); + + protected: + /// Helper function so clients need not know about boost::multi_index_container. + const ColumnPtr & insertColumn(ColumnPtr); + + class Columns; + + /// Columns in the result set. + std::unique_ptr columns; }; } namespace std { /// @cond - template struct tuple_size> { - static constexpr auto value = sizeof...(Fn); + template struct tuple_size> { + static constexpr auto value = sizeof...(Fn); }; - template struct tuple_element> { - using type = typename std::tuple_element>::type; + template struct tuple_element> { + using type = typename std::tuple_element>::type; }; /// @endcond } #endif - diff --git a/libdbpp/selectcommandUtil.impl.h b/libdbpp/selectcommandUtil.impl.h index b8f62e5..ec1d56a 100644 --- a/libdbpp/selectcommandUtil.impl.h +++ b/libdbpp/selectcommandUtil.impl.h @@ -6,9 +6,9 @@ /// @cond namespace DB { - template + template inline void - forEachField(DB::SelectCommand * sel, const Func & func, const Args & ... args) + forEachField(DB::SelectCommand * sel, const Func & func, const Args &... args) { if constexpr (field >= std::tuple_size::value) { (void)sel; @@ -21,41 +21,39 @@ namespace DB { } } - template - inline void SelectCommand::forEachRow(const Func & func) + template + inline void + SelectCommand::forEachRow(const Func & func) { while (fetch()) { forEachField, Func, 0>(this, func); } } - template - inline RowRange SelectCommand::as() + template + inline RowRange + SelectCommand::as() { return RowRange(this); } - template - inline RowRange::RowRange(SelectCommand * s) : - sel(s) - { - } + template inline RowRange::RowRange(SelectCommand * s) : sel(s) { } - template - inline RowRangeIterator RowRange::begin() const + template + inline RowRangeIterator + RowRange::begin() const { return RowRangeIterator(sel); } - template - inline RowRangeIterator RowRange::end() const + template + inline RowRangeIterator + RowRange::end() const { return RowRangeIterator(nullptr); } - template - inline RowRangeIterator::RowRangeIterator(SelectCommand * s) : - sel(s) + template inline RowRangeIterator::RowRangeIterator(SelectCommand * s) : sel(s) { if (sel) { validRow = sel->fetch(); @@ -65,40 +63,41 @@ namespace DB { } } - template - inline bool RowRangeIterator::operator!=(const RowRangeIterator &) const + template + inline bool + RowRangeIterator::operator!=(const RowRangeIterator &) const { return validRow; } - template - inline void RowRangeIterator::operator++() + template + inline void + RowRangeIterator::operator++() { validRow = sel->fetch(); } - template - inline Row RowRangeIterator::operator*() const + template + inline Row + RowRangeIterator::operator*() const { return Row(sel); } - template - inline Row::Row(SelectCommand * s) : - RowBase(s) - { - } + template inline Row::Row(SelectCommand * s) : RowBase(s) { } - template + template template - inline typename Row::template FieldType Row::value() const + inline typename Row::template FieldType + Row::value() const { return get(); } - template + template template - inline typename Row::template FieldType Row::get() const + inline typename Row::template FieldType + Row::get() const { FieldType a; sel->operator[](C) >> a; @@ -108,4 +107,3 @@ namespace DB { /// @endcond #endif - diff --git a/libdbpp/sqlParse.h b/libdbpp/sqlParse.h index 20d6c0e..e84ceb7 100644 --- a/libdbpp/sqlParse.h +++ b/libdbpp/sqlParse.h @@ -1,63 +1,62 @@ #ifndef DB_SQLPARSE_H #define DB_SQLPARSE_H -#include -#include -#include #include "connection.h" +#include #include +#include +#include #ifndef yyFlexLexer -#define yyFlexLexer sqlBaseFlexLexer -#include +# define yyFlexLexer sqlBaseFlexLexer +# include #endif namespace DB { /// Exception representing a failure to parse an SQL script class DLL_PUBLIC SqlParseException : public AdHoc::StdException { - public: - /// Create a new SqlParseException - /// @param what What went wrong - /// @param line What line number - SqlParseException(const char * what, unsigned int line); - - private: - std::string message() const noexcept override; - const char * reason; - const unsigned int line; + public: + /// Create a new SqlParseException + /// @param what What went wrong + /// @param line What line number + SqlParseException(const char * what, unsigned int line); + + private: + std::string message() const noexcept override; + const char * reason; + const unsigned int line; }; /// @cond class DLL_PUBLIC SqlParse : public yyFlexLexer { - public: - SqlParse(std::istream &, std::filesystem::path); + public: + SqlParse(std::istream &, std::filesystem::path); - void Execute(); + void Execute(); - virtual void Comment(const std::string &) const = 0; - virtual void Statement(const std::string &) const = 0; + virtual void Comment(const std::string &) const = 0; + virtual void Statement(const std::string &) const = 0; - protected: - void LexerError(const char *) override; + protected: + void LexerError(const char *) override; - private: - int yylex() override; - const std::filesystem::path scriptDir; - std::string comment; - std::string statement; + private: + int yylex() override; + const std::filesystem::path scriptDir; + std::string comment; + std::string statement; }; class DLL_PUBLIC SqlExecuteScript : public SqlParse { - public: - SqlExecuteScript(std::istream &, const std::filesystem::path &, Connection *); + public: + SqlExecuteScript(std::istream &, const std::filesystem::path &, Connection *); - void Comment(const std::string &) const override; - void Statement(const std::string &) const override; + void Comment(const std::string &) const override; + void Statement(const std::string &) const override; - private: - DB::Connection * const conn; + private: + DB::Connection * const conn; }; /// @endcond } #endif - diff --git a/libdbpp/sqlParseImpl.cpp b/libdbpp/sqlParseImpl.cpp index 4c3a990..bb27c6e 100644 --- a/libdbpp/sqlParseImpl.cpp +++ b/libdbpp/sqlParseImpl.cpp @@ -1,53 +1,50 @@ -#include -#include #include "sqlParse.h" +#include +#include namespace DB { - SqlParseException::SqlParseException(const char * r, unsigned int l) : reason(r), line(l) { } + SqlParseException::SqlParseException(const char * r, unsigned int l) : reason(r), line(l) { } AdHocFormatter(SqlParseExceptionMsg, "Error parsing SQL script: %? at line %?"); - std::string - SqlParseException::message() const noexcept - { - return SqlParseExceptionMsg::get(reason, line); - } - - SqlParse::SqlParse(std::istream & f, std::filesystem::path s) : - yyFlexLexer(&f, nullptr), - scriptDir(std::move(s)) - { - if (!f.good()) { - throw SqlParseException("Script stream not in good state.", 0); - } - } - - void - SqlParse::Execute() - { - while (yylex()) {} - } - - void - SqlParse::LexerError(const char * msg) - { - throw std::runtime_error(msg); - } - - SqlExecuteScript::SqlExecuteScript(std::istream & f, const std::filesystem::path & s, DB::Connection * c) : - SqlParse(f, s), - conn(c) - { - } - - void - SqlExecuteScript::Comment(const std::string &) const - { - } - - void - SqlExecuteScript::Statement(const std::string & text) const - { - conn->execute(text); - } + std::string + SqlParseException::message() const noexcept + { + return SqlParseExceptionMsg::get(reason, line); + } + + SqlParse::SqlParse(std::istream & f, std::filesystem::path s) : yyFlexLexer(&f, nullptr), scriptDir(std::move(s)) + { + if (!f.good()) { + throw SqlParseException("Script stream not in good state.", 0); + } + } + + void + SqlParse::Execute() + { + while (yylex()) { } + } + + void + SqlParse::LexerError(const char * msg) + { + throw std::runtime_error(msg); + } + + SqlExecuteScript::SqlExecuteScript(std::istream & f, const std::filesystem::path & s, DB::Connection * c) : + SqlParse(f, s), conn(c) + { + } + + void + SqlExecuteScript::Comment(const std::string &) const + { + } + + void + SqlExecuteScript::Statement(const std::string & text) const + { + conn->execute(text); + } } diff --git a/libdbpp/sqlWriter.cpp b/libdbpp/sqlWriter.cpp index 328893c..f0afe3d 100644 --- a/libdbpp/sqlWriter.cpp +++ b/libdbpp/sqlWriter.cpp @@ -5,14 +5,10 @@ DB::SqlWriter::bindParams(DB::Command *, unsigned int &) { } -DB::StaticSqlWriter::StaticSqlWriter(std::string s) : - sql(std::move(s)) -{ -} +DB::StaticSqlWriter::StaticSqlWriter(std::string s) : sql(std::move(s)) { } void DB::StaticSqlWriter::writeSql(AdHoc::Buffer & buf) { buf.append(sql); } - diff --git a/libdbpp/sqlWriter.h b/libdbpp/sqlWriter.h index dbb35aa..43aef2e 100644 --- a/libdbpp/sqlWriter.h +++ b/libdbpp/sqlWriter.h @@ -1,43 +1,42 @@ #ifndef DB_SQLWRITER_H #define DB_SQLWRITER_H -#include #include #include +#include namespace DB { class Command; /// Base class of dynamic SQL constructors. class DLL_PUBLIC SqlWriter { - public: - SqlWriter() = default; - virtual ~SqlWriter() = default; - /// Standd special memeber - SPECIAL_MEMBERS_DEFAULT(SqlWriter); - /// Append your SQL to the buffer. - /// @param buffer The buffer - virtual void writeSql(AdHoc::Buffer & buffer) = 0; - /// Bind your parameters (offset should be increment 1 per bind made) - /// @param cmd Command to bind to. - /// @param offset The current bind offset. - virtual void bindParams(Command * cmd, unsigned int & offset); + public: + SqlWriter() = default; + virtual ~SqlWriter() = default; + /// Standd special memeber + SPECIAL_MEMBERS_DEFAULT(SqlWriter); + /// Append your SQL to the buffer. + /// @param buffer The buffer + virtual void writeSql(AdHoc::Buffer & buffer) = 0; + /// Bind your parameters (offset should be increment 1 per bind made) + /// @param cmd Command to bind to. + /// @param offset The current bind offset. + virtual void bindParams(Command * cmd, unsigned int & offset); }; /// A SQL Writer implementation that just writes static SQL. class DLL_PUBLIC StaticSqlWriter : public SqlWriter { - public: - /// Construct with the SQL to write. - /// @param sql The SQL to write. - explicit StaticSqlWriter(std::string sql); - /// Append the SQL to the buffer. - /// @param buffer The buffer - void writeSql(AdHoc::Buffer & buffer) override; + public: + /// Construct with the SQL to write. + /// @param sql The SQL to write. + explicit StaticSqlWriter(std::string sql); + /// Append the SQL to the buffer. + /// @param buffer The buffer + void writeSql(AdHoc::Buffer & buffer) override; - /// The SQL to write. - std::string sql; + /// The SQL to write. + std::string sql; }; } #endif - diff --git a/libdbpp/tablepatch.cpp b/libdbpp/tablepatch.cpp index 1a57bbc..e7e9fb3 100644 --- a/libdbpp/tablepatch.cpp +++ b/libdbpp/tablepatch.cpp @@ -1,11 +1,11 @@ +#include "tablepatch.h" #include "connection.h" #include "modifycommand.h" #include "selectcommand.h" -#include "tablepatch.h" #include "sqlWriter.h" +#include #include #include -#include DB::PatchResult DB::Connection::patchTable(TablePatch * tp) @@ -22,11 +22,8 @@ DB::Connection::patchTable(TablePatch * tp) tp->srcExpr = new DB::StaticSqlWriter(tp->src); ownedExpr = true; } - DB::PatchResult r { - tp->doDeletes ? patchDeletes(tp) : 0, - tp->doUpdates ? patchUpdates(tp) : 0, - tp->doInserts ? patchInserts(tp) : 0 - }; + DB::PatchResult r {tp->doDeletes ? patchDeletes(tp) : 0, tp->doUpdates ? patchUpdates(tp) : 0, + tp->doInserts ? patchInserts(tp) : 0}; if (ownedExpr) { delete tp->srcExpr; tp->srcExpr = nullptr; @@ -40,17 +37,19 @@ push(const boost::format &, typename Container::const_iterator &) { } -template +template static inline void -push(boost::format & f, typename Container::const_iterator & i, const Value & v, const Values & ... vs) +push(boost::format & f, typename Container::const_iterator & i, const Value & v, const Values &... vs) { f % v(i); push(f, i, vs...); } -template +template static inline unsigned int -appendIf(AdHoc::Buffer & buf, const Container & c, const std::function & sel, const Separator & sep, const std::string & fmts, const Ps & ... ps) +appendIf(AdHoc::Buffer & buf, const Container & c, + const std::function & sel, const Separator & sep, + const std::string & fmts, const Ps &... ps) { auto fmt = AdHoc::Buffer::getFormat(fmts); unsigned int x = 0; @@ -67,24 +66,31 @@ appendIf(AdHoc::Buffer & buf, const Container & c, const std::function +template static inline unsigned int -append(AdHoc::Buffer & buf, const Container & c, const Separator & sep, const std::string & fmts, const Ps & ... ps) +append(AdHoc::Buffer & buf, const Container & c, const Separator & sep, const std::string & fmts, const Ps &... ps) { - return appendIf(buf, c, [](auto){ return true; }, sep, fmts, ps...); + return appendIf( + buf, c, + [](auto) { + return true; + }, + sep, fmts, ps...); } -template +template static inline typename Container::key_type self(const typename Container::const_iterator & i) { return *i; } #define selfCols self -#define isNotKey(tp) [tp](auto i){ return !AdHoc::containerContains((tp)->pk, *i); } +#define isNotKey(tp) \ + [tp](auto i) { \ + return !AdHoc::containerContains((tp)->pk, *i); \ + } -static -void +static void patchDeletesSelect(AdHoc::Buffer & toDelSql, DB::TablePatch * tp) { toDelSql.append(" WHERE "); @@ -124,58 +130,56 @@ DB::Connection::patchDeletes(TablePatch * tp) } AdHoc::Buffer toDelSql; switch (bulkDeleteStyle()) { - case BulkDeleteUsingSubSelect: - { - // ----------------------------------------------------------------- - // Build SQL to delete keys ---------------------------------------- - // ----------------------------------------------------------------- - if (tp->insteadOfDelete) { - toDelSql.appendbf("UPDATE %s SET ", - tp->dest); - tp->insteadOfDelete->writeSql(toDelSql); - toDelSql.append(" WHERE ("); - } - else { - toDelSql.appendbf("DELETE FROM %s WHERE (", - tp->dest); - } - append(toDelSql, tp->pk, ", ", "%s.%s", [tp](auto){ return tp->dest; }, selfCols); - // ----------------------------------------------------------------- - // Build SQL to select keys to delete ------------------------------ - // ----------------------------------------------------------------- - toDelSql.append(") IN (SELECT "); - append(toDelSql, tp->pk, ", ", "a.%s", selfCols); - toDelSql.appendbf(" FROM %s a LEFT OUTER JOIN ", - tp->dest); - tp->srcExpr->writeSql(toDelSql); - toDelSql.append(" b ON "); - append(toDelSql, tp->pk, " AND ", " a.%s = b.%s", selfCols, selfCols); - patchDeletesSelect(toDelSql, tp); - toDelSql.append(")"); - break; + case BulkDeleteUsingSubSelect: { + // ----------------------------------------------------------------- + // Build SQL to delete keys ---------------------------------------- + // ----------------------------------------------------------------- + if (tp->insteadOfDelete) { + toDelSql.appendbf("UPDATE %s SET ", tp->dest); + tp->insteadOfDelete->writeSql(toDelSql); + toDelSql.append(" WHERE ("); + } + else { + toDelSql.appendbf("DELETE FROM %s WHERE (", tp->dest); } + append( + toDelSql, tp->pk, ", ", "%s.%s", + [tp](auto) { + return tp->dest; + }, + selfCols); + // ----------------------------------------------------------------- + // Build SQL to select keys to delete ------------------------------ + // ----------------------------------------------------------------- + toDelSql.append(") IN (SELECT "); + append(toDelSql, tp->pk, ", ", "a.%s", selfCols); + toDelSql.appendbf(" FROM %s a LEFT OUTER JOIN ", tp->dest); + tp->srcExpr->writeSql(toDelSql); + toDelSql.append(" b ON "); + append(toDelSql, tp->pk, " AND ", " a.%s = b.%s", selfCols, selfCols); + patchDeletesSelect(toDelSql, tp); + toDelSql.append(")"); + break; + } case BulkDeleteUsingUsingAlias: - case BulkDeleteUsingUsing: - { - if (tp->insteadOfDelete) { - toDelSql.appendbf("UPDATE %s a ", - tp->dest); - } - else { - toDelSql.appendbf("DELETE FROM %s USING %s a ", - (bulkDeleteStyle() == BulkDeleteUsingUsingAlias ? "a" : tp->dest), - tp->dest); - } - toDelSql.append(" LEFT OUTER JOIN "); - tp->srcExpr->writeSql(toDelSql); - toDelSql.append(" b ON "); - append(toDelSql, tp->pk, " AND ", " a.%s = b.%s ", selfCols, selfCols); - if (tp->insteadOfDelete) { - tp->insteadOfDelete->writeSql(toDelSql); - } - patchDeletesSelect(toDelSql, tp); - break; + case BulkDeleteUsingUsing: { + if (tp->insteadOfDelete) { + toDelSql.appendbf("UPDATE %s a ", tp->dest); + } + else { + toDelSql.appendbf("DELETE FROM %s USING %s a ", + (bulkDeleteStyle() == BulkDeleteUsingUsingAlias ? "a" : tp->dest), tp->dest); } + toDelSql.append(" LEFT OUTER JOIN "); + tp->srcExpr->writeSql(toDelSql); + toDelSql.append(" b ON "); + append(toDelSql, tp->pk, " AND ", " a.%s = b.%s ", selfCols, selfCols); + if (tp->insteadOfDelete) { + tp->insteadOfDelete->writeSql(toDelSql); + } + patchDeletesSelect(toDelSql, tp); + break; + } } auto del = modify(toDelSql); unsigned int offset = 0; @@ -192,15 +196,13 @@ DB::Connection::patchDeletes(TablePatch * tp) return del->execute(); } -static -void +static void patchUpdatesSelect(AdHoc::Buffer & updSql, DB::TablePatch * tp) { updSql.append(" WHERE "); append(updSql, tp->pk, " AND ", " a.%s = b.%s ", selfCols, selfCols); updSql.append(" AND ("); - appendIf(updSql, tp->cols, isNotKey(tp), " OR ", - " (((CASE WHEN (a.%s IS NULL AND b.%s IS NULL) THEN 1 ELSE 0 END) \ + appendIf(updSql, tp->cols, isNotKey(tp), " OR ", " (((CASE WHEN (a.%s IS NULL AND b.%s IS NULL) THEN 1 ELSE 0 END) \ + (CASE WHEN(a.%s = b.%s) THEN 1 ELSE 0 END)) = 0)", selfCols, selfCols, selfCols, selfCols); updSql.append(")"); @@ -243,76 +245,69 @@ DB::Connection::patchUpdates(TablePatch * tp) tp->beforeUpdate(upd); } switch (bulkUpdateStyle()) { - case BulkUpdateUsingFromSrc: - { - // ----------------------------------------------------------------- - // Build SQL for list of updates to perform ------------------------ - // ----------------------------------------------------------------- - AdHoc::Buffer updSql; - updSql.appendbf("UPDATE %s a SET ", - tp->dest); - appendIf(updSql, tp->cols, isNotKey(tp), ", ", " %s = b.%s ", selfCols, selfCols); - updSql.append(" FROM "); - tp->srcExpr->writeSql(updSql); - updSql.append(" b "); - patchUpdatesSelect(updSql, tp); - // ----------------------------------------------------------------- - // Execute the bulk update command --------------------------------- - // ----------------------------------------------------------------- - auto upd = modify(updSql); - unsigned int offset = 0; - tp->srcExpr->bindParams(upd.get(), offset); - if (tp->where) { - tp->where->bindParams(upd.get(), offset); - } - return upd->execute(true); + case BulkUpdateUsingFromSrc: { + // ----------------------------------------------------------------- + // Build SQL for list of updates to perform ------------------------ + // ----------------------------------------------------------------- + AdHoc::Buffer updSql; + updSql.appendbf("UPDATE %s a SET ", tp->dest); + appendIf(updSql, tp->cols, isNotKey(tp), ", ", " %s = b.%s ", selfCols, selfCols); + updSql.append(" FROM "); + tp->srcExpr->writeSql(updSql); + updSql.append(" b "); + patchUpdatesSelect(updSql, tp); + // ----------------------------------------------------------------- + // Execute the bulk update command --------------------------------- + // ----------------------------------------------------------------- + auto upd = modify(updSql); + unsigned int offset = 0; + tp->srcExpr->bindParams(upd.get(), offset); + if (tp->where) { + tp->where->bindParams(upd.get(), offset); } - break; - case BulkUpdateUsingJoin: - { - // ----------------------------------------------------------------- - // Build SQL for list of updates to perform ------------------------ - // ----------------------------------------------------------------- - AdHoc::Buffer updSql; - updSql.appendbf("UPDATE %s a, ", - tp->dest); - tp->srcExpr->writeSql(updSql); - updSql.append(" b SET "); - appendIf(updSql, tp->cols, isNotKey(tp), ", ", " a.%s = b.%s ", selfCols, selfCols); - patchUpdatesSelect(updSql, tp); - if (tp->order) { - updSql.append(" ORDER BY "); - tp->order->writeSql(updSql); - } - // ----------------------------------------------------------------- - // Execute the bulk update command --------------------------------- - // ----------------------------------------------------------------- - auto upd = modify(updSql); - unsigned int offset = 0; + return upd->execute(true); + } break; + case BulkUpdateUsingJoin: { + // ----------------------------------------------------------------- + // Build SQL for list of updates to perform ------------------------ + // ----------------------------------------------------------------- + AdHoc::Buffer updSql; + updSql.appendbf("UPDATE %s a, ", tp->dest); + tp->srcExpr->writeSql(updSql); + updSql.append(" b SET "); + appendIf(updSql, tp->cols, isNotKey(tp), ", ", " a.%s = b.%s ", selfCols, selfCols); + patchUpdatesSelect(updSql, tp); + if (tp->order) { + updSql.append(" ORDER BY "); + tp->order->writeSql(updSql); + } + // ----------------------------------------------------------------- + // Execute the bulk update command --------------------------------- + // ----------------------------------------------------------------- + auto upd = modify(updSql); + unsigned int offset = 0; + tp->where->bindParams(upd.get(), offset); + if (tp->where) { tp->where->bindParams(upd.get(), offset); - if (tp->where) { - tp->where->bindParams(upd.get(), offset); - } - if (tp->order) { - tp->order->bindParams(upd.get(), offset); - } - return upd->execute(true); } + if (tp->order) { + tp->order->bindParams(upd.get(), offset); + } + return upd->execute(true); + } default: return 0; } } -static -void +static void patchInsertsSelect(AdHoc::Buffer & toInsSql, DB::TablePatch * tp) { toInsSql.append("SELECT "); append(toInsSql, tp->cols, ", ", "b.%s", selfCols); toInsSql.append(" FROM "); tp->srcExpr->writeSql(toInsSql); - toInsSql.appendbf(" b LEFT OUTER JOIN %s a ON ", - tp->dest); + toInsSql.appendbf(" b LEFT OUTER JOIN %s a ON ", tp->dest); append(toInsSql, tp->pk, " AND ", " a.%s = b.%s", selfCols, selfCols); toInsSql.append(" WHERE "); append(toInsSql, tp->pk, " AND ", " a.%s IS NULL", selfCols); @@ -340,8 +335,7 @@ DB::Connection::patchInserts(TablePatch * tp) // Build SQL for copying new records ------------------------------- // ----------------------------------------------------------------- AdHoc::Buffer toInsSql; - toInsSql.appendbf("INSERT INTO %s(", - tp->dest); + toInsSql.appendbf("INSERT INTO %s(", tp->dest); append(toInsSql, tp->cols, ", ", "%s", selfCols); toInsSql.append(")\n"); patchInsertsSelect(toInsSql, tp); @@ -359,4 +353,3 @@ DB::PatchCheckFailure::message() const noexcept { return "Santiy checks failed: check table names and keys"; } - diff --git a/libdbpp/tablepatch.h b/libdbpp/tablepatch.h index 46521dc..be8aec0 100644 --- a/libdbpp/tablepatch.h +++ b/libdbpp/tablepatch.h @@ -1,58 +1,57 @@ #ifndef TABLEPATCH_H #define TABLEPATCH_H -#include -#include -#include #include +#include +#include #include #include -#include +#include +#include namespace DB { class SqlWriter; /// Table patch settings. class DLL_PUBLIC TablePatch { - private: - using TableName = std::string; - using ColumnName = std::string; - using ColumnNames = std::set; - using PrimaryKey = ColumnNames; - using PKI = PrimaryKey::const_iterator; - using AuditFunction = std::function; + private: + using TableName = std::string; + using ColumnName = std::string; + using ColumnNames = std::set; + using PrimaryKey = ColumnNames; + using PKI = PrimaryKey::const_iterator; + using AuditFunction = std::function; - public: - /// Source table name. - TableName src; - /// Source expression. - SqlWriter * srcExpr { nullptr }; - /// Destination table name. - TableName dest; - /// Columns comprising the [effective] primary key. - PrimaryKey pk; - /// Columns to be updated in the path. - ColumnNames cols; - /// An optional SQL writer to replace the default delete operation. - SqlWriter * insteadOfDelete { nullptr }; - /// An optional SQL writer to append a where clause. - SqlWriter * where { nullptr }; - /// An optional SQL writer to append an order by clause. - SqlWriter * order { nullptr }; - /// Enable deletion - bool doDeletes { true }; - /// Enable updates - bool doUpdates { true }; - /// Enable insertion - bool doInserts { true }; - /// Before delete audit - AuditFunction beforeDelete; - /// Before update audit - AuditFunction beforeUpdate; - /// Before insert audit - AuditFunction beforeInsert; + public: + /// Source table name. + TableName src; + /// Source expression. + SqlWriter * srcExpr {nullptr}; + /// Destination table name. + TableName dest; + /// Columns comprising the [effective] primary key. + PrimaryKey pk; + /// Columns to be updated in the path. + ColumnNames cols; + /// An optional SQL writer to replace the default delete operation. + SqlWriter * insteadOfDelete {nullptr}; + /// An optional SQL writer to append a where clause. + SqlWriter * where {nullptr}; + /// An optional SQL writer to append an order by clause. + SqlWriter * order {nullptr}; + /// Enable deletion + bool doDeletes {true}; + /// Enable updates + bool doUpdates {true}; + /// Enable insertion + bool doInserts {true}; + /// Before delete audit + AuditFunction beforeDelete; + /// Before update audit + AuditFunction beforeUpdate; + /// Before insert audit + AuditFunction beforeInsert; }; } #endif - diff --git a/libdbpp/testCore.cpp b/libdbpp/testCore.cpp index d29480b..4887a79 100644 --- a/libdbpp/testCore.cpp +++ b/libdbpp/testCore.cpp @@ -1,40 +1,70 @@ #include "testCore.h" -#include #include #include #include #include +#include namespace DB { -TestCore::TestCore() : - testString("Some C String"), - testDateTime(boost::posix_time::from_time_t(1430530593)), - testInterval(boost::posix_time::time_duration(1, 2, 3)), - testBlobData([](){ - AdHoc::FileUtils::MemMap f("/proc/self/exe"); - return std::vector(f.sv().begin(), f.sv().end()); - }()), - testBlob(testBlobData) -{ -} + TestCore::TestCore() : + testString("Some C String"), testDateTime(boost::posix_time::from_time_t(1430530593)), + testInterval(boost::posix_time::time_duration(1, 2, 3)), testBlobData([]() { + AdHoc::FileUtils::MemMap f("/proc/self/exe"); + return std::vector(f.sv().begin(), f.sv().end()); + }()), + testBlob(testBlobData) + { + } -template -class Assert : public DB::HandleField { + template class Assert : public DB::HandleField { public: explicit Assert(const T & e) : expected(e) { } - void floatingpoint(double v) override { (*this)(v); } - void integer(int64_t v) override { (*this)(v); } - void boolean(bool v) override { (*this)(v); } - void string(const std::string_view v) override { (*this)(v); } - void timestamp(const boost::posix_time::ptime & v) override { (*this)(v); } - void interval(const boost::posix_time::time_duration & v) override { (*this)(v); } - void blob(const Blob & v) override { (*this)(v); } - void null() override { } + void + floatingpoint(double v) override + { + (*this)(v); + } + void + integer(int64_t v) override + { + (*this)(v); + } + void + boolean(bool v) override + { + (*this)(v); + } + void + string(const std::string_view v) override + { + (*this)(v); + } + void + timestamp(const boost::posix_time::ptime & v) override + { + (*this)(v); + } + void + interval(const boost::posix_time::time_duration & v) override + { + (*this)(v); + } + void + blob(const Blob & v) override + { + (*this)(v); + } + void + null() override + { + } - template - void operator()(const D & v) { + template + void + operator()(const D & v) + { if constexpr (std::is_convertible::value) { BOOST_REQUIRE_EQUAL(expected, v); } @@ -46,50 +76,54 @@ class Assert : public DB::HandleField { private: const T & expected; -}; + }; -template -void -TestCore::assertScalarValueHelper(DB::SelectCommand & sel, const T & t) const -{ - while (sel.fetch()) { - assertColumnValueHelper(sel, 0, t); + template + void + TestCore::assertScalarValueHelper(DB::SelectCommand & sel, const T & t) const + { + while (sel.fetch()) { + assertColumnValueHelper(sel, 0, t); + } } -} -template -void -TestCore::assertColumnValueHelper(DB::SelectCommand & sel, unsigned int col, const T & t) const -{ - Assert a(t); - sel[col].apply(a); -} + template + void + TestCore::assertColumnValueHelper(DB::SelectCommand & sel, unsigned int col, const T & t) const + { + Assert a(t); + sel[col].apply(a); + } -AdHocFormatter(BlobDbg, "Blob[length=%?, addr=%?]"); -std::ostream & -operator<<(std::ostream & s, const DB::Blob b) -{ - BlobDbg::write(s, b.len, b.data); - return s; -} + AdHocFormatter(BlobDbg, "Blob[length=%?, addr=%?]"); + std::ostream & + operator<<(std::ostream & s, const DB::Blob b) + { + BlobDbg::write(s, b.len, b.data); + return s; + } -template void TestCore::assertScalarValueHelper(SelectCommand &, const bool &) const; -template void TestCore::assertScalarValueHelper(SelectCommand &, const int64_t &) const; -template void TestCore::assertScalarValueHelper(SelectCommand &, const int &) const; -template void TestCore::assertScalarValueHelper(SelectCommand &, const double &) const; -template void TestCore::assertScalarValueHelper(SelectCommand &, const std::string_view &) const; -template void TestCore::assertScalarValueHelper(SelectCommand &, const boost::posix_time::ptime &) const; -template void TestCore::assertScalarValueHelper(SelectCommand &, const boost::posix_time::time_duration &) const; -template void TestCore::assertScalarValueHelper(SelectCommand &, const DB::Blob &) const; + template void TestCore::assertScalarValueHelper(SelectCommand &, const bool &) const; + template void TestCore::assertScalarValueHelper(SelectCommand &, const int64_t &) const; + template void TestCore::assertScalarValueHelper(SelectCommand &, const int &) const; + template void TestCore::assertScalarValueHelper(SelectCommand &, const double &) const; + template void TestCore::assertScalarValueHelper(SelectCommand &, const std::string_view &) const; + template void TestCore::assertScalarValueHelper( + SelectCommand &, const boost::posix_time::ptime &) const; + template void TestCore::assertScalarValueHelper( + SelectCommand &, const boost::posix_time::time_duration &) const; + template void TestCore::assertScalarValueHelper(SelectCommand &, const DB::Blob &) const; -template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const bool &) const; -template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const int &) const; -template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const int64_t &) const; -template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const double &) const; -template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const std::string_view &) const; -template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const boost::posix_time::ptime &) const; -template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const boost::posix_time::time_duration &) const; -template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const DB::Blob &) const; + template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const bool &) const; + template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const int &) const; + template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const int64_t &) const; + template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const double &) const; + template void TestCore::assertColumnValueHelper( + SelectCommand &, unsigned int, const std::string_view &) const; + template void TestCore::assertColumnValueHelper( + SelectCommand &, unsigned int, const boost::posix_time::ptime &) const; + template void TestCore::assertColumnValueHelper( + SelectCommand &, unsigned int, const boost::posix_time::time_duration &) const; + template void TestCore::assertColumnValueHelper(SelectCommand &, unsigned int, const DB::Blob &) const; } - diff --git a/libdbpp/testCore.h b/libdbpp/testCore.h index 06aedf0..ea1f01b 100644 --- a/libdbpp/testCore.h +++ b/libdbpp/testCore.h @@ -6,17 +6,17 @@ namespace DB { -class SelectCommand; + class SelectCommand; -/// @cond -class DLL_PUBLIC TestCore { + /// @cond + class DLL_PUBLIC TestCore { protected: TestCore(); - int64_t testInt { 43 }; - double testDouble { 3.14 }; + int64_t testInt {43}; + double testDouble {3.14}; std::string_view testString; - bool testBool { false }; + bool testBool {false}; boost::posix_time::ptime testDateTime; boost::posix_time::time_duration testInterval; std::vector testBlobData; @@ -24,14 +24,12 @@ class DLL_PUBLIC TestCore { template void assertScalarValueHelper(SelectCommand & sel, const T & t) const; template void assertColumnValueHelper(SelectCommand & sel, unsigned int col, const T & t) const; -}; -/// @endcond + }; + /// @endcond -DLL_PUBLIC -std::ostream & -operator<<(std::ostream & s, const Blob b); + DLL_PUBLIC + std::ostream & operator<<(std::ostream & s, const Blob b); } #endif - diff --git a/libdbpp/unittests/libdbpp-mysql b/libdbpp/unittests/libdbpp-mysql index ef7a210..d77f801 160000 --- a/libdbpp/unittests/libdbpp-mysql +++ b/libdbpp/unittests/libdbpp-mysql @@ -1 +1 @@ -Subproject commit ef7a2108654dd8afb18fd27f0f84f152f7f796cc +Subproject commit d77f801dc01c5e30c0d96e907c8ac14f23d7b630 diff --git a/libdbpp/unittests/libdbpp-odbc b/libdbpp/unittests/libdbpp-odbc index e5c210f..22e0839 160000 --- a/libdbpp/unittests/libdbpp-odbc +++ b/libdbpp/unittests/libdbpp-odbc @@ -1 +1 @@ -Subproject commit e5c210fcbddcbb73ca387cf0eb3c5a6f91b2f4a6 +Subproject commit 22e0839fd6912b888b7c3c790573aef1f5df3936 diff --git a/libdbpp/unittests/libdbpp-postgresql b/libdbpp/unittests/libdbpp-postgresql index 4487208..3bfa3da 160000 --- a/libdbpp/unittests/libdbpp-postgresql +++ b/libdbpp/unittests/libdbpp-postgresql @@ -1 +1 @@ -Subproject commit 448720848b383639c37f5f0487efdf8c0f0ed433 +Subproject commit 3bfa3dafe335479aade55507719071f7dceb0d8c diff --git a/libdbpp/unittests/libdbpp-sqlite b/libdbpp/unittests/libdbpp-sqlite index f571f6b..0af57e2 160000 --- a/libdbpp/unittests/libdbpp-sqlite +++ b/libdbpp/unittests/libdbpp-sqlite @@ -1 +1 @@ -Subproject commit f571f6b2bf1370b0757c29162988a40e02a82f91 +Subproject commit 0af57e2595922c9ee59d7cd489daf37a3550496c diff --git a/libdbpp/unittests/mockdb.cpp b/libdbpp/unittests/mockdb.cpp index 54c1e3a..722592a 100644 --- a/libdbpp/unittests/mockdb.cpp +++ b/libdbpp/unittests/mockdb.cpp @@ -2,9 +2,7 @@ // LCOV_EXCL_START -MockDb::MockDb(const std::string &) -{ -} +MockDb::MockDb(const std::string &) { } void MockDb::beginTxInt() @@ -22,7 +20,6 @@ MockDb::rollbackTxInt() void MockDb::ping() const { - } DB::BulkDeleteStyle @@ -85,4 +82,3 @@ FACTORY(MockMock, DB::MockDatabaseFactory); FACTORY(MockDb, DB::ConnectionFactory); // LCOV_EXCL_STOP - diff --git a/libdbpp/unittests/mockdb.h b/libdbpp/unittests/mockdb.h index 379d076..f291487 100644 --- a/libdbpp/unittests/mockdb.h +++ b/libdbpp/unittests/mockdb.h @@ -5,30 +5,29 @@ #include "../mockDatabase.h" class MockDb : public DB::Connection { - public: - MockDb(const std::string &); +public: + MockDb(const std::string &); - void beginTxInt() override; - void commitTxInt() override; - void rollbackTxInt() override; - void ping() const override; - DB::BulkDeleteStyle bulkDeleteStyle() const override; - DB::BulkUpdateStyle bulkUpdateStyle() const override; + void beginTxInt() override; + void commitTxInt() override; + void rollbackTxInt() override; + void ping() const override; + DB::BulkDeleteStyle bulkDeleteStyle() const override; + DB::BulkUpdateStyle bulkUpdateStyle() const override; - void execute(const std::string & sql, const DB::CommandOptionsCPtr &) override; - DB::SelectCommandPtr select(const std::string &, const DB::CommandOptionsCPtr &) override; - DB::ModifyCommandPtr modify(const std::string &, const DB::CommandOptionsCPtr &) override; + void execute(const std::string & sql, const DB::CommandOptionsCPtr &) override; + DB::SelectCommandPtr select(const std::string &, const DB::CommandOptionsCPtr &) override; + DB::ModifyCommandPtr modify(const std::string &, const DB::CommandOptionsCPtr &) override; - mutable std::vector executed; + mutable std::vector executed; }; class MockMock : public DB::MockDatabase { - public: - MockMock(const std::string &, const std::string &, const std::vector &); - DB::ConnectionPtr openConnection() const override; - void CreateNewDatabase() const override; - void DropDatabase() const override; +public: + MockMock(const std::string &, const std::string &, const std::vector &); + DB::ConnectionPtr openConnection() const override; + void CreateNewDatabase() const override; + void DropDatabase() const override; }; #endif - diff --git a/libdbpp/unittests/testConnection.cpp b/libdbpp/unittests/testConnection.cpp index 491c236..46a8e6a 100644 --- a/libdbpp/unittests/testConnection.cpp +++ b/libdbpp/unittests/testConnection.cpp @@ -1,17 +1,17 @@ #define BOOST_TEST_MODULE DbConnection #include -#include +#include "mockdb.h" #include -#include #include -#include -#include #include +#include +#include +#include #include -#include "mockdb.h" +#include -BOOST_AUTO_TEST_CASE( create ) +BOOST_AUTO_TEST_CASE(create) { auto mock = DB::ConnectionFactory::createNew("MockDb", "doesn't matter"); BOOST_REQUIRE(mock); @@ -20,17 +20,16 @@ BOOST_AUTO_TEST_CASE( create ) BOOST_REQUIRE(!mock->select("")); } -BOOST_AUTO_TEST_CASE( resolve ) +BOOST_AUTO_TEST_CASE(resolve) { auto libname = DB::Connection::resolvePlugin(typeid(DB::Connection), "postgresql"); BOOST_REQUIRE(libname); BOOST_REQUIRE_EQUAL("libdbpp-postgresql.so", *libname); BOOST_REQUIRE_THROW( - (void)DB::ConnectionFactory::createNew("otherdb", "doesn't matter"), - AdHoc::LoadLibraryException); + (void)DB::ConnectionFactory::createNew("otherdb", "doesn't matter"), AdHoc::LoadLibraryException); } -BOOST_AUTO_TEST_CASE( finish ) +BOOST_AUTO_TEST_CASE(finish) { auto mock = DB::ConnectionFactory::createNew("MockDb", "doesn't matter"); BOOST_REQUIRE(mock); @@ -45,7 +44,7 @@ BOOST_AUTO_TEST_CASE( finish ) mock->finish(); } -BOOST_AUTO_TEST_CASE( tx ) +BOOST_AUTO_TEST_CASE(tx) { auto mock = DB::ConnectionFactory::createNew("MockDb", "doesn't matter"); BOOST_REQUIRE(mock); @@ -64,7 +63,7 @@ BOOST_AUTO_TEST_CASE( tx ) BOOST_REQUIRE_EQUAL(false, mock->inTx()); } -BOOST_AUTO_TEST_CASE( txscope ) +BOOST_AUTO_TEST_CASE(txscope) { auto mock = DB::ConnectionFactory::createNew("MockDb", "doesn't matter"); BOOST_REQUIRE(mock); @@ -84,7 +83,7 @@ BOOST_AUTO_TEST_CASE( txscope ) } } -BOOST_AUTO_TEST_CASE( savepoints ) +BOOST_AUTO_TEST_CASE(savepoints) { auto mock = DB::ConnectionFactory::createNew("MockDb", "doesn't matter"); auto mockdb = std::dynamic_pointer_cast(mock); @@ -101,7 +100,7 @@ BOOST_AUTO_TEST_CASE( savepoints ) BOOST_REQUIRE_EQUAL("ROLLBACK TO SAVEPOINT sp1", *mockdb->executed.rbegin()); } -BOOST_AUTO_TEST_CASE( commandOptions ) +BOOST_AUTO_TEST_CASE(commandOptions) { auto optsDefault = DB::CommandOptionsFactory::createNew("", 1234, {}); BOOST_REQUIRE(optsDefault); @@ -109,12 +108,9 @@ BOOST_AUTO_TEST_CASE( commandOptions ) BOOST_REQUIRE_EQUAL(1234, *optsDefault->hash); } -BOOST_AUTO_TEST_CASE( commandOptionsPq1 ) +BOOST_AUTO_TEST_CASE(commandOptionsPq1) { - auto optsBase = DB::CommandOptionsFactory::createNew("postgresql", 12345, { - {"no-cursor", ""}, - {"page-size", "5"} - }); + auto optsBase = DB::CommandOptionsFactory::createNew("postgresql", 12345, {{"no-cursor", ""}, {"page-size", "5"}}); BOOST_REQUIRE(optsBase); auto optsPq = std::dynamic_pointer_cast(optsBase); BOOST_REQUIRE(optsPq); @@ -124,11 +120,9 @@ BOOST_AUTO_TEST_CASE( commandOptionsPq1 ) BOOST_REQUIRE_EQUAL(5, optsPq->fetchTuples); } -BOOST_AUTO_TEST_CASE( commandOptionsPq2 ) +BOOST_AUTO_TEST_CASE(commandOptionsPq2) { - auto optsBase = DB::CommandOptionsFactory::createNew("postgresql", 123456, { - {"page-size", "50"} - }); + auto optsBase = DB::CommandOptionsFactory::createNew("postgresql", 123456, {{"page-size", "50"}}); BOOST_REQUIRE(optsBase); auto optsPq = std::dynamic_pointer_cast(optsBase); BOOST_REQUIRE(optsPq); @@ -137,4 +131,3 @@ BOOST_AUTO_TEST_CASE( commandOptionsPq2 ) BOOST_REQUIRE(optsPq->useCursor); BOOST_REQUIRE_EQUAL(50, optsPq->fetchTuples); } - diff --git a/libdbpp/unittests/testConnectionPool.cpp b/libdbpp/unittests/testConnectionPool.cpp index de3de79..7ef6586 100644 --- a/libdbpp/unittests/testConnectionPool.cpp +++ b/libdbpp/unittests/testConnectionPool.cpp @@ -1,20 +1,21 @@ #define BOOST_TEST_MODULE DbConnectionPool #include +#include #include #include -#include class MockPool : public DB::PluginMock, public DB::ConnectionPool { - public: - MockPool() : - PluginMock("pqmock", { }, "user=postgres dbname=postgres"), - DB::ConnectionPool(4, 2, "postgresql", stringbf("user=postgres dbname=%s", databaseName())) - { - } +public: + MockPool() : + PluginMock("pqmock", {}, "user=postgres dbname=postgres"), DB::ConnectionPool(4, 2, "postgresql", + stringbf("user=postgres dbname=%s", + databaseName())) + { + } }; -BOOST_AUTO_TEST_CASE( basic ) +BOOST_AUTO_TEST_CASE(basic) { MockPool pool; DB::Connection * cr; @@ -38,4 +39,3 @@ BOOST_AUTO_TEST_CASE( basic ) BOOST_REQUIRE_EQUAL(0, pool.inUseCount()); BOOST_REQUIRE_EQUAL(2, pool.availableCount()); } - diff --git a/libdbpp/unittests/testMock.cpp b/libdbpp/unittests/testMock.cpp index 43b757d..41c640d 100644 --- a/libdbpp/unittests/testMock.cpp +++ b/libdbpp/unittests/testMock.cpp @@ -1,20 +1,18 @@ #define BOOST_TEST_MODULE DbMock #include -#include -#include #include "../error.h" #include "../mockDatabase.h" #include "mockdb.h" +#include +#include -BOOST_AUTO_TEST_CASE( noFactory ) +BOOST_AUTO_TEST_CASE(noFactory) { - BOOST_REQUIRE_THROW({ - (void)DB::MockDatabaseFactory::get("not-found"); - }, AdHoc::LoadLibraryException); + BOOST_REQUIRE_THROW({ (void)DB::MockDatabaseFactory::get("not-found"); }, AdHoc::LoadLibraryException); } -BOOST_AUTO_TEST_CASE( mockFactory ) +BOOST_AUTO_TEST_CASE(mockFactory) { auto f = DB::MockDatabaseFactory::get("MockMock"); BOOST_REQUIRE(f); @@ -26,19 +24,22 @@ BOOST_AUTO_TEST_CASE( mockFactory ) BOOST_REQUIRE_EQUAL(typeid(MockDb), typeid(cr)); } -BOOST_AUTO_TEST_CASE( missingMock ) +BOOST_AUTO_TEST_CASE(missingMock) { - BOOST_REQUIRE_THROW({ - (void)DB::MockDatabaseFactory::createNew("MockMock", - "user=postgres dbname=postgres", typeid(this).name(), { rootDir / "missing.sql" }); - }, std::fstream::failure); + BOOST_REQUIRE_THROW( + { + (void)DB::MockDatabaseFactory::createNew( + "MockMock", "user=postgres dbname=postgres", typeid(this).name(), {rootDir / "missing.sql"}); + }, + std::fstream::failure); } -BOOST_AUTO_TEST_CASE( failingMock ) +BOOST_AUTO_TEST_CASE(failingMock) { - BOOST_REQUIRE_THROW({ - (void)DB::MockDatabaseFactory::createNew("MockMock", - "user=postgres dbname=postgres", typeid(this).name(), { rootDir / "badMock.sql" }); - }, DB::Error); + BOOST_REQUIRE_THROW( + { + (void)DB::MockDatabaseFactory::createNew( + "MockMock", "user=postgres dbname=postgres", typeid(this).name(), {rootDir / "badMock.sql"}); + }, + DB::Error); } - diff --git a/libdbpp/unittests/testParse.cpp b/libdbpp/unittests/testParse.cpp index 3764f43..6991242 100644 --- a/libdbpp/unittests/testParse.cpp +++ b/libdbpp/unittests/testParse.cpp @@ -1,92 +1,94 @@ #define BOOST_TEST_MODULE DbConnection #include -#include #include #include -#include -#include #include +#include +#include #include +#include using SQLs = std::vector; BOOST_TEST_SPECIALIZED_COLLECTION_COMPARE(SQLs); class RecordingParser : std::fstream, public DB::SqlParse { - public: - explicit RecordingParser(const std::filesystem::path & p) : - std::fstream(p), - DB::SqlParse(*this, p.parent_path()) - { - } - - void Comment(const std::string & c) const override - { - comments.push_back(c); - } - - void Statement(const std::string & s) const override - { - executed.push_back(s); - } - - mutable SQLs comments; - mutable SQLs executed; +public: + explicit RecordingParser(const std::filesystem::path & p) : + std::fstream(p), DB::SqlParse(*this, p.parent_path()) { } + + void + Comment(const std::string & c) const override + { + comments.push_back(c); + } + + void + Statement(const std::string & s) const override + { + executed.push_back(s); + } + + mutable SQLs comments; + mutable SQLs executed; }; template -void assertFail(const std::filesystem::path & p) +void +assertFail(const std::filesystem::path & p) { BOOST_TEST_CONTEXT(p) { - BOOST_REQUIRE_THROW({ - RecordingParser s(p); - s.Execute(); - }, E); + BOOST_REQUIRE_THROW( + { + RecordingParser s(p); + s.Execute(); + }, + E); } } -BOOST_AUTO_TEST_CASE( parseBad ) +BOOST_AUTO_TEST_CASE(parseBad) { assertFail("/bad"); } -BOOST_AUTO_TEST_CASE( parse ) +BOOST_AUTO_TEST_CASE(parse) { RecordingParser p(rootDir / "parseTest.sql"); p.Execute(); BOOST_REQUIRE_EQUAL(p.executed.size(), 3); BOOST_REQUIRE_EQUAL(p.executed[1], "INSERT INTO name(t, i) VALUES('string', 3)"); auto cs = { - "Single line comment", - "", - "", - "", - "", - "Comment", - "", - "", - "", - "Multi line\n\t comment", - "! Stupid MySQL terminates", - "! comments with a ;", - "! Because reasons", + "Single line comment", + "", + "", + "", + "", + "Comment", + "", + "", + "", + "Multi line\n\t comment", + "! Stupid MySQL terminates", + "! comments with a ;", + "! Because reasons", }; BOOST_CHECK_EQUAL_COLLECTIONS(p.comments.begin(), p.comments.end(), cs.begin(), cs.end()); } -BOOST_AUTO_TEST_CASE( parseDollarQuote ) +BOOST_AUTO_TEST_CASE(parseDollarQuote) { RecordingParser p(rootDir / "dollarQuote.sql"); p.Execute(); } -BOOST_AUTO_TEST_CASE( parseScriptDir ) +BOOST_AUTO_TEST_CASE(parseScriptDir) { RecordingParser p(rootDir / "scriptDir.sql"); p.Execute(); } -BOOST_AUTO_TEST_CASE( parseStringParse ) +BOOST_AUTO_TEST_CASE(parseStringParse) { RecordingParser p(rootDir / "stringParse.sql"); p.Execute(); @@ -94,7 +96,7 @@ BOOST_AUTO_TEST_CASE( parseStringParse ) BOOST_REQUIRE_EQUAL("INSERT INTO name(t, i) VALUES('fancy string '' \\' \\r \\n', 7)", p.executed[1]); } -BOOST_AUTO_TEST_CASE( indentedStatement ) +BOOST_AUTO_TEST_CASE(indentedStatement) { RecordingParser p(rootDir / "indentedStatement.sql"); p.Execute(); @@ -103,7 +105,7 @@ BOOST_AUTO_TEST_CASE( indentedStatement ) BOOST_REQUIRE(p.comments.empty()); } -BOOST_AUTO_TEST_CASE( indentedOneLineComment ) +BOOST_AUTO_TEST_CASE(indentedOneLineComment) { RecordingParser p(rootDir / "indentedOneLineComment.sql"); p.Execute(); @@ -112,7 +114,7 @@ BOOST_AUTO_TEST_CASE( indentedOneLineComment ) BOOST_REQUIRE(p.executed.empty()); } -BOOST_AUTO_TEST_CASE( indentedBlockComment ) +BOOST_AUTO_TEST_CASE(indentedBlockComment) { RecordingParser p(rootDir / "indentedBlockComment.sql"); p.Execute(); @@ -121,7 +123,7 @@ BOOST_AUTO_TEST_CASE( indentedBlockComment ) BOOST_REQUIRE(p.executed.empty()); } -BOOST_AUTO_TEST_CASE( commentsMixedIn ) +BOOST_AUTO_TEST_CASE(commentsMixedIn) { RecordingParser p(rootDir / "commentsMixedIn.sql"); p.Execute(); @@ -133,18 +135,17 @@ BOOST_AUTO_TEST_CASE( commentsMixedIn ) BOOST_REQUIRE_EQUAL("And a timestamp", p.comments[2]); } -BOOST_AUTO_TEST_CASE( parseUnterminateComment ) +BOOST_AUTO_TEST_CASE(parseUnterminateComment) { assertFail(rootDir / "unterminatedComment.sql"); } -BOOST_AUTO_TEST_CASE( parseUnterminateDollarQuote ) +BOOST_AUTO_TEST_CASE(parseUnterminateDollarQuote) { assertFail(rootDir / "unterminatedDollarQuote.sql"); } -BOOST_AUTO_TEST_CASE( parseUnterminateString ) +BOOST_AUTO_TEST_CASE(parseUnterminateString) { assertFail(rootDir / "unterminatedString.sql"); } - diff --git a/libdbpp/unittests/testPatch.cpp b/libdbpp/unittests/testPatch.cpp index 53fb49e..e81f9d7 100644 --- a/libdbpp/unittests/testPatch.cpp +++ b/libdbpp/unittests/testPatch.cpp @@ -1,55 +1,56 @@ #define BOOST_TEST_MODULE DbTablePatch #include +#include +#include #include #include #include -#include -#include -#include -#include #include +#include +#include class Mock : public DB::PluginMock { - public: - Mock() : - DB::PluginMock("pqmock", { rootDir / "patch.sql" }, "user=postgres dbname=postgres") - { - } +public: + Mock() : DB::PluginMock("pqmock", {rootDir / "patch.sql"}, "user=postgres dbname=postgres") { } }; class OrderByA : public DB::StaticSqlWriter { - public: - OrderByA() : DB::StaticSqlWriter("a") { } +public: + OrderByA() : DB::StaticSqlWriter("a") { } }; class WhereAequals1 : public DB::SqlWriter { - public: - void writeSql(AdHoc::Buffer & b) override - { - b.append("a.a = ?"); - } - void bindParams(DB::Command * cmd, unsigned int & o) override - { - cmd->bindParamI(o++, 1); - } +public: + void + writeSql(AdHoc::Buffer & b) override + { + b.append("a.a = ?"); + } + void + bindParams(DB::Command * cmd, unsigned int & o) override + { + cmd->bindParamI(o++, 1); + } }; class MarkDeleted : public DB::SqlWriter { - public: - void writeSql(AdHoc::Buffer & b) override - { - b.append("deleted = ?"); - } - void bindParams(DB::Command * cmd, unsigned int & o) override - { - cmd->bindParamB(o++, true); - } +public: + void + writeSql(AdHoc::Buffer & b) override + { + b.append("deleted = ?"); + } + void + bindParams(DB::Command * cmd, unsigned int & o) override + { + cmd->bindParamB(o++, true); + } }; BOOST_FIXTURE_TEST_SUITE(mock, Mock); -BOOST_AUTO_TEST_CASE( sanityFail ) +BOOST_AUTO_TEST_CASE(sanityFail) { auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); BOOST_REQUIRE(db); @@ -60,7 +61,7 @@ BOOST_AUTO_TEST_CASE( sanityFail ) BOOST_REQUIRE_THROW(db->patchTable(&tp), DB::PatchCheckFailure); } -BOOST_AUTO_TEST_CASE( noTx ) +BOOST_AUTO_TEST_CASE(noTx) { auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); BOOST_REQUIRE(db); @@ -74,7 +75,7 @@ BOOST_AUTO_TEST_CASE( noTx ) BOOST_AUTO_TEST_SUITE_END(); -BOOST_AUTO_TEST_CASE( testBasic ) +BOOST_AUTO_TEST_CASE(testBasic) { Mock mock; auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); @@ -98,7 +99,7 @@ BOOST_AUTO_TEST_CASE( testBasic ) BOOST_REQUIRE_EQUAL(0, r2.updates); } -BOOST_AUTO_TEST_CASE( allKeys ) +BOOST_AUTO_TEST_CASE(allKeys) { Mock mock; auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); @@ -116,7 +117,7 @@ BOOST_AUTO_TEST_CASE( allKeys ) BOOST_REQUIRE_EQUAL(0, r.updates); } -BOOST_AUTO_TEST_CASE( testOrder ) +BOOST_AUTO_TEST_CASE(testOrder) { Mock mock; auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); @@ -129,20 +130,21 @@ BOOST_AUTO_TEST_CASE( testOrder ) tp.pk = {"a", "b"}; tp.order = ℴ tp.beforeDelete = [](const DB::SelectCommandPtr & i) { - i->forEachRow([](auto a, auto b, auto c, auto d) { - fprintf(stderr, "<< %ld %ld %s %s\n", a, b, c.c_str(), d.c_str()); - }); - }; + i->forEachRow([](auto a, auto b, auto c, auto d) { + fprintf(stderr, "<< %ld %ld %s %s\n", a, b, c.c_str(), d.c_str()); + }); + }; tp.beforeUpdate = [](const DB::SelectCommandPtr & i) { - i->forEachRow([](auto a, auto b, auto c1, auto d1, auto c2, auto d2) { - fprintf(stderr, "== %ld %ld %s->%s %s->%s\n", a, b, c1.c_str(), c2.c_str(), d1.c_str(), d2.c_str()); - }); - }; + i->forEachRow( + [](auto a, auto b, auto c1, auto d1, auto c2, auto d2) { + fprintf(stderr, "== %ld %ld %s->%s %s->%s\n", a, b, c1.c_str(), c2.c_str(), d1.c_str(), d2.c_str()); + }); + }; tp.beforeInsert = [](const DB::SelectCommandPtr & i) { - i->forEachRow([](auto a, auto b, auto c, auto d) { - fprintf(stderr, ">> %ld %ld %s %s\n", a, b, c.c_str(), d.c_str()); - }); - }; + i->forEachRow([](auto a, auto b, auto c, auto d) { + fprintf(stderr, ">> %ld %ld %s %s\n", a, b, c.c_str(), d.c_str()); + }); + }; db->beginTx(); auto r = db->patchTable(&tp); db->commitTx(); @@ -151,7 +153,7 @@ BOOST_AUTO_TEST_CASE( testOrder ) BOOST_REQUIRE_EQUAL(1, r.updates); } -BOOST_AUTO_TEST_CASE( testWhere ) +BOOST_AUTO_TEST_CASE(testWhere) { Mock mock; auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); @@ -171,7 +173,7 @@ BOOST_AUTO_TEST_CASE( testWhere ) BOOST_REQUIRE_EQUAL(1, r.updates); } -BOOST_AUTO_TEST_CASE( testInstead ) +BOOST_AUTO_TEST_CASE(testInstead) { Mock mock; auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); @@ -191,7 +193,7 @@ BOOST_AUTO_TEST_CASE( testInstead ) BOOST_REQUIRE_EQUAL(1, r.updates); } -BOOST_AUTO_TEST_CASE( testSrcExprTable ) +BOOST_AUTO_TEST_CASE(testSrcExprTable) { Mock mock; DB::StaticSqlWriter s("source"); @@ -210,7 +212,7 @@ BOOST_AUTO_TEST_CASE( testSrcExprTable ) BOOST_REQUIRE_EQUAL(1, r.updates); } -BOOST_AUTO_TEST_CASE( testSrcExprSelectTable ) +BOOST_AUTO_TEST_CASE(testSrcExprSelectTable) { Mock mock; DB::StaticSqlWriter s("(SELECT * FROM source)"); @@ -230,22 +232,19 @@ BOOST_AUTO_TEST_CASE( testSrcExprSelectTable ) } class BindInt : public DB::StaticSqlWriter { - public: - BindInt(const std::string & s, int i) : - DB::StaticSqlWriter(s), - myInt(i) - { - } +public: + BindInt(const std::string & s, int i) : DB::StaticSqlWriter(s), myInt(i) { } - void bindParams(DB::Command * c, unsigned int & offset) override - { - c->bindParamI(offset++, myInt); - } + void + bindParams(DB::Command * c, unsigned int & offset) override + { + c->bindParamI(offset++, myInt); + } - int myInt; + int myInt; }; -BOOST_AUTO_TEST_CASE( testSrcExprSelectFilteredTable ) +BOOST_AUTO_TEST_CASE(testSrcExprSelectFilteredTable) { Mock mock; BindInt s("(SELECT s.* FROM source s WHERE s.a = ?)", 1); @@ -263,4 +262,3 @@ BOOST_AUTO_TEST_CASE( testSrcExprSelectFilteredTable ) BOOST_REQUIRE_EQUAL(1, r.inserts); BOOST_REQUIRE_EQUAL(1, r.updates); } - diff --git a/libdbpp/unittests/testUtils.cpp b/libdbpp/unittests/testUtils.cpp index 9ceef54..4d1adbe 100644 --- a/libdbpp/unittests/testUtils.cpp +++ b/libdbpp/unittests/testUtils.cpp @@ -1,29 +1,28 @@ #define BOOST_TEST_MODULE DbUtil #include +#include +#include +#include #include -#include -#include -#include #include #include +#include #include -#include -#include -#include +#include +#include #include class StandardMockDatabase : public DB::PluginMock { - public: - StandardMockDatabase() : DB::PluginMock("pqmock", { - rootDir / "util.sql" }, "user=postgres dbname=postgres") - { - } +public: + StandardMockDatabase() : DB::PluginMock("pqmock", {rootDir / "util.sql"}, "user=postgres dbname=postgres") + { + } }; -BOOST_GLOBAL_FIXTURE( StandardMockDatabase ); +BOOST_GLOBAL_FIXTURE(StandardMockDatabase); -BOOST_AUTO_TEST_CASE( forEachRow ) +BOOST_AUTO_TEST_CASE(forEachRow) { auto db = DB::MockDatabase::openConnectionTo("pqmock"); auto sel = db->select("SELECT a, b, c, d, e, f FROM forEachRow ORDER BY a LIMIT 1"); @@ -32,17 +31,18 @@ BOOST_AUTO_TEST_CASE( forEachRow ) BOOST_REQUIRE_EQUAL(1, a); BOOST_REQUIRE_CLOSE(4.3, b, 0.001); BOOST_REQUIRE_EQUAL("Some text", c); - BOOST_REQUIRE_EQUAL(boost::posix_time::ptime_from_tm({ 17, 39, 13, 7, 10, 115, 0, 0, 0, 0, nullptr}), d); + BOOST_REQUIRE_EQUAL(boost::posix_time::ptime_from_tm({17, 39, 13, 7, 10, 115, 0, 0, 0, 0, nullptr}), d); BOOST_REQUIRE_EQUAL(boost::posix_time::time_duration(4, 3, 2), e); BOOST_REQUIRE_EQUAL(true, f); }); } -BOOST_AUTO_TEST_CASE( forEachRowNulls ) +BOOST_AUTO_TEST_CASE(forEachRowNulls) { auto db = DB::MockDatabase::openConnectionTo("pqmock"); auto sel = db->select("SELECT a, b, c, d, e, f FROM forEachRow ORDER BY a DESC LIMIT 1"); - sel->forEachRow, std::string, std::optional, std::optional, bool>( + sel->forEachRow, std::string, std::optional, + std::optional, bool>( [](auto && a, auto b, auto c, auto d, auto && e, auto f) { BOOST_REQUIRE_EQUAL(2, a); BOOST_REQUIRE(b); @@ -54,7 +54,7 @@ BOOST_AUTO_TEST_CASE( forEachRowNulls ) }); } -BOOST_AUTO_TEST_CASE( stdforOverRows ) +BOOST_AUTO_TEST_CASE(stdforOverRows) { auto db = DB::MockDatabase::openConnectionTo("pqmock"); unsigned int count = 0; @@ -75,14 +75,14 @@ BOOST_AUTO_TEST_CASE( stdforOverRows ) BOOST_REQUIRE_EQUAL(totalOfc, "Some textSome text"); } -BOOST_AUTO_TEST_CASE( stdforOverRowsStructuredBinding ) +BOOST_AUTO_TEST_CASE(stdforOverRowsStructuredBinding) { auto db = DB::MockDatabase::openConnectionTo("pqmock"); unsigned int count = 0; int64_t totalOfa = 0; std::string totalOfc; auto sel = db->select("SELECT a, c FROM forEachRow ORDER BY a DESC"); - for (const auto [ a, c ] : sel->as()) { + for (const auto [a, c] : sel->as()) { count += 1; totalOfa += a; totalOfc += c; @@ -92,14 +92,14 @@ BOOST_AUTO_TEST_CASE( stdforOverRowsStructuredBinding ) BOOST_REQUIRE_EQUAL(totalOfc, "Some textSome text"); } -BOOST_AUTO_TEST_CASE( stdforOverRowsStructuredBindingOptional ) +BOOST_AUTO_TEST_CASE(stdforOverRowsStructuredBindingOptional) { auto db = DB::MockDatabase::openConnectionTo("pqmock"); unsigned int count = 0; int64_t totalOfa = 0; std::string totalOfc; auto sel = db->select("SELECT a, c FROM forEachRow ORDER BY a DESC"); - for (const auto [ a, c ] : sel->as, std::optional>()) { + for (const auto [a, c] : sel->as, std::optional>()) { count += 1; BOOST_REQUIRE(a); totalOfa += *a; @@ -111,13 +111,13 @@ BOOST_AUTO_TEST_CASE( stdforOverRowsStructuredBindingOptional ) BOOST_REQUIRE_EQUAL(totalOfc, "Some textSome text"); } -BOOST_AUTO_TEST_CASE( execute ) +BOOST_AUTO_TEST_CASE(execute) { auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); db->execute("UPDATE forEachRow SET a = 2"); } -BOOST_AUTO_TEST_CASE( columns ) +BOOST_AUTO_TEST_CASE(columns) { auto db = DB::MockDatabase::openConnectionTo("pqmock"); auto sel = db->select("SELECT a, b, c, d, e FROM forEachRow ORDER BY a LIMIT 1"); @@ -136,7 +136,7 @@ BOOST_AUTO_TEST_CASE( columns ) BOOST_REQUIRE_THROW((void)(*sel)[""], DB::ColumnDoesNotExist); } -BOOST_AUTO_TEST_CASE( extract ) +BOOST_AUTO_TEST_CASE(extract) { auto db = DB::MockDatabase::openConnectionTo("pqmock"); auto sel = db->select("SELECT a, b, c FROM forEachRow WHERE f"); @@ -164,7 +164,7 @@ BOOST_AUTO_TEST_CASE( extract ) BOOST_REQUIRE(!sel->fetch()); } -BOOST_AUTO_TEST_CASE( bulkLoadStream ) +BOOST_AUTO_TEST_CASE(bulkLoadStream) { std::ifstream in(rootDir / "source.dat"); auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); @@ -172,11 +172,11 @@ BOOST_AUTO_TEST_CASE( bulkLoadStream ) BOOST_REQUIRE_EQUAL(56, db->bulkUploadData(in)); db->endBulkUpload(nullptr); db->select("SELECT COUNT(*) FROM bulk1")->forEachRow([](auto n) { - BOOST_REQUIRE_EQUAL(4, n); - }); + BOOST_REQUIRE_EQUAL(4, n); + }); } -BOOST_AUTO_TEST_CASE( bulkLoadFile ) +BOOST_AUTO_TEST_CASE(bulkLoadFile) { auto f = fopen((rootDir / "source.dat").c_str(), "r"); auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); @@ -185,12 +185,12 @@ BOOST_AUTO_TEST_CASE( bulkLoadFile ) db->endBulkUpload(nullptr); fclose(f); db->select("SELECT COUNT(*) FROM bulk2")->forEachRow([](auto n) { - BOOST_REQUIRE_EQUAL(4, n); - }); + BOOST_REQUIRE_EQUAL(4, n); + }); } using StringTypes = boost::mpl::list; -BOOST_AUTO_TEST_CASE_TEMPLATE( nullBind, Str, StringTypes ) +BOOST_AUTO_TEST_CASE_TEMPLATE(nullBind, Str, StringTypes) { auto db = DB::MockDatabase::openConnectionTo("pqmock"); db->execute("DELETE FROM forEachRow"); @@ -202,7 +202,8 @@ BOOST_AUTO_TEST_CASE_TEMPLATE( nullBind, Str, StringTypes ) ins->bindParamT(4, std::optional()); ins->bindParamB(5, std::optional()); ins->execute(); - auto sel = db->select("SELECT a, b, c, d, e, f FROM forEachRow WHERE a IS NULL AND b IS NULL AND c IS NULL AND d IS NULL AND e IS NULL AND f IS NULL"); + auto sel = db->select("SELECT a, b, c, d, e, f FROM forEachRow WHERE a IS NULL AND b IS NULL AND c IS NULL AND d " + "IS NULL AND e IS NULL AND f IS NULL"); unsigned int count = 0; for (const auto & row : sel->as, Str>()) { count += 1; @@ -214,7 +215,7 @@ BOOST_AUTO_TEST_CASE_TEMPLATE( nullBind, Str, StringTypes ) BOOST_REQUIRE_EQUAL(1, count); } -BOOST_AUTO_TEST_CASE( iceNullBind ) +BOOST_AUTO_TEST_CASE(iceNullBind) { auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); auto ins = db->modify("INSERT INTO forEachRow VALUES(?, ?, ?, ?, ?, ?)"); @@ -225,7 +226,8 @@ BOOST_AUTO_TEST_CASE( iceNullBind ) ins->bindParamT(4, IceUtil::Optional()); ins->bindParamB(5, IceUtil::Optional()); ins->execute(); - auto sel = db->select("SELECT a, b, c, d, e, f FROM forEachRow WHERE a IS NULL AND b IS NULL AND c IS NULL AND d IS NULL AND e IS NULL AND f IS NULL"); + auto sel = db->select("SELECT a, b, c, d, e, f FROM forEachRow WHERE a IS NULL AND b IS NULL AND c IS NULL AND d " + "IS NULL AND e IS NULL AND f IS NULL"); unsigned int count = 0; for (const auto & row : sel->as<>()) { (void)row; @@ -234,7 +236,7 @@ BOOST_AUTO_TEST_CASE( iceNullBind ) BOOST_REQUIRE_EQUAL(2, count); } -BOOST_AUTO_TEST_CASE( charStarBindNull ) +BOOST_AUTO_TEST_CASE(charStarBindNull) { auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); db->modify("DELETE FROM forEachRow")->execute(); @@ -261,7 +263,7 @@ BOOST_AUTO_TEST_CASE( charStarBindNull ) } } -BOOST_AUTO_TEST_CASE( bind ) +BOOST_AUTO_TEST_CASE(bind) { auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); auto m = db->modify("doesn't matter, only testing compile"); @@ -270,7 +272,7 @@ BOOST_AUTO_TEST_CASE( bind ) m->bindParamI(0, (time_t)1); } -BOOST_AUTO_TEST_CASE( bindIntPtr ) +BOOST_AUTO_TEST_CASE(bindIntPtr) { auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); db->modify("DELETE FROM forEachRow")->execute(); @@ -301,7 +303,7 @@ BOOST_AUTO_TEST_CASE( bindIntPtr ) BOOST_REQUIRE_EQUAL(159, total); } -BOOST_FIXTURE_TEST_CASE( traits_bind, DB::TestCore ) +BOOST_FIXTURE_TEST_CASE(traits_bind, DB::TestCore) { using namespace std::literals; auto db = DB::ConnectionPtr(DB::MockDatabase::openConnectionTo("pqmock")); @@ -356,14 +358,14 @@ BOOST_FIXTURE_TEST_CASE( traits_bind, DB::TestCore ) check(__LINE__, std::optional(testBlob), false, testBlob, cmd2); } -BOOST_AUTO_TEST_CASE( testBlobRaw ) +BOOST_AUTO_TEST_CASE(testBlobRaw) { DB::Blob ptr(this, 1); BOOST_REQUIRE_EQUAL(ptr.data, this); BOOST_REQUIRE_EQUAL(ptr.len, 1); } -BOOST_AUTO_TEST_CASE( testBlobObject ) +BOOST_AUTO_TEST_CASE(testBlobObject) { int32_t x = 20; DB::Blob obj(&x); @@ -371,7 +373,7 @@ BOOST_AUTO_TEST_CASE( testBlobObject ) BOOST_REQUIRE_EQUAL(obj.len, 4); } -BOOST_AUTO_TEST_CASE( testBlobVec ) +BOOST_AUTO_TEST_CASE(testBlobVec) { std::vector buf(20, 0); DB::Blob vec(buf); @@ -385,15 +387,15 @@ struct S { }; BOOST_STATIC_ASSERT(sizeof(S) == 16); -BOOST_AUTO_TEST_CASE( testBlobStruct ) +BOOST_AUTO_TEST_CASE(testBlobStruct) { - S s = { 8, 4 }; + S s = {8, 4}; DB::Blob str(&s); BOOST_REQUIRE_EQUAL(str.data, &s); BOOST_REQUIRE_EQUAL(str.len, 16); } -BOOST_AUTO_TEST_CASE( testBlobVecStruct ) +BOOST_AUTO_TEST_CASE(testBlobVecStruct) { std::vector buf(20, {4, 8}); DB::Blob vec(buf); @@ -401,7 +403,7 @@ BOOST_AUTO_TEST_CASE( testBlobVecStruct ) BOOST_REQUIRE_EQUAL(vec.len, 20 * 16); } -BOOST_AUTO_TEST_CASE( testBlobCompare ) +BOOST_AUTO_TEST_CASE(testBlobCompare) { std::vector buf1(20, {4, 8}); DB::Blob vec1(buf1); @@ -422,17 +424,21 @@ BOOST_AUTO_TEST_CASE( testBlobCompare ) // These just compile time support, actual data extraction should be tested by the implementing connector. template auto -testExtractT(DB::Row row) { +testExtractT(DB::Row row) +{ return row.template value<0>(); } template void -testExtractT(const DB::SelectCommandPtr & sel) { +testExtractT(const DB::SelectCommandPtr & sel) +{ // test default construct T test; (void)test; - for (const auto & row : sel->as()) { testExtractT(row); } + for (const auto & row : sel->as()) { + testExtractT(row); + } #ifdef __clang__ // Clang cannot compile this for reasons largely todo with ambiguousness in the spec // Fixed when we move to std::chrono @@ -440,11 +446,13 @@ testExtractT(const DB::SelectCommandPtr & sel) { #else if constexpr (true) { #endif - for (const auto & row : sel->as>()) { testExtractT(row); } + for (const auto & row : sel->as>()) { + testExtractT(row); + } } } -BOOST_AUTO_TEST_CASE( testExtractTypes ) +BOOST_AUTO_TEST_CASE(testExtractTypes) { auto db = DB::MockDatabase::openConnectionTo("pqmock"); auto sel = db->select("SELECT 1 FROM forEachRow LIMIT 0"); @@ -462,4 +470,3 @@ BOOST_AUTO_TEST_CASE( testExtractTypes ) testExtractT(sel); testExtractT(sel); } - -- cgit v1.2.3