Compare commits

..

No commits in common. "e3bc481a5ec3e88bb0f9cedc00f61a03e3dd59d3" and "2f9d01f0c70823abd8efd3326757d112635a6e8c" have entirely different histories.

24 changed files with 727 additions and 748 deletions

View File

@ -6,9 +6,9 @@ add_executable(${PROJECT_NAME} test_main.cc)
# ##############################################################################
# If you include the drogon source code locally in your project, use this method
# to add drogon
# target_link_libraries(${PROJECT_NAME} PRIVATE drogon)
# target_link_libraries(${PROJECT_NAME}_test PRIVATE drogon)
#
# and comment out the following lines
target_link_libraries(${PROJECT_NAME} PRIVATE Drogon::Drogon)
ParseAndAddDrogonTests(${PROJECT_NAME})
ParseAndAddDrogonTests(${PROJECT_NAME})

View File

@ -57,26 +57,6 @@ class DROGON_EXPORT DrObjectBase
}
};
template <typename T>
struct isAutoCreationClass
{
template <class C>
static constexpr auto check(C *)
-> std::enable_if_t<std::is_same_v<decltype(C::isAutoCreation), bool>,
bool>
{
return C::isAutoCreation;
}
template <typename>
static constexpr bool check(...)
{
return false;
}
static constexpr bool value = check<T>(nullptr);
};
/**
* a class template to
* implement the reflection function of creating the class object by class name
@ -122,22 +102,23 @@ class DrObject : public virtual DrObjectBase
}
template <typename D>
void registerClass()
typename std::enable_if<std::is_default_constructible<D>::value,
void>::type
registerClass()
{
DrClassMap::registerClass(
className(),
[]() -> DrObjectBase * { return new T; },
[]() -> std::shared_ptr<DrObjectBase> {
return std::make_shared<T>();
});
}
template <typename D>
typename std::enable_if<!std::is_default_constructible<D>::value,
void>::type
registerClass()
{
if constexpr (std::is_default_constructible<D>::value)
{
DrClassMap::registerClass(
className(),
[]() -> DrObjectBase * { return new T; },
[]() -> std::shared_ptr<DrObjectBase> {
return std::make_shared<T>();
});
}
else if constexpr (isAutoCreationClass<D>::value)
{
static_assert(std::is_default_constructible<D>::value,
"Class is not default constructable!");
}
}
};

View File

@ -70,91 +70,6 @@ struct BinderArgTypeTraits<const T &>
static const bool isValid = true;
};
template <typename T>
T getHandlerArgumentValue(std::string &&p)
{
if constexpr (internal::CanConstructFromString<T>::value)
{
return T(std::move(p));
}
else if constexpr (internal::CanConvertFromStringStream<T>::value)
{
T value{T()};
if (!p.empty())
{
std::stringstream ss(std::move(p));
ss >> value;
}
return value;
}
else if constexpr (internal::CanConvertFromString<T>::value)
{
T value;
value = p;
return value;
}
else
{
LOG_ERROR << "Can't convert string to type " << typeid(T).name();
return T();
}
}
template <>
inline std::string getHandlerArgumentValue<std::string>(std::string &&p)
{
return std::move(p);
}
template <>
inline int getHandlerArgumentValue<int>(std::string &&p)
{
return std::stoi(p);
}
template <>
inline long getHandlerArgumentValue<long>(std::string &&p)
{
return std::stol(p);
}
template <>
inline long long getHandlerArgumentValue<long long>(std::string &&p)
{
return std::stoll(p);
}
template <>
inline unsigned long getHandlerArgumentValue<unsigned long>(std::string &&p)
{
return std::stoul(p);
}
template <>
inline unsigned long long getHandlerArgumentValue<unsigned long long>(
std::string &&p)
{
return std::stoull(p);
}
template <>
inline float getHandlerArgumentValue<float>(std::string &&p)
{
return std::stof(p);
}
template <>
inline double getHandlerArgumentValue<double>(std::string &&p)
{
return std::stod(p);
}
template <>
inline long double getHandlerArgumentValue<long double>(std::string &&p)
{
return std::stold(p);
}
class HttpBinderBase
{
public:
@ -238,22 +153,27 @@ class HttpBinder : public HttpBinderBase
template <bool isClassFunction = traits::isClassFunction,
bool isDrObjectClass = traits::isDrObjectClass>
void createHandlerInstance()
typename std::enable_if<isDrObjectClass && isClassFunction, void>::type
createHandlerInstance()
{
auto objPtr =
DrClassMap::getSingleInstance<typename traits::class_type>();
LOG_TRACE << "create handler class object: " << objPtr.get();
}
template <bool isClassFunction = traits::isClassFunction,
bool isDrObjectClass = traits::isDrObjectClass>
typename std::enable_if<!isDrObjectClass && isClassFunction, void>::type
createHandlerInstance()
{
auto &obj = getControllerObj<typename traits::class_type>();
LOG_TRACE << "create handler class object: " << &obj;
}
template <bool isClassFunction = traits::isClassFunction>
typename std::enable_if<!isClassFunction, void>::type
createHandlerInstance()
{
if constexpr (isClassFunction)
{
if constexpr (isDrObjectClass)
{
auto objPtr = DrClassMap::getSingleInstance<
typename traits::class_type>();
LOG_TRACE << "create handler class object: " << objPtr.get();
}
else
{
auto &obj = getControllerObj<typename traits::class_type>();
LOG_TRACE << "create handler class object: " << &obj;
}
}
}
private:
@ -264,201 +184,276 @@ class HttpBinder : public HttpBinderBase
static const size_t argument_count = traits::arity;
std::string handlerName_;
template <typename T>
typename std::enable_if<internal::CanConvertFromStringStream<T>::value,
void>::type
getHandlerArgumentValue(T &value, std::string &&p)
{
if (!p.empty())
{
std::stringstream ss(std::move(p));
ss >> value;
}
}
template <typename T>
typename std::enable_if<!(internal::CanConvertFromStringStream<T>::value),
void>::type
getHandlerArgumentValue(T &value, std::string &&p)
{
}
void getHandlerArgumentValue(std::string &value, std::string &&p)
{
value = std::move(p);
}
void getHandlerArgumentValue(int &value, std::string &&p)
{
value = std::stoi(p);
}
void getHandlerArgumentValue(long &value, std::string &&p)
{
value = std::stol(p);
}
void getHandlerArgumentValue(long long &value, std::string &&p)
{
value = std::stoll(p);
}
void getHandlerArgumentValue(unsigned long &value, std::string &&p)
{
value = std::stoul(p);
}
void getHandlerArgumentValue(unsigned long long &value, std::string &&p)
{
value = std::stoull(p);
}
void getHandlerArgumentValue(float &value, std::string &&p)
{
value = std::stof(p);
}
void getHandlerArgumentValue(double &value, std::string &&p)
{
value = std::stod(p);
}
void getHandlerArgumentValue(long double &value, std::string &&p)
{
value = std::stold(p);
}
template <typename... Values, std::size_t Boundary = argument_count>
typename std::enable_if<(sizeof...(Values) < Boundary), void>::type run(
std::deque<std::string> &pathArguments,
const HttpRequestPtr &req,
std::function<void(const HttpResponsePtr &)> &&callback,
Values &&...values)
{
// Call this function recursively until parameter's count equals to the
// count of target function parameters
static_assert(
BinderArgTypeTraits<nth_argument_type<sizeof...(Values)>>::isValid,
"your handler argument type must be value type or const left "
"reference type or right reference type");
using ValueType =
typename std::remove_cv<typename std::remove_reference<
nth_argument_type<sizeof...(Values)>>::type>::type;
ValueType value = ValueType();
if (!pathArguments.empty())
{
std::string v = std::move(pathArguments.front());
pathArguments.pop_front();
try
{
if (v.empty() == false)
getHandlerArgumentValue(value, std::move(v));
}
catch (const std::exception &e)
{
handleException(e, req, std::move(callback));
return;
}
}
else
{
try
{
value = req->as<ValueType>();
}
catch (const std::exception &e)
{
handleException(e, req, std::move(callback));
return;
}
catch (...)
{
LOG_ERROR << "Exception not derived from std::exception";
return;
}
}
run(pathArguments,
req,
std::move(callback),
std::forward<Values>(values)...,
std::move(value));
}
template <typename... Values,
std::size_t Boundary = argument_count,
bool isCoroutine = traits::isCoroutine>
void run(std::deque<std::string> &pathArguments,
const HttpRequestPtr &req,
std::function<void(const HttpResponsePtr &)> &&callback,
Values &&...values)
typename std::enable_if<(sizeof...(Values) == Boundary) && !isCoroutine,
void>::type
run(std::deque<std::string> &,
const HttpRequestPtr &req,
std::function<void(const HttpResponsePtr &)> &&callback,
Values &&...values)
{
if constexpr (sizeof...(Values) < Boundary)
{ // Call this function recursively until parameter's count equals to
// the count of target function parameters
static_assert(
BinderArgTypeTraits<
nth_argument_type<sizeof...(Values)>>::isValid,
"your handler argument type must be value type or const left "
"reference type or right reference type");
using ValueType = std::remove_cv_t<
std::remove_reference_t<nth_argument_type<sizeof...(Values)>>>;
if (!pathArguments.empty())
{
std::string v{std::move(pathArguments.front())};
pathArguments.pop_front();
try
{
if (!v.empty())
{
auto value =
getHandlerArgumentValue<ValueType>(std::move(v));
run(pathArguments,
req,
std::move(callback),
std::forward<Values>(values)...,
std::move(value));
return;
}
}
catch (const std::exception &e)
{
handleException(e, req, std::move(callback));
return;
}
}
else
{
try
{
auto value = req->as<ValueType>();
run(pathArguments,
req,
std::move(callback),
std::forward<Values>(values)...,
std::move(value));
return;
}
catch (const std::exception &e)
{
handleException(e, req, std::move(callback));
return;
}
catch (...)
{
LOG_ERROR << "Exception not derived from std::exception";
return;
}
}
run(pathArguments,
req,
std::move(callback),
std::forward<Values>(values)...,
ValueType());
}
else if constexpr (sizeof...(Values) == Boundary)
try
{
if constexpr (!isCoroutine)
// Explcit copy because `callFunction` moves it
auto cb = callback;
callFunction(req, cb, std::move(values)...);
}
catch (const std::exception &except)
{
handleException(except, req, std::move(callback));
}
catch (...)
{
LOG_ERROR << "Exception not derived from std::exception";
return;
}
}
#ifdef __cpp_impl_coroutine
template <typename... Values,
std::size_t Boundary = argument_count,
bool isCoroutine = traits::isCoroutine>
typename std::enable_if<(sizeof...(Values) == Boundary) && isCoroutine,
void>::type
run(std::deque<std::string> &,
const HttpRequestPtr &req,
std::function<void(const HttpResponsePtr &)> &&callback,
Values &&...values)
{
[this](HttpRequestPtr req,
std::function<void(const HttpResponsePtr &)> callback,
Values &&...values) -> AsyncTask {
try
{
try
if constexpr (std::is_same_v<AsyncTask,
typename traits::return_type>)
{
// Explcit copy because `callFunction` moves it
auto cb = callback;
callFunction(req, cb, std::move(values)...);
}
catch (const std::exception &except)
else if constexpr (std::is_same_v<Task<>,
typename traits::return_type>)
{
handleException(except, req, std::move(callback));
// Explcit copy because `callFunction` moves it
auto cb = callback;
co_await callFunction(req, cb, std::move(values)...);
}
catch (...)
else if constexpr (std::is_same_v<Task<HttpResponsePtr>,
typename traits::return_type>)
{
LOG_ERROR << "Exception not derived from std::exception";
return;
auto resp =
co_await callFunction(req, std::move(values)...);
callback(std::move(resp));
}
}
#ifdef __cpp_impl_coroutine
else
catch (const std::exception &except)
{
[this](HttpRequestPtr req,
std::function<void(const HttpResponsePtr &)> callback,
Values &&...values) -> AsyncTask {
try
{
if constexpr (std::is_same_v<
AsyncTask,
typename traits::return_type>)
{
// Explcit copy because `callFunction` moves it
auto cb = callback;
callFunction(req, cb, std::move(values)...);
}
else if constexpr (std::is_same_v<
Task<>,
typename traits::return_type>)
{
// Explcit copy because `callFunction` moves it
auto cb = callback;
co_await callFunction(req,
cb,
std::move(values)...);
}
else if constexpr (std::is_same_v<
Task<HttpResponsePtr>,
typename traits::return_type>)
{
auto resp =
co_await callFunction(req,
std::move(values)...);
callback(std::move(resp));
}
}
catch (const std::exception &except)
{
handleException(except, req, std::move(callback));
}
catch (...)
{
LOG_ERROR
<< "Exception not derived from std::exception";
}
}(req, std::move(callback), std::move(values)...);
handleException(except, req, std::move(callback));
}
catch (...)
{
LOG_ERROR << "Exception not derived from std::exception";
}
}(req, std::move(callback), std::move(values)...);
}
#endif
}
template <typename... Values,
bool isClassFunction = traits::isClassFunction,
bool isDrObjectClass = traits::isDrObjectClass,
bool isNormal = std::is_same<typename traits::first_param_type,
HttpRequestPtr>::value>
typename std::enable_if<isClassFunction && !isDrObjectClass && isNormal,
typename traits::return_type>::type
callFunction(const HttpRequestPtr &req, Values &&...values)
{
static auto &obj = getControllerObj<typename traits::class_type>();
return (obj.*func_)(req, std::move(values)...);
}
template <typename... Values,
bool isClassFunction = traits::isClassFunction,
bool isDrObjectClass = traits::isDrObjectClass,
bool isNormal = std::is_same_v<typename traits::first_param_type,
HttpRequestPtr>>
typename traits::return_type callFunction(const HttpRequestPtr &req,
Values &&...values)
bool isNormal = std::is_same<typename traits::first_param_type,
HttpRequestPtr>::value>
typename std::enable_if<isClassFunction && isDrObjectClass && isNormal,
typename traits::return_type>::type
callFunction(const HttpRequestPtr &req, Values &&...values)
{
if constexpr (isNormal)
{
if constexpr (isClassFunction)
{
if constexpr (!isDrObjectClass)
{
static auto &obj =
getControllerObj<typename traits::class_type>();
return (obj.*func_)(req, std::move(values)...);
}
else
{
static auto objPtr = DrClassMap::getSingleInstance<
typename traits::class_type>();
return (*objPtr.*func_)(req, std::move(values)...);
}
}
else
{
return func_(req, std::move(values)...);
}
}
else
{
if constexpr (isClassFunction)
{
if constexpr (!isDrObjectClass)
{
static auto &obj =
getControllerObj<typename traits::class_type>();
return (obj.*func_)((*req), std::move(values)...);
}
else
{
static auto objPtr = DrClassMap::getSingleInstance<
typename traits::class_type>();
return (*objPtr.*func_)((*req), std::move(values)...);
}
}
else
{
return func_((*req), std::move(values)...);
}
}
static auto objPtr =
DrClassMap::getSingleInstance<typename traits::class_type>();
return (*objPtr.*func_)(req, std::move(values)...);
}
template <typename... Values,
bool isClassFunction = traits::isClassFunction,
bool isNormal = std::is_same<typename traits::first_param_type,
HttpRequestPtr>::value>
typename std::enable_if<!isClassFunction && isNormal,
typename traits::return_type>::type
callFunction(const HttpRequestPtr &req, Values &&...values)
{
return func_(req, std::move(values)...);
}
template <typename... Values,
bool isClassFunction = traits::isClassFunction,
bool isDrObjectClass = traits::isDrObjectClass,
bool isNormal = std::is_same<typename traits::first_param_type,
HttpRequestPtr>::value>
typename std::enable_if<isClassFunction && !isDrObjectClass && !isNormal,
typename traits::return_type>::type
callFunction(const HttpRequestPtr &req, Values &&...values)
{
static auto &obj = getControllerObj<typename traits::class_type>();
return (obj.*func_)((*req), std::move(values)...);
}
template <typename... Values,
bool isClassFunction = traits::isClassFunction,
bool isDrObjectClass = traits::isDrObjectClass,
bool isNormal = std::is_same<typename traits::first_param_type,
HttpRequestPtr>::value>
typename std::enable_if<isClassFunction && isDrObjectClass && !isNormal,
typename traits::return_type>::type
callFunction(const HttpRequestPtr &req, Values &&...values)
{
static auto objPtr =
DrClassMap::getSingleInstance<typename traits::class_type>();
return (*objPtr.*func_)((*req), std::move(values)...);
}
template <typename... Values,
bool isClassFunction = traits::isClassFunction,
bool isNormal = std::is_same<typename traits::first_param_type,
HttpRequestPtr>::value>
typename std::enable_if<!isClassFunction && !isNormal,
typename traits::return_type>::type
callFunction(const HttpRequestPtr &req, Values &&...values)
{
return func_((*req), std::move(values)...);
}
};

View File

@ -59,7 +59,7 @@ template <typename T, bool AutoCreation = true>
class HttpController : public DrObject<T>, public HttpControllerBase
{
public:
static constexpr bool isAutoCreation = AutoCreation;
static const bool isAutoCreation = AutoCreation;
protected:
template <typename FUNCTION>

View File

@ -69,10 +69,11 @@ struct is_printable : std::false_type
};
template <typename _Tp>
struct is_printable<
_Tp,
std::enable_if_t<std::is_same_v<decltype(std::cout << std::declval<_Tp>()),
std::ostream &>>> : std::true_type
struct is_printable<_Tp,
typename std::enable_if<
std::is_same<decltype(std::cout << std::declval<_Tp>()),
std::ostream &>::value>::type>
: std::true_type
{
};
@ -166,10 +167,10 @@ inline std::string attemptPrint(T &&v)
// Poor man's if constexpr because SFINAE don't disambiguate between
// possible resolutions
return
typename std::conditional_t<std::is_convertible_v<T, std::string_view>,
internal::StringPrinter,
DefaultPrinter>()(v);
return typename std::conditional<
std::is_convertible<T, std::string_view>::value,
internal::StringPrinter,
DefaultPrinter>::type()(v);
}
// Specializations to reduce template construction
@ -280,7 +281,7 @@ struct Lhs
template <typename RhsType>
ComparsionResult operator&&(const RhsType &rhs)
{
static_assert(!std::is_same_v<RhsType, void>,
static_assert(!std::is_same<RhsType, void>::value,
" && is not supported in expression decomposition");
return {};
}
@ -288,7 +289,7 @@ struct Lhs
template <typename RhsType>
ComparsionResult operator||(const RhsType &rhs)
{
static_assert(!std::is_same_v<RhsType, void>,
static_assert(!std::is_same<RhsType, void>::value,
" || is not supported in expression decomposition");
return {};
}
@ -296,7 +297,7 @@ struct Lhs
template <typename RhsType>
ComparsionResult operator|(const RhsType &rhs)
{
static_assert(!std::is_same_v<RhsType, void>,
static_assert(!std::is_same<RhsType, void>::value,
" | is not supported in expression decomposition");
return {};
}
@ -304,7 +305,7 @@ struct Lhs
template <typename RhsType>
ComparsionResult operator&(const RhsType &rhs)
{
static_assert(!std::is_same_v<RhsType, void>,
static_assert(!std::is_same<RhsType, void>::value,
" & is not supported in expression decomposition");
return {};
}

View File

@ -106,7 +106,8 @@ class DROGON_EXPORT PluginBase : public virtual DrObjectBase,
template <typename T>
struct IsPlugin
{
using TYPE = std::remove_cv_t<typename std::remove_reference_t<T>>;
using TYPE =
typename std::remove_cv<typename std::remove_reference<T>::type>::type;
static int test(void *)
{

View File

@ -50,7 +50,7 @@ struct FunctionTraits;
template <typename Function>
struct FunctionTraits
: public FunctionTraits<
decltype(&std::remove_reference_t<Function>::operator())>
decltype(&std::remove_reference<Function>::type::operator())>
{
static const bool isClassFunction = false;
static const bool isDrObjectClass = false;
@ -190,7 +190,7 @@ struct FunctionTraits<ReturnType (*)(Arguments...)>
template <std::size_t Index>
using argument =
typename std::tuple_element_t<Index, std::tuple<Arguments...>>;
typename std::tuple_element<Index, std::tuple<Arguments...>>::type;
static const std::size_t arity = sizeof...(Arguments);
using class_type = void;

View File

@ -37,7 +37,8 @@ struct CanConvertToString
static no test(...);
public:
static constexpr bool value = std::is_same_v<decltype(test<Type>(0)), yes>;
static constexpr bool value =
std::is_same<decltype(test<Type>(0)), yes>::value;
};
} // namespace internal
@ -52,20 +53,21 @@ class OStringStream
}
template <typename T>
OStringStream &operator<<(T &&value)
std::enable_if_t<!internal::CanConvertToString<T>::value, OStringStream &>
operator<<(T &&value)
{
if constexpr (internal::CanConvertToString<T>::value)
{
buffer_.append(std::to_string(std::forward<T>(value)));
return *this;
}
else
{
std::stringstream ss;
ss << std::forward<T>(value);
buffer_.append(ss.str());
return *this;
}
std::stringstream ss;
ss << std::forward<T>(value);
buffer_.append(ss.str());
return *this;
}
template <typename T>
std::enable_if_t<internal::CanConvertToString<T>::value, OStringStream &>
operator<<(T &&value)
{
buffer_.append(std::to_string(std::forward<T>(value)));
return *this;
}
template <int N>

View File

@ -53,43 +53,9 @@ struct CanConvertFromStringStream
public:
static constexpr bool value =
std::is_same_v<decltype(test<T>(nullptr, std::stringstream())), yes>;
std::is_same<decltype(test<T>(nullptr, std::stringstream())),
yes>::value;
};
template <typename T>
struct CanConstructFromString
{
private:
using yes = std::true_type;
using no = std::false_type;
template <typename U>
static auto test(U *p) -> decltype(U(std::string{}), yes());
template <typename>
static no test(...);
public:
static constexpr bool value =
std::is_same_v<decltype(test<T>(nullptr)), yes>;
};
template <typename T>
struct CanConvertFromString
{
private:
using yes = std::true_type;
using no = std::false_type;
template <class U>
static auto test(U *p) -> decltype(*p = std::string(), yes());
template <class>
static no test(...);
public:
static constexpr bool value =
std::is_same_v<decltype(test<T>(nullptr)), yes>;
};
} // namespace internal
namespace utils
@ -113,8 +79,7 @@ DROGON_EXPORT std::string genRandomString(int length);
/// Convert a binary string to hex format
DROGON_EXPORT std::string binaryStringToHex(const unsigned char *ptr,
size_t length,
bool lowerCase = false);
size_t length);
/// Get a binary string from hexadecimal format
DROGON_EXPORT std::string hexToBinaryString(const char *ptr, size_t length);
@ -123,11 +88,6 @@ DROGON_EXPORT std::string hexToBinaryString(const char *ptr, size_t length);
DROGON_EXPORT std::vector<char> hexToBinaryVector(const char *ptr,
size_t length);
DROGON_EXPORT void binaryStringToHex(const char *ptr,
size_t length,
char *out,
bool lowerCase = false);
/// Split the string into multiple separated strings.
/**
* @param acceptEmptyString if true, empty strings are accepted in the
@ -146,7 +106,7 @@ DROGON_EXPORT std::set<std::string> splitStringToSet(
const std::string &separator);
/// Get UUID string.
DROGON_EXPORT std::string getUuid(bool lowercase = true);
DROGON_EXPORT std::string getUuid();
/// Get the encoded length of base64.
constexpr size_t base64EncodedLength(size_t in_len, bool padded = true)
@ -436,22 +396,24 @@ DROGON_EXPORT bool secureRandomBytes(void *ptr, size_t size);
DROGON_EXPORT std::string secureRandomString(size_t size);
template <typename T>
T fromString(const std::string &p) noexcept(false)
typename std::enable_if<internal::CanConvertFromStringStream<T>::value, T>::type
fromString(const std::string &p) noexcept(false)
{
if constexpr (internal::CanConvertFromStringStream<T>::value)
T value{};
if (!p.empty())
{
T value{};
if (!p.empty())
{
std::stringstream ss(p);
ss >> value;
}
return value;
}
else
{
throw std::runtime_error("Bad type conversion");
std::stringstream ss(p);
ss >> value;
}
return value;
}
template <typename T>
typename std::enable_if<!(internal::CanConvertFromStringStream<T>::value),
T>::type
fromString(const std::string &) noexcept(false)
{
throw std::runtime_error("Bad type conversion");
}
template <>

View File

@ -1375,6 +1375,7 @@ void Http2Transport::sendFrame(const internal::H2Frame &frame, int32_t streamId)
void Http2Transport::sendBufferedData()
{
LOG_WARN << "Sending buffered data. Size: " << batchedSendBuffer.size();
if (batchedSendBuffer.size() == 0)
return;
OByteStream buffer;

View File

@ -777,14 +777,14 @@ void HttpAppFrameworkImpl::findSessionForRequest(const HttpRequestImplPtr &req)
if (useSession_)
{
std::string sessionId = req->getCookie(sessionCookieKey_);
bool needSetSessionid = false;
bool needSetJsessionid = false;
if (sessionId.empty())
{
sessionId = sessionIdGeneratorCallback_();
needSetSessionid = true;
sessionId = utils::getUuid();
needSetJsessionid = true;
}
req->setSession(
sessionManagerPtr_->getSession(sessionId, needSetSessionid));
sessionManagerPtr_->getSession(sessionId, needSetJsessionid));
}
}

View File

@ -25,7 +25,6 @@
#include <string>
#include <vector>
#include "SessionManager.h"
#include "drogon/utils/Utilities.h"
#include "impl_forwards.h"
namespace trantor
@ -251,9 +250,7 @@ class HttpAppFrameworkImpl final : public HttpAppFramework
HttpAppFramework &setSessionIdGenerator(
SessionManager::IdGeneratorCallback idGeneratorCallback = nullptr)
{
sessionIdGeneratorCallback_ =
idGeneratorCallback ? idGeneratorCallback
: []() { return utils::getUuid(true); };
sessionIdGeneratorCallback_ = idGeneratorCallback;
return *this;
}

View File

@ -760,7 +760,7 @@ void HttpRequestImpl::appendToBody(const char *data, size_t length)
void HttpRequestImpl::createTmpFile()
{
auto tmpfile = HttpAppFrameworkImpl::instance().getUploadPath();
auto fileName = utils::getUuid(false);
auto fileName = utils::getUuid();
tmpfile.append("/tmp/")
.append(1, fileName[0])
.append(1, fileName[1])

View File

@ -13,6 +13,7 @@
*/
#include "SessionManager.h"
#include <drogon/utils/Utilities.h>
using namespace drogon;
@ -26,7 +27,8 @@ SessionManager::SessionManager(
timeout_(timeout),
sessionStartAdvices_(startAdvices),
sessionDestroyAdvices_(destroyAdvices),
idGeneratorCallback_(idGeneratorCallback)
idGeneratorCallback_(idGeneratorCallback ? idGeneratorCallback
: utils::getUuid)
{
if (timeout_ > 0)
{

View File

@ -37,7 +37,7 @@ class SessionManager : public trantor::NonCopyable
size_t timeout,
const std::vector<AdviceStartSessionCallback> &startAdvices,
const std::vector<AdviceDestroySessionCallback> &destroyAdvices,
IdGeneratorCallback idGeneratorCallback);
IdGeneratorCallback idGeneratorCallback = nullptr);
~SessionManager()
{

View File

@ -289,55 +289,31 @@ std::string hexToBinaryString(const char *ptr, size_t length)
return ret;
}
DROGON_EXPORT void binaryStringToHex(const char *ptr,
size_t length,
char *out,
bool lowerCase)
std::string binaryStringToHex(const unsigned char *ptr, size_t length)
{
std::string idString;
for (size_t i = 0; i < length; ++i)
{
int value = (ptr[i] & 0xf0) >> 4;
if (value < 10)
{
out[i * 2] = char(value + 48);
idString.append(1, char(value + 48));
}
else
{
if (!lowerCase)
{
out[i * 2] = char(value + 55);
}
else
{
out[i * 2] = char(value + 87);
}
idString.append(1, char(value + 55));
}
value = (ptr[i] & 0x0f);
if (value < 10)
{
out[i * 2 + 1] = char(value + 48);
idString.append(1, char(value + 48));
}
else
{
if (!lowerCase)
{
out[i * 2 + 1] = char(value + 55);
}
else
{
out[i * 2 + 1] = char(value + 87);
}
idString.append(1, char(value + 55));
}
}
}
std::string binaryStringToHex(const unsigned char *ptr,
size_t length,
bool lowercase)
{
std::string idString(length * 2, '\0');
binaryStringToHex((const char *)ptr, length, &idString[0], lowercase);
return idString;
}
@ -366,23 +342,7 @@ std::set<std::string> splitStringToSet(const std::string &str,
return ret;
}
inline std::string createUuidString(const char *str, size_t len, bool lowercase)
{
assert(len == 16);
std::string uuid(36, '\0');
binaryStringToHex(str, 4, &uuid[0], lowercase);
uuid[8] = '-';
binaryStringToHex(str + 4, 2, &uuid[9], lowercase);
uuid[13] = '-';
binaryStringToHex(str + 6, 2, &uuid[14], lowercase);
uuid[18] = '-';
binaryStringToHex(str + 8, 2, &uuid[19], lowercase);
uuid[23] = '-';
binaryStringToHex(str + 10, 6, &uuid[24], lowercase);
return uuid;
}
std::string getUuid(bool lowercase)
std::string getUuid()
{
#if USE_OSSP_UUID
uuid_t *uuid;
@ -392,7 +352,7 @@ std::string getUuid(bool lowercase)
size_t len{0};
uuid_export(uuid, UUID_FMT_BIN, &str, &len);
uuid_destroy(uuid);
auto ret = createUuidString(str, len, lowercase);
std::string ret{binaryStringToHex((const unsigned char *)str, len)};
free(str);
return ret;
#elif defined __FreeBSD__ || defined __OpenBSD__
@ -410,7 +370,7 @@ std::string getUuid(bool lowercase)
uuid_enc_be(binstr, uuid);
#endif /* _BYTE_ORDER == _LITTLE_ENDIAN */
delete uuid;
auto ret = createUuidString(binstr, 16, lowercase);
std::string ret{binaryStringToHex((const unsigned char *)binstr, 16)};
free(binstr);
return ret;
#elif defined _WIN32
@ -419,7 +379,7 @@ std::string getUuid(bool lowercase)
char tempStr[100];
auto len = snprintf(tempStr,
sizeof(tempStr),
"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
"%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
uu.Data1,
uu.Data2,
uu.Data3,
@ -435,8 +395,7 @@ std::string getUuid(bool lowercase)
#else
uuid_t uu;
uuid_generate(uu);
auto uuid = createUuidString((const char *)uu, 16, lowercase);
return uuid;
return binaryStringToHex(uu, 16);
#endif
}

View File

@ -25,9 +25,7 @@ set(UNITTEST_SOURCES
unittests/StringOpsTest.cc
unittests/ControllerCreationTest.cc
unittests/MultiPartParserTest.cc
unittests/SlashRemoverTest.cc
unittests/UuidUnittest.cc
)
unittests/SlashRemoverTest.cc)
if(DROGON_CXX_STANDARD GREATER_EQUAL 20 AND HAS_COROUTINE)
set(UNITTEST_SOURCES ${UNITTEST_SOURCES} unittests/CoroutineTest.cc)

View File

@ -1,17 +0,0 @@
#include <string_view>
#include <drogon/utils/Utilities.h>
#include <iostream>
#include <drogon/drogon_test.h>
DROGON_TEST(UuidTest)
{
auto uuid = drogon::utils::getUuid();
std::cout << "uuid: " << uuid << std::endl;
CHECK(uuid[8] == '-');
CHECK(uuid[13] == '-');
CHECK(uuid[18] == '-');
CHECK(uuid[23] == '-');
CHECK(uuid.size() == 36);
}

View File

@ -167,6 +167,7 @@ class BaseBuilder
}
public:
#ifdef __cpp_if_constexpr
static ResultType convert_result(const Result &r)
{
if constexpr (SelectAll)
@ -197,6 +198,48 @@ class BaseBuilder
}
}
}
#else
template <bool SA = SelectAll,
bool SI = Single,
std::enable_if_t<SA, std::nullptr_t> = nullptr,
std::enable_if_t<SI, std::nullptr_t> = nullptr>
static inline T convert_result(const Result &r)
{
return T(r[0]);
}
template <bool SA = SelectAll,
bool SI = Single,
std::enable_if_t<SA, std::nullptr_t> = nullptr,
std::enable_if_t<!SI, std::nullptr_t> = nullptr>
static inline std::vector<T> convert_result(const Result &r)
{
std::vector<T> ret;
for (const Row &row : r)
{
ret.template emplace_back(T(row));
}
return ret;
}
template <bool SA = SelectAll,
bool SI = Single,
std::enable_if_t<!SA, std::nullptr_t> = nullptr,
std::enable_if_t<SI, std::nullptr_t> = nullptr>
static inline Row convert_result(const Result &r)
{
return r[0];
}
template <bool SA = SelectAll,
bool SI = Single,
std::enable_if_t<!SA, std::nullptr_t> = nullptr,
std::enable_if_t<!SI, std::nullptr_t> = nullptr>
static inline Result convert_result(const Result &r)
{
return r;
}
#endif
inline ResultType execSync(const DbClientPtr &client)
{

View File

@ -80,12 +80,13 @@ class CoroMapper : public Mapper<T>
inline internal::MapperAwaiter<T> findByPrimaryKey(const TraitsPKType &key)
{
if constexpr (!std::is_same_v<typename T::PrimaryKeyType, void>)
if constexpr (!std::is_same<typename T::PrimaryKeyType, void>::value)
{
auto lb = [this, key](SingleRowCallback &&callback,
ExceptPtrCallback &&errCallback) mutable {
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!");
static_assert(
!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value,
"No function member named sqlForFindingByPrimaryKey, "
@ -416,8 +417,9 @@ class CoroMapper : public Mapper<T>
auto lb = [this, obj](CountCallback &&callback,
ExceptPtrCallback &&errCallback) {
this->clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!");
static_assert(
!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "update ";
sql += T::tableName;
sql += " set ";
@ -528,8 +530,9 @@ class CoroMapper : public Mapper<T>
auto lb = [this, obj](CountCallback &&callback,
ExceptPtrCallback &&errCallback) {
this->clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!");
static_assert(
!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "delete from ";
sql += T::tableName;
sql += " ";
@ -552,8 +555,9 @@ class CoroMapper : public Mapper<T>
auto lb = [this, criteria](CountCallback &&callback,
ExceptPtrCallback &&errCallback) {
this->clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!");
static_assert(
!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "delete from ";
sql += T::tableName;
@ -580,7 +584,7 @@ class CoroMapper : public Mapper<T>
inline internal::MapperAwaiter<size_t> deleteByPrimaryKey(
const TraitsPKType &key)
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
static_assert(
internal::has_sqlForDeletingByPrimaryKey<T>::value,

View File

@ -110,10 +110,9 @@ struct FunctionTraits<ReturnType (*)(Arguments...)>
static const std::size_t arity = sizeof...(Arguments);
// static const bool isSqlCallback = false;
static const bool isSqlCallback = true;
static const bool isStepResultCallback = true;
static const bool isExceptCallback = false;
static const bool isPtr = false;
};
} // namespace internal
} // namespace orm

View File

@ -62,7 +62,8 @@ struct has_sqlForFindingByPrimaryKey
static no test(...);
public:
static constexpr bool value = std::is_same_v<decltype(test<T>(0)), yes>;
static constexpr bool value =
std::is_same<decltype(test<T>(0)), yes>::value;
};
template <typename T>
@ -80,7 +81,8 @@ struct has_sqlForDeletingByPrimaryKey
static no test(...);
public:
static constexpr bool value = std::is_same_v<decltype(test<T>(0)), yes>;
static constexpr bool value =
std::is_same<decltype(test<T>(0)), yes>::value;
};
} // namespace internal
@ -183,7 +185,7 @@ class Mapper
using CountCallback = std::function<void(const size_t)>;
using TraitsPKType = typename internal::
Traits<T, !std::is_same_v<typename T::PrimaryKeyType, void>>::type;
Traits<T, !std::is_same<typename T::PrimaryKeyType, void>::value>::type;
/**
* @brief Find a record by the primary key.
@ -194,48 +196,53 @@ class Mapper
*/
template <typename U = T>
inline T findByPrimaryKey(const TraitsPKType &key) noexcept(false)
inline typename std::enable_if<
!std::is_same<typename U::PrimaryKeyType, void>::value,
T>::type
findByPrimaryKey(const TraitsPKType &key) noexcept(false)
{
if constexpr (!std::is_same_v<typename U::PrimaryKeyType, void>)
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value,
"No function member named sqlForFindingByPrimaryKey, please "
"make sure that the model class is generated by the latest "
"version of drogon_ctl");
// return findOne(Criteria(T::primaryKeyName, key));
std::string sql = T::sqlForFindingByPrimaryKey();
if (forUpdate_)
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!");
static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value,
"No function member named sqlForFindingByPrimaryKey, please "
"make sure that the model class is generated by the latest "
"version of drogon_ctl");
// return findOne(Criteria(T::primaryKeyName, key));
std::string sql = T::sqlForFindingByPrimaryKey();
if (forUpdate_)
{
sql += " for update";
}
clear();
Result r(nullptr);
{
auto binder = *client_ << std::move(sql);
outputPrimeryKeyToBinder(key, binder);
binder << Mode::Blocking;
binder >> [&r](const Result &result) { r = result; };
binder.exec(); // exec may be throw exception;
}
if (r.size() == 0)
{
throw UnexpectedRows("0 rows found");
}
else if (r.size() > 1)
{
throw UnexpectedRows("Found more than one row");
}
auto row = r[0];
return T(row);
sql += " for update";
}
else
clear();
Result r(nullptr);
{
LOG_FATAL << "The table must have a primary key";
abort();
auto binder = *client_ << std::move(sql);
outputPrimeryKeyToBinder(key, binder);
binder << Mode::Blocking;
binder >> [&r](const Result &result) { r = result; };
binder.exec(); // exec may be throw exception;
}
if (r.size() == 0)
{
throw UnexpectedRows("0 rows found");
}
else if (r.size() > 1)
{
throw UnexpectedRows("Found more than one row");
}
auto row = r[0];
return T(row);
}
template <typename U = T>
inline typename std::enable_if<
std::is_same<typename U::PrimaryKeyType, void>::value,
T>::type
findByPrimaryKey(const TraitsPKType &key) noexcept(false)
{
LOG_FATAL << "The table must have a primary key";
abort();
}
/**
@ -246,49 +253,56 @@ class Mapper
* @param ecb Is called when an error occurs or a record cannot be found.
*/
template <typename U = T>
inline void findByPrimaryKey(const TraitsPKType &key,
const SingleRowCallback &rcb,
const ExceptionCallback &ecb) noexcept
inline typename std::enable_if<
!std::is_same<typename U::PrimaryKeyType, void>::value,
void>::type
findByPrimaryKey(const TraitsPKType &key,
const SingleRowCallback &rcb,
const ExceptionCallback &ecb) noexcept
{
if constexpr (!std::is_same_v<typename U::PrimaryKeyType, void>)
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value,
"No function member named sqlForFindingByPrimaryKey, please "
"make sure that the model class is generated by the latest "
"version of drogon_ctl");
// findOne(Criteria(T::primaryKeyName, key), rcb, ecb);
std::string sql = T::sqlForFindingByPrimaryKey();
if (forUpdate_)
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!");
static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value,
"No function member named sqlForFindingByPrimaryKey, please "
"make sure that the model class is generated by the latest "
"version of drogon_ctl");
// findOne(Criteria(T::primaryKeyName, key), rcb, ecb);
std::string sql = T::sqlForFindingByPrimaryKey();
if (forUpdate_)
sql += " for update";
}
clear();
auto binder = *client_ << std::move(sql);
outputPrimeryKeyToBinder(key, binder);
binder >> [ecb, rcb](const Result &r) {
if (r.size() == 0)
{
sql += " for update";
ecb(UnexpectedRows("0 rows found"));
}
clear();
auto binder = *client_ << std::move(sql);
outputPrimeryKeyToBinder(key, binder);
binder >> [ecb, rcb](const Result &r) {
if (r.size() == 0)
{
ecb(UnexpectedRows("0 rows found"));
}
else if (r.size() > 1)
{
ecb(UnexpectedRows("Found more than one row"));
}
else
{
rcb(T(r[0]));
}
};
binder >> ecb;
}
else
{
LOG_FATAL << "The table must have a primary key";
abort();
}
else if (r.size() > 1)
{
ecb(UnexpectedRows("Found more than one row"));
}
else
{
rcb(T(r[0]));
}
};
binder >> ecb;
}
template <typename U = T>
inline typename std::enable_if<
std::is_same<typename U::PrimaryKeyType, void>::value,
void>::type
findByPrimaryKey(const TraitsPKType &key,
const SingleRowCallback &rcb,
const ExceptionCallback &ecb) noexcept
{
LOG_FATAL << "The table must have a primary key";
abort();
}
/**
@ -301,56 +315,60 @@ class Mapper
* user calls the get() method of the future object.
*/
template <typename U = T>
inline std::future<T> findFutureByPrimaryKey(
const TraitsPKType &key) noexcept
inline typename std::enable_if<
!std::is_same<typename U::PrimaryKeyType, void>::value,
std::future<T>>::type
findFutureByPrimaryKey(const TraitsPKType &key) noexcept
{
if constexpr (!std::is_same_v<typename U::PrimaryKeyType, void>)
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value,
"No function member named sqlForFindingByPrimaryKey, please "
"make sure that the model class is generated by the latest "
"version of drogon_ctl");
// return findFutureOne(Criteria(T::primaryKeyName, key));
std::string sql = T::sqlForFindingByPrimaryKey();
if (forUpdate_)
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!");
static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value,
"No function member named sqlForFindingByPrimaryKey, please "
"make sure that the model class is generated by the latest "
"version of drogon_ctl");
// return findFutureOne(Criteria(T::primaryKeyName, key));
std::string sql = T::sqlForFindingByPrimaryKey();
if (forUpdate_)
{
sql += " for update";
}
clear();
auto binder = *client_ << std::move(sql);
outputPrimeryKeyToBinder(key, binder);
sql += " for update";
}
clear();
auto binder = *client_ << std::move(sql);
outputPrimeryKeyToBinder(key, binder);
std::shared_ptr<std::promise<T>> prom =
std::make_shared<std::promise<T>>();
binder >> [prom](const Result &r) {
if (r.size() == 0)
{
prom->set_exception(std::make_exception_ptr(
UnexpectedRows("0 rows found")));
}
else if (r.size() > 1)
{
prom->set_exception(std::make_exception_ptr(
UnexpectedRows("Found more than one row")));
}
else
{
prom->set_value(T(r[0]));
}
};
binder >>
[prom](const std::exception_ptr &e) { prom->set_exception(e); };
binder.exec();
return prom->get_future();
}
else
{
LOG_FATAL << "The table must have a primary key";
abort();
}
std::shared_ptr<std::promise<T>> prom =
std::make_shared<std::promise<T>>();
binder >> [prom](const Result &r) {
if (r.size() == 0)
{
prom->set_exception(
std::make_exception_ptr(UnexpectedRows("0 rows found")));
}
else if (r.size() > 1)
{
prom->set_exception(std::make_exception_ptr(
UnexpectedRows("Found more than one row")));
}
else
{
prom->set_value(T(r[0]));
}
};
binder >>
[prom](const std::exception_ptr &e) { prom->set_exception(e); };
binder.exec();
return prom->get_future();
}
template <typename U = T>
inline typename std::enable_if<
std::is_same<typename U::PrimaryKeyType, void>::value,
std::future<U>>::type
findFutureByPrimaryKey(const TraitsPKType &key) noexcept
{
LOG_FATAL << "The table must have a primary key";
abort();
}
/**
@ -683,57 +701,67 @@ class Mapper
}
template <typename PKType = decltype(T::primaryKeyName)>
void makePrimaryKeyCriteria(std::string &sql)
typename std::enable_if<std::is_same<const std::string, PKType>::value,
void>::type
makePrimaryKeyCriteria(std::string &sql)
{
if constexpr (std::is_same_v<const std::string, PKType>)
sql += " where ";
sql += T::primaryKeyName;
sql += " = $?";
}
template <typename PKType = decltype(T::primaryKeyName)>
typename std::enable_if<
std::is_same<const std::vector<std::string>, PKType>::value,
void>::type
makePrimaryKeyCriteria(std::string &sql)
{
sql += " where ";
for (size_t i = 0; i < T::primaryKeyName.size(); ++i)
{
sql += " where ";
sql += T::primaryKeyName;
sql += T::primaryKeyName[i];
sql += " = $?";
}
else if constexpr (std::is_same_v<const std::vector<std::string>,
PKType>)
{
sql += " where ";
for (size_t i = 0; i < T::primaryKeyName.size(); ++i)
if (i < (T::primaryKeyName.size() - 1))
{
sql += T::primaryKeyName[i];
sql += " = $?";
if (i < (T::primaryKeyName.size() - 1))
{
sql += " and ";
}
sql += " and ";
}
}
}
template <typename PKType = decltype(T::primaryKeyName)>
void outputPrimeryKeyToBinder(const TraitsPKType &pk,
internal::SqlBinder &binder)
typename std::enable_if<std::is_same<const std::string, PKType>::value,
void>::type
outputPrimeryKeyToBinder(const TraitsPKType &pk,
internal::SqlBinder &binder)
{
if constexpr (std::is_same_v<const std::string, PKType>)
{
binder << pk;
}
else if constexpr (std::is_same_v<const std::vector<std::string>,
PKType>)
{
tupleToBinder<typename T::PrimaryKeyType>(pk, binder);
}
binder << pk;
}
template <typename PKType = decltype(T::primaryKeyName)>
typename std::enable_if<
std::is_same<const std::vector<std::string>, PKType>::value,
void>::type
outputPrimeryKeyToBinder(const TraitsPKType &pk,
internal::SqlBinder &binder)
{
tupleToBinder<typename T::PrimaryKeyType>(pk, binder);
}
template <typename TP, ssize_t N = std::tuple_size<TP>::value>
void tupleToBinder(const TP &t, internal::SqlBinder &binder)
typename std::enable_if<(N > 1), void>::type tupleToBinder(
const TP &t,
internal::SqlBinder &binder)
{
if constexpr (N > 1)
{
tupleToBinder<TP, N - 1>(t, binder);
binder << std::get<N - 1>(t);
}
else if constexpr (N == 1)
{
binder << std::get<0>(t);
}
tupleToBinder<TP, N - 1>(t, binder);
binder << std::get<N - 1>(t);
}
template <typename TP, ssize_t N = std::tuple_size<TP>::value>
typename std::enable_if<(N == 1), void>::type tupleToBinder(
const TP &t,
internal::SqlBinder &binder)
{
binder << std::get<0>(t);
}
std::string replaceSqlPlaceHolder(const std::string &sqlStr,
@ -1293,7 +1321,7 @@ template <typename T>
inline size_t Mapper<T>::update(const T &obj) noexcept(false)
{
clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "update ";
sql += T::tableName;
@ -1366,7 +1394,7 @@ inline void Mapper<T>::update(const T &obj,
const ExceptionCallback &ecb) noexcept
{
clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "update ";
sql += T::tableName;
@ -1429,7 +1457,7 @@ template <typename T>
inline std::future<size_t> Mapper<T>::updateFuture(const T &obj) noexcept
{
clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "update ";
sql += T::tableName;
@ -1501,7 +1529,7 @@ template <typename T>
inline size_t Mapper<T>::deleteOne(const T &obj) noexcept(false)
{
clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "delete from ";
sql += T::tableName;
@ -1528,7 +1556,7 @@ inline void Mapper<T>::deleteOne(const T &obj,
const ExceptionCallback &ecb) noexcept
{
clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "delete from ";
sql += T::tableName;
@ -1547,7 +1575,7 @@ template <typename T>
inline std::future<size_t> Mapper<T>::deleteFutureOne(const T &obj) noexcept
{
clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "delete from ";
sql += T::tableName;
@ -1571,7 +1599,7 @@ template <typename T>
inline size_t Mapper<T>::deleteBy(const Criteria &criteria) noexcept(false)
{
clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "delete from ";
sql += T::tableName;
@ -1603,7 +1631,7 @@ inline void Mapper<T>::deleteBy(const Criteria &criteria,
const ExceptionCallback &ecb) noexcept
{
clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "delete from ";
sql += T::tableName;
@ -1629,7 +1657,7 @@ inline std::future<size_t> Mapper<T>::deleteFutureBy(
const Criteria &criteria) noexcept
{
clear();
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
std::string sql = "delete from ";
sql += T::tableName;
@ -1769,7 +1797,7 @@ template <typename T>
inline size_t Mapper<T>::deleteByPrimaryKey(
const typename Mapper<T>::TraitsPKType &key) noexcept(false)
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
static_assert(internal::has_sqlForDeletingByPrimaryKey<T>::value,
"No function member named sqlForDeletingByPrimaryKey, please "
@ -1793,7 +1821,7 @@ inline void Mapper<T>::deleteByPrimaryKey(
const CountCallback &rcb,
const ExceptionCallback &ecb) noexcept
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
static_assert(internal::has_sqlForDeletingByPrimaryKey<T>::value,
"No function member named sqlForDeletingByPrimaryKey, please "
@ -1811,7 +1839,7 @@ template <typename T>
inline std::future<size_t> Mapper<T>::deleteFutureByPrimaryKey(
const typename Mapper<T>::TraitsPKType &key) noexcept
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
"No primary key in the table!");
static_assert(internal::has_sqlForDeletingByPrimaryKey<T>::value,
"No function member named sqlForDeletingByPrimaryKey, please "

View File

@ -203,78 +203,83 @@ class CallbackHolder : public CallbackHolderBase
static const size_t argumentCount = traits::arity;
template <bool isStep = traits::isStepResultCallback>
void run(const Result &result)
typename std::enable_if<isStep, void>::type run(const Result &result)
{
if constexpr (isStep)
if (result.empty())
{
if (result.empty())
{
run(nullptr, true);
return;
}
for (auto const &row : result)
{
run(&row, false);
}
run(nullptr, true);
return;
}
else
for (auto const &row : result)
{
static_assert(argumentCount == 0,
"Your sql callback function type is wrong!");
function_(result);
run(&row, false);
}
run(nullptr, true);
}
template <bool isStep = traits::isStepResultCallback>
typename std::enable_if<!isStep, void>::type run(const Result &result)
{
static_assert(argumentCount == 0,
"Your sql callback function type is wrong!");
function_(result);
}
template <typename... Values, std::size_t Boundary = argumentCount>
void run(const Row *const row, bool isNull, Values &&...values)
typename std::enable_if<(sizeof...(Values) < Boundary), void>::type run(
const Row *const row,
bool isNull,
Values &&...values)
{
if constexpr (sizeof...(Values) < Boundary)
// call this function recursively until parameter's count equals to the
// count of target function parameters
static_assert(
CallbackArgTypeTraits<NthArgumentType<sizeof...(Values)>>::isValid,
"your sql callback function argument type must be value "
"type or "
"const "
"left-reference type");
using ValueType =
typename std::remove_cv<typename std::remove_reference<
NthArgumentType<sizeof...(Values)>>::type>::type;
ValueType value = ValueType();
if (row && row->size() > sizeof...(Values))
{
// call this function recursively until parameter's count equals to
// the count of target function parameters
static_assert(
CallbackArgTypeTraits<
NthArgumentType<sizeof...(Values)>>::isValid,
"your sql callback function argument type must be value "
"type or "
"const "
"left-reference type");
using ValueType =
typename std::remove_cv<typename std::remove_reference<
NthArgumentType<sizeof...(Values)>>::type>::type;
ValueType value = ValueType();
if (row && row->size() > sizeof...(Values))
{
// if(!VectorTypeTraits<ValueType>::isVector)
// value = (*row)[sizeof...(Values)].as<ValueType>();
// else
// ; // value =
// (*row)[sizeof...(Values)].asArray<VectorTypeTraits<ValueType>::ItemsType>();
value = makeValue<ValueType>(
(*row)[(Row::SizeType)sizeof...(Values)]);
}
// if(!VectorTypeTraits<ValueType>::isVector)
// value = (*row)[sizeof...(Values)].as<ValueType>();
// else
// ; // value =
// (*row)[sizeof...(Values)].asArray<VectorTypeTraits<ValueType>::ItemsType>();
value =
makeValue<ValueType>((*row)[(Row::SizeType)sizeof...(Values)]);
}
run(row, isNull, std::forward<Values>(values)..., std::move(value));
}
else if constexpr (sizeof...(Values) == Boundary)
{
function_(isNull, std::move(values)...);
}
run(row, isNull, std::forward<Values>(values)..., std::move(value));
}
template <typename... Values, std::size_t Boundary = argumentCount>
typename std::enable_if<(sizeof...(Values) == Boundary), void>::type run(
const Row *const,
bool isNull,
Values &&...values)
{
function_(isNull, std::move(values)...);
}
template <typename ValueType>
ValueType makeValue(const Field &field)
typename std::enable_if<VectorTypeTraits<ValueType>::isVector,
ValueType>::type
makeValue(const Field &field)
{
if constexpr (VectorTypeTraits<ValueType>::isVector)
{
return field
.asArray<typename VectorTypeTraits<ValueType>::ItemsType>();
}
else
{
return field.as<ValueType>();
}
return field.asArray<typename VectorTypeTraits<ValueType>::ItemsType>();
}
template <typename ValueType>
typename std::enable_if<!VectorTypeTraits<ValueType>::isVector,
ValueType>::type
makeValue(const Field &field)
{
return field.as<ValueType>();
}
};
@ -341,38 +346,51 @@ class DROGON_EXPORT SqlBinder : public trantor::NonCopyable
template <typename CallbackType,
typename traits =
FunctionTraits<typename std::decay<CallbackType>::type>>
self &operator>>(CallbackType &&callback)
typename std::enable_if<traits::isExceptCallback && traits::isPtr,
self>::type &
operator>>(CallbackType &&callback)
{
if constexpr (traits::isExceptCallback)
{
if constexpr (traits::isPtr)
{
// LOG_DEBUG << "ptr callback";
isExceptionPtr_ = true;
exceptionPtrCallback_ = std::forward<CallbackType>(callback);
return *this;
}
else
{
isExceptionPtr_ = false;
exceptionCallback_ = std::forward<CallbackType>(callback);
return *this;
}
}
else if constexpr (traits::isSqlCallback)
{
callbackHolder_ = std::shared_ptr<CallbackHolderBase>(
new CallbackHolder<typename std::decay<CallbackType>::type>(
std::forward<CallbackType>(callback)));
return *this;
}
// LOG_DEBUG << "ptr callback";
isExceptionPtr_ = true;
exceptionPtrCallback_ = std::forward<CallbackType>(callback);
return *this;
}
template <typename CallbackType,
typename traits =
FunctionTraits<typename std::decay<CallbackType>::type>>
typename std::enable_if<traits::isExceptCallback && !traits::isPtr,
self>::type &
operator>>(CallbackType &&callback)
{
isExceptionPtr_ = false;
exceptionCallback_ = std::forward<CallbackType>(callback);
return *this;
}
template <typename CallbackType,
typename traits =
FunctionTraits<typename std::decay<CallbackType>::type>>
typename std::enable_if<traits::isSqlCallback, self>::type &operator>>(
CallbackType &&callback)
{
callbackHolder_ = std::shared_ptr<CallbackHolderBase>(
new CallbackHolder<typename std::decay<CallbackType>::type>(
std::forward<CallbackType>(callback)));
return *this;
}
template <typename T>
self &operator<<(T &&parameter)
typename std::enable_if<
!std::is_same<typename std::remove_cv<
typename std::remove_reference<T>::type>::type,
trantor::Date>::value,
self &>::type
operator<<(T &&parameter)
{
using ParaType = std::remove_cv_t<std::remove_reference_t<T>>;
++parametersNumber_;
using ParaType = typename std::remove_cv<
typename std::remove_reference<T>::type>::type;
std::shared_ptr<void> obj = std::make_shared<ParaType>(parameter);
if (type_ == ClientType::PostgreSQL)
{
@ -464,7 +482,12 @@ class DROGON_EXPORT SqlBinder : public trantor::NonCopyable
self &operator<<(std::string &&str);
self &operator<<(trantor::Date date)
self &operator<<(trantor::Date &&date)
{
return operator<<(date.toDbStringLocal());
}
self &operator<<(const trantor::Date &date)
{
return operator<<(date.toDbStringLocal());
}

@ -1 +1 @@
Subproject commit d596221dd13a27ae86a637dba82154d0c5f96331
Subproject commit 624fc083076d7da88b1fb1dca1669ff48168a3ce