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

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 * a class template to
* implement the reflection function of creating the class object by class name * implement the reflection function of creating the class object by class name
@ -122,9 +102,9 @@ class DrObject : public virtual DrObjectBase
} }
template <typename D> template <typename D>
void registerClass() typename std::enable_if<std::is_default_constructible<D>::value,
{ void>::type
if constexpr (std::is_default_constructible<D>::value) registerClass()
{ {
DrClassMap::registerClass( DrClassMap::registerClass(
className(), className(),
@ -133,11 +113,12 @@ class DrObject : public virtual DrObjectBase
return std::make_shared<T>(); return std::make_shared<T>();
}); });
} }
else if constexpr (isAutoCreationClass<D>::value)
template <typename D>
typename std::enable_if<!std::is_default_constructible<D>::value,
void>::type
registerClass()
{ {
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; 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 class HttpBinderBase
{ {
public: public:
@ -238,22 +153,27 @@ class HttpBinder : public HttpBinderBase
template <bool isClassFunction = traits::isClassFunction, template <bool isClassFunction = traits::isClassFunction,
bool isDrObjectClass = traits::isDrObjectClass> bool isDrObjectClass = traits::isDrObjectClass>
void createHandlerInstance() typename std::enable_if<isDrObjectClass && isClassFunction, void>::type
createHandlerInstance()
{ {
if constexpr (isClassFunction) auto objPtr =
{ DrClassMap::getSingleInstance<typename traits::class_type>();
if constexpr (isDrObjectClass)
{
auto objPtr = DrClassMap::getSingleInstance<
typename traits::class_type>();
LOG_TRACE << "create handler class object: " << objPtr.get(); LOG_TRACE << "create handler class object: " << objPtr.get();
} }
else
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>(); auto &obj = getControllerObj<typename traits::class_type>();
LOG_TRACE << "create handler class object: " << &obj; LOG_TRACE << "create handler class object: " << &obj;
} }
}
template <bool isClassFunction = traits::isClassFunction>
typename std::enable_if<!isClassFunction, void>::type
createHandlerInstance()
{
} }
private: private:
@ -264,41 +184,95 @@ class HttpBinder : public HttpBinderBase
static const size_t argument_count = traits::arity; static const size_t argument_count = traits::arity;
std::string handlerName_; std::string handlerName_;
template <typename... Values, template <typename T>
std::size_t Boundary = argument_count, typename std::enable_if<internal::CanConvertFromStringStream<T>::value,
bool isCoroutine = traits::isCoroutine> void>::type
void run(std::deque<std::string> &pathArguments, 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, const HttpRequestPtr &req,
std::function<void(const HttpResponsePtr &)> &&callback, std::function<void(const HttpResponsePtr &)> &&callback,
Values &&...values) Values &&...values)
{ {
if constexpr (sizeof...(Values) < Boundary) // Call this function recursively until parameter's count equals to the
{ // Call this function recursively until parameter's count equals to // count of target function parameters
// the count of target function parameters
static_assert( static_assert(
BinderArgTypeTraits< BinderArgTypeTraits<nth_argument_type<sizeof...(Values)>>::isValid,
nth_argument_type<sizeof...(Values)>>::isValid,
"your handler argument type must be value type or const left " "your handler argument type must be value type or const left "
"reference type or right reference type"); "reference type or right reference type");
using ValueType = std::remove_cv_t< using ValueType =
std::remove_reference_t<nth_argument_type<sizeof...(Values)>>>; typename std::remove_cv<typename std::remove_reference<
nth_argument_type<sizeof...(Values)>>::type>::type;
ValueType value = ValueType();
if (!pathArguments.empty()) if (!pathArguments.empty())
{ {
std::string v{std::move(pathArguments.front())}; std::string v = std::move(pathArguments.front());
pathArguments.pop_front(); pathArguments.pop_front();
try try
{ {
if (!v.empty()) if (v.empty() == false)
{ getHandlerArgumentValue(value, std::move(v));
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) catch (const std::exception &e)
{ {
@ -310,13 +284,7 @@ class HttpBinder : public HttpBinderBase
{ {
try try
{ {
auto value = req->as<ValueType>(); value = req->as<ValueType>();
run(pathArguments,
req,
std::move(callback),
std::forward<Values>(values)...,
std::move(value));
return;
} }
catch (const std::exception &e) catch (const std::exception &e)
{ {
@ -334,11 +302,18 @@ class HttpBinder : public HttpBinderBase
req, req,
std::move(callback), std::move(callback),
std::forward<Values>(values)..., std::forward<Values>(values)...,
ValueType()); std::move(value));
} }
else if constexpr (sizeof...(Values) == Boundary)
{ template <typename... Values,
if constexpr (!isCoroutine) 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)
{ {
try try
{ {
@ -357,38 +332,40 @@ class HttpBinder : public HttpBinderBase
} }
} }
#ifdef __cpp_impl_coroutine #ifdef __cpp_impl_coroutine
else 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, [this](HttpRequestPtr req,
std::function<void(const HttpResponsePtr &)> callback, std::function<void(const HttpResponsePtr &)> callback,
Values &&...values) -> AsyncTask { Values &&...values) -> AsyncTask {
try try
{ {
if constexpr (std::is_same_v< if constexpr (std::is_same_v<AsyncTask,
AsyncTask,
typename traits::return_type>) typename traits::return_type>)
{ {
// Explcit copy because `callFunction` moves it // Explcit copy because `callFunction` moves it
auto cb = callback; auto cb = callback;
callFunction(req, cb, std::move(values)...); callFunction(req, cb, std::move(values)...);
} }
else if constexpr (std::is_same_v< else if constexpr (std::is_same_v<Task<>,
Task<>,
typename traits::return_type>) typename traits::return_type>)
{ {
// Explcit copy because `callFunction` moves it // Explcit copy because `callFunction` moves it
auto cb = callback; auto cb = callback;
co_await callFunction(req, co_await callFunction(req, cb, std::move(values)...);
cb,
std::move(values)...);
} }
else if constexpr (std::is_same_v< else if constexpr (std::is_same_v<Task<HttpResponsePtr>,
Task<HttpResponsePtr>,
typename traits::return_type>) typename traits::return_type>)
{ {
auto resp = auto resp =
co_await callFunction(req, co_await callFunction(req, std::move(values)...);
std::move(values)...);
callback(std::move(resp)); callback(std::move(resp));
} }
} }
@ -398,68 +375,86 @@ class HttpBinder : public HttpBinderBase
} }
catch (...) catch (...)
{ {
LOG_ERROR LOG_ERROR << "Exception not derived from std::exception";
<< "Exception not derived from std::exception";
} }
}(req, std::move(callback), std::move(values)...); }(req, std::move(callback), std::move(values)...);
} }
#endif #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, template <typename... Values,
bool isClassFunction = traits::isClassFunction, bool isClassFunction = traits::isClassFunction,
bool isDrObjectClass = traits::isDrObjectClass, bool isDrObjectClass = traits::isDrObjectClass,
bool isNormal = std::is_same_v<typename traits::first_param_type, bool isNormal = std::is_same<typename traits::first_param_type,
HttpRequestPtr>> HttpRequestPtr>::value>
typename traits::return_type callFunction(const HttpRequestPtr &req, typename std::enable_if<isClassFunction && isDrObjectClass && isNormal,
Values &&...values) typename traits::return_type>::type
callFunction(const HttpRequestPtr &req, Values &&...values)
{ {
if constexpr (isNormal) static auto objPtr =
{ DrClassMap::getSingleInstance<typename traits::class_type>();
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)...); return (*objPtr.*func_)(req, std::move(values)...);
} }
}
else 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)...); return func_(req, std::move(values)...);
} }
}
else 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)
{ {
if constexpr (isClassFunction) static auto &obj = getControllerObj<typename traits::class_type>();
{
if constexpr (!isDrObjectClass)
{
static auto &obj =
getControllerObj<typename traits::class_type>();
return (obj.*func_)((*req), std::move(values)...); return (obj.*func_)((*req), std::move(values)...);
} }
else
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< static auto objPtr =
typename traits::class_type>(); DrClassMap::getSingleInstance<typename traits::class_type>();
return (*objPtr.*func_)((*req), std::move(values)...); return (*objPtr.*func_)((*req), std::move(values)...);
} }
}
else 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)...); return func_((*req), std::move(values)...);
} }
}
}
}; };
} // namespace internal } // namespace internal

View File

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

View File

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

View File

@ -106,7 +106,8 @@ class DROGON_EXPORT PluginBase : public virtual DrObjectBase,
template <typename T> template <typename T>
struct IsPlugin 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 *) static int test(void *)
{ {

View File

@ -50,7 +50,7 @@ struct FunctionTraits;
template <typename Function> template <typename Function>
struct FunctionTraits struct FunctionTraits
: public 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 isClassFunction = false;
static const bool isDrObjectClass = false; static const bool isDrObjectClass = false;
@ -190,7 +190,7 @@ struct FunctionTraits<ReturnType (*)(Arguments...)>
template <std::size_t Index> template <std::size_t Index>
using argument = 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); static const std::size_t arity = sizeof...(Arguments);
using class_type = void; using class_type = void;

View File

@ -37,7 +37,8 @@ struct CanConvertToString
static no test(...); static no test(...);
public: 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 } // namespace internal
@ -52,20 +53,21 @@ class OStringStream
} }
template <typename T> 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; std::stringstream ss;
ss << std::forward<T>(value); ss << std::forward<T>(value);
buffer_.append(ss.str()); buffer_.append(ss.str());
return *this; 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> template <int N>

View File

@ -53,43 +53,9 @@ struct CanConvertFromStringStream
public: public:
static constexpr bool value = 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 internal
namespace utils namespace utils
@ -113,8 +79,7 @@ DROGON_EXPORT std::string genRandomString(int length);
/// Convert a binary string to hex format /// Convert a binary string to hex format
DROGON_EXPORT std::string binaryStringToHex(const unsigned char *ptr, DROGON_EXPORT std::string binaryStringToHex(const unsigned char *ptr,
size_t length, size_t length);
bool lowerCase = false);
/// Get a binary string from hexadecimal format /// Get a binary string from hexadecimal format
DROGON_EXPORT std::string hexToBinaryString(const char *ptr, size_t length); 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, DROGON_EXPORT std::vector<char> hexToBinaryVector(const char *ptr,
size_t length); 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. /// Split the string into multiple separated strings.
/** /**
* @param acceptEmptyString if true, empty strings are accepted in the * @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); const std::string &separator);
/// Get UUID string. /// Get UUID string.
DROGON_EXPORT std::string getUuid(bool lowercase = true); DROGON_EXPORT std::string getUuid();
/// Get the encoded length of base64. /// Get the encoded length of base64.
constexpr size_t base64EncodedLength(size_t in_len, bool padded = true) constexpr size_t base64EncodedLength(size_t in_len, bool padded = true)
@ -436,10 +396,9 @@ DROGON_EXPORT bool secureRandomBytes(void *ptr, size_t size);
DROGON_EXPORT std::string secureRandomString(size_t size); DROGON_EXPORT std::string secureRandomString(size_t size);
template <typename T> 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{}; T value{};
if (!p.empty()) if (!p.empty())
{ {
@ -447,11 +406,14 @@ T fromString(const std::string &p) noexcept(false)
ss >> value; ss >> value;
} }
return value; return value;
} }
else
{ 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"); throw std::runtime_error("Bad type conversion");
}
} }
template <> template <>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -25,9 +25,7 @@ set(UNITTEST_SOURCES
unittests/StringOpsTest.cc unittests/StringOpsTest.cc
unittests/ControllerCreationTest.cc unittests/ControllerCreationTest.cc
unittests/MultiPartParserTest.cc unittests/MultiPartParserTest.cc
unittests/SlashRemoverTest.cc unittests/SlashRemoverTest.cc)
unittests/UuidUnittest.cc
)
if(DROGON_CXX_STANDARD GREATER_EQUAL 20 AND HAS_COROUTINE) if(DROGON_CXX_STANDARD GREATER_EQUAL 20 AND HAS_COROUTINE)
set(UNITTEST_SOURCES ${UNITTEST_SOURCES} unittests/CoroutineTest.cc) 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: public:
#ifdef __cpp_if_constexpr
static ResultType convert_result(const Result &r) static ResultType convert_result(const Result &r)
{ {
if constexpr (SelectAll) 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) inline ResultType execSync(const DbClientPtr &client)
{ {

View File

@ -80,11 +80,12 @@ class CoroMapper : public Mapper<T>
inline internal::MapperAwaiter<T> findByPrimaryKey(const TraitsPKType &key) 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, auto lb = [this, key](SingleRowCallback &&callback,
ExceptPtrCallback &&errCallback) mutable { ExceptPtrCallback &&errCallback) mutable {
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!"); "No primary key in the table!");
static_assert( static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value, internal::has_sqlForFindingByPrimaryKey<T>::value,
@ -416,7 +417,8 @@ class CoroMapper : public Mapper<T>
auto lb = [this, obj](CountCallback &&callback, auto lb = [this, obj](CountCallback &&callback,
ExceptPtrCallback &&errCallback) { ExceptPtrCallback &&errCallback) {
this->clear(); this->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!"); "No primary key in the table!");
std::string sql = "update "; std::string sql = "update ";
sql += T::tableName; sql += T::tableName;
@ -528,7 +530,8 @@ class CoroMapper : public Mapper<T>
auto lb = [this, obj](CountCallback &&callback, auto lb = [this, obj](CountCallback &&callback,
ExceptPtrCallback &&errCallback) { ExceptPtrCallback &&errCallback) {
this->clear(); this->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!"); "No primary key in the table!");
std::string sql = "delete from "; std::string sql = "delete from ";
sql += T::tableName; sql += T::tableName;
@ -552,7 +555,8 @@ class CoroMapper : public Mapper<T>
auto lb = [this, criteria](CountCallback &&callback, auto lb = [this, criteria](CountCallback &&callback,
ExceptPtrCallback &&errCallback) { ExceptPtrCallback &&errCallback) {
this->clear(); this->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!"); "No primary key in the table!");
std::string sql = "delete from "; std::string sql = "delete from ";
sql += T::tableName; sql += T::tableName;
@ -580,7 +584,7 @@ class CoroMapper : public Mapper<T>
inline internal::MapperAwaiter<size_t> deleteByPrimaryKey( inline internal::MapperAwaiter<size_t> deleteByPrimaryKey(
const TraitsPKType &key) 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!"); "No primary key in the table!");
static_assert( static_assert(
internal::has_sqlForDeletingByPrimaryKey<T>::value, 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 std::size_t arity = sizeof...(Arguments);
// static const bool isSqlCallback = false;
static const bool isSqlCallback = true; static const bool isSqlCallback = true;
static const bool isStepResultCallback = true; static const bool isStepResultCallback = true;
static const bool isExceptCallback = false;
static const bool isPtr = false;
}; };
} // namespace internal } // namespace internal
} // namespace orm } // namespace orm

View File

@ -62,7 +62,8 @@ struct has_sqlForFindingByPrimaryKey
static no test(...); static no test(...);
public: 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> template <typename T>
@ -80,7 +81,8 @@ struct has_sqlForDeletingByPrimaryKey
static no test(...); static no test(...);
public: 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 } // namespace internal
@ -183,7 +185,7 @@ class Mapper
using CountCallback = std::function<void(const size_t)>; using CountCallback = std::function<void(const size_t)>;
using TraitsPKType = typename internal:: 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. * @brief Find a record by the primary key.
@ -194,11 +196,12 @@ class Mapper
*/ */
template <typename U = T> 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,
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!"); "No primary key in the table!");
static_assert( static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value, internal::has_sqlForFindingByPrimaryKey<T>::value,
@ -231,12 +234,16 @@ class Mapper
auto row = r[0]; auto row = r[0];
return T(row); return T(row);
} }
else
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"; LOG_FATAL << "The table must have a primary key";
abort(); abort();
} }
}
/** /**
* @brief Asynchronously find a record by the primary key. * @brief Asynchronously find a record by the primary key.
@ -246,13 +253,14 @@ class Mapper
* @param ecb Is called when an error occurs or a record cannot be found. * @param ecb Is called when an error occurs or a record cannot be found.
*/ */
template <typename U = T> template <typename U = T>
inline void findByPrimaryKey(const TraitsPKType &key, inline typename std::enable_if<
!std::is_same<typename U::PrimaryKeyType, void>::value,
void>::type
findByPrimaryKey(const TraitsPKType &key,
const SingleRowCallback &rcb, const SingleRowCallback &rcb,
const ExceptionCallback &ecb) noexcept const ExceptionCallback &ecb) noexcept
{ {
if constexpr (!std::is_same_v<typename U::PrimaryKeyType, void>) static_assert(!std::is_same<typename T::PrimaryKeyType, void>::value,
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!"); "No primary key in the table!");
static_assert( static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value, internal::has_sqlForFindingByPrimaryKey<T>::value,
@ -284,12 +292,18 @@ class Mapper
}; };
binder >> ecb; binder >> ecb;
} }
else
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"; LOG_FATAL << "The table must have a primary key";
abort(); abort();
} }
}
/** /**
* @brief Asynchronously find a record by the primary key. * @brief Asynchronously find a record by the primary key.
@ -301,12 +315,12 @@ class Mapper
* user calls the get() method of the future object. * user calls the get() method of the future object.
*/ */
template <typename U = T> template <typename U = T>
inline std::future<T> findFutureByPrimaryKey( inline typename std::enable_if<
const TraitsPKType &key) noexcept !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,
{
static_assert(!std::is_same_v<typename T::PrimaryKeyType, void>,
"No primary key in the table!"); "No primary key in the table!");
static_assert( static_assert(
internal::has_sqlForFindingByPrimaryKey<T>::value, internal::has_sqlForFindingByPrimaryKey<T>::value,
@ -328,8 +342,8 @@ class Mapper
binder >> [prom](const Result &r) { binder >> [prom](const Result &r) {
if (r.size() == 0) if (r.size() == 0)
{ {
prom->set_exception(std::make_exception_ptr( prom->set_exception(
UnexpectedRows("0 rows found"))); std::make_exception_ptr(UnexpectedRows("0 rows found")));
} }
else if (r.size() > 1) else if (r.size() > 1)
{ {
@ -346,12 +360,16 @@ class Mapper
binder.exec(); binder.exec();
return prom->get_future(); return prom->get_future();
} }
else
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"; LOG_FATAL << "The table must have a primary key";
abort(); abort();
} }
}
/** /**
* @brief Find all the records in the table. * @brief Find all the records in the table.
@ -683,16 +701,20 @@ class Mapper
} }
template <typename PKType = decltype(T::primaryKeyName)> 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
if constexpr (std::is_same_v<const std::string, PKType>) makePrimaryKeyCriteria(std::string &sql)
{ {
sql += " where "; sql += " where ";
sql += T::primaryKeyName; sql += T::primaryKeyName;
sql += " = $?"; sql += " = $?";
} }
else if constexpr (std::is_same_v<const std::vector<std::string>,
PKType>) 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 "; sql += " where ";
for (size_t i = 0; i < T::primaryKeyName.size(); ++i) for (size_t i = 0; i < T::primaryKeyName.size(); ++i)
@ -705,36 +727,42 @@ class Mapper
} }
} }
} }
}
template <typename PKType = decltype(T::primaryKeyName)> template <typename PKType = decltype(T::primaryKeyName)>
void outputPrimeryKeyToBinder(const TraitsPKType &pk, typename std::enable_if<std::is_same<const std::string, PKType>::value,
void>::type
outputPrimeryKeyToBinder(const TraitsPKType &pk,
internal::SqlBinder &binder) internal::SqlBinder &binder)
{
if constexpr (std::is_same_v<const std::string, PKType>)
{ {
binder << pk; binder << pk;
} }
else if constexpr (std::is_same_v<const std::vector<std::string>,
PKType>) 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); tupleToBinder<typename T::PrimaryKeyType>(pk, binder);
} }
}
template <typename TP, ssize_t N = std::tuple_size<TP>::value> 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,
if constexpr (N > 1) internal::SqlBinder &binder)
{ {
tupleToBinder<TP, N - 1>(t, binder); tupleToBinder<TP, N - 1>(t, binder);
binder << std::get<N - 1>(t); binder << std::get<N - 1>(t);
} }
else if constexpr (N == 1)
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); binder << std::get<0>(t);
} }
}
std::string replaceSqlPlaceHolder(const std::string &sqlStr, std::string replaceSqlPlaceHolder(const std::string &sqlStr,
const std::string &holderStr) const; const std::string &holderStr) const;
@ -1293,7 +1321,7 @@ template <typename T>
inline size_t Mapper<T>::update(const T &obj) noexcept(false) inline size_t Mapper<T>::update(const T &obj) noexcept(false)
{ {
clear(); 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!"); "No primary key in the table!");
std::string sql = "update "; std::string sql = "update ";
sql += T::tableName; sql += T::tableName;
@ -1366,7 +1394,7 @@ inline void Mapper<T>::update(const T &obj,
const ExceptionCallback &ecb) noexcept const ExceptionCallback &ecb) noexcept
{ {
clear(); 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!"); "No primary key in the table!");
std::string sql = "update "; std::string sql = "update ";
sql += T::tableName; sql += T::tableName;
@ -1429,7 +1457,7 @@ template <typename T>
inline std::future<size_t> Mapper<T>::updateFuture(const T &obj) noexcept inline std::future<size_t> Mapper<T>::updateFuture(const T &obj) noexcept
{ {
clear(); 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!"); "No primary key in the table!");
std::string sql = "update "; std::string sql = "update ";
sql += T::tableName; sql += T::tableName;
@ -1501,7 +1529,7 @@ template <typename T>
inline size_t Mapper<T>::deleteOne(const T &obj) noexcept(false) inline size_t Mapper<T>::deleteOne(const T &obj) noexcept(false)
{ {
clear(); 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!"); "No primary key in the table!");
std::string sql = "delete from "; std::string sql = "delete from ";
sql += T::tableName; sql += T::tableName;
@ -1528,7 +1556,7 @@ inline void Mapper<T>::deleteOne(const T &obj,
const ExceptionCallback &ecb) noexcept const ExceptionCallback &ecb) noexcept
{ {
clear(); 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!"); "No primary key in the table!");
std::string sql = "delete from "; std::string sql = "delete from ";
sql += T::tableName; sql += T::tableName;
@ -1547,7 +1575,7 @@ template <typename T>
inline std::future<size_t> Mapper<T>::deleteFutureOne(const T &obj) noexcept inline std::future<size_t> Mapper<T>::deleteFutureOne(const T &obj) noexcept
{ {
clear(); 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!"); "No primary key in the table!");
std::string sql = "delete from "; std::string sql = "delete from ";
sql += T::tableName; sql += T::tableName;
@ -1571,7 +1599,7 @@ template <typename T>
inline size_t Mapper<T>::deleteBy(const Criteria &criteria) noexcept(false) inline size_t Mapper<T>::deleteBy(const Criteria &criteria) noexcept(false)
{ {
clear(); 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!"); "No primary key in the table!");
std::string sql = "delete from "; std::string sql = "delete from ";
sql += T::tableName; sql += T::tableName;
@ -1603,7 +1631,7 @@ inline void Mapper<T>::deleteBy(const Criteria &criteria,
const ExceptionCallback &ecb) noexcept const ExceptionCallback &ecb) noexcept
{ {
clear(); 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!"); "No primary key in the table!");
std::string sql = "delete from "; std::string sql = "delete from ";
sql += T::tableName; sql += T::tableName;
@ -1629,7 +1657,7 @@ inline std::future<size_t> Mapper<T>::deleteFutureBy(
const Criteria &criteria) noexcept const Criteria &criteria) noexcept
{ {
clear(); 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!"); "No primary key in the table!");
std::string sql = "delete from "; std::string sql = "delete from ";
sql += T::tableName; sql += T::tableName;
@ -1769,7 +1797,7 @@ template <typename T>
inline size_t Mapper<T>::deleteByPrimaryKey( inline size_t Mapper<T>::deleteByPrimaryKey(
const typename Mapper<T>::TraitsPKType &key) noexcept(false) 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!"); "No primary key in the table!");
static_assert(internal::has_sqlForDeletingByPrimaryKey<T>::value, static_assert(internal::has_sqlForDeletingByPrimaryKey<T>::value,
"No function member named sqlForDeletingByPrimaryKey, please " "No function member named sqlForDeletingByPrimaryKey, please "
@ -1793,7 +1821,7 @@ inline void Mapper<T>::deleteByPrimaryKey(
const CountCallback &rcb, const CountCallback &rcb,
const ExceptionCallback &ecb) noexcept 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!"); "No primary key in the table!");
static_assert(internal::has_sqlForDeletingByPrimaryKey<T>::value, static_assert(internal::has_sqlForDeletingByPrimaryKey<T>::value,
"No function member named sqlForDeletingByPrimaryKey, please " "No function member named sqlForDeletingByPrimaryKey, please "
@ -1811,7 +1839,7 @@ template <typename T>
inline std::future<size_t> Mapper<T>::deleteFutureByPrimaryKey( inline std::future<size_t> Mapper<T>::deleteFutureByPrimaryKey(
const typename Mapper<T>::TraitsPKType &key) noexcept 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!"); "No primary key in the table!");
static_assert(internal::has_sqlForDeletingByPrimaryKey<T>::value, static_assert(internal::has_sqlForDeletingByPrimaryKey<T>::value,
"No function member named sqlForDeletingByPrimaryKey, please " "No function member named sqlForDeletingByPrimaryKey, please "

View File

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

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