singledatabasequerytest.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "singledatabasequerytest.h"
  2. #include <Cutelyst/Plugins/Utils/Sql>
  3. #include <apool.h>
  4. #include <aresult.h>
  5. #include <apreparedquery.h>
  6. #include <QSqlQuery>
  7. #include <QJsonDocument>
  8. #include <QJsonObject>
  9. #include "picojson.h"
  10. SingleDatabaseQueryTest::SingleDatabaseQueryTest(QObject *parent) : Controller(parent)
  11. {
  12. }
  13. void SingleDatabaseQueryTest::dbp(Context *c)
  14. {
  15. const int id = (qrand() % 10000) + 1;
  16. ASync async(c);
  17. static thread_local auto db = APool::database();
  18. db.exec(APreparedQueryLiteral(u"SELECT id, randomNumber FROM world WHERE id=$1"),
  19. {id}, [c, async] (AResult &result) {
  20. if (Q_LIKELY(!result.error() && result.size())) {
  21. auto it = result.begin();
  22. c->response()->setJsonBody(QByteArray::fromStdString(
  23. picojson::value(picojson::object({
  24. {"id", picojson::value(double(it[0].toInt()))},
  25. {"randomNumber", picojson::value(double(it[1].toInt()))}
  26. })).serialize()));
  27. return;
  28. }
  29. c->res()->setStatus(Response::InternalServerError);
  30. }, c);
  31. }
  32. void SingleDatabaseQueryTest::db_postgres(Context *c)
  33. {
  34. QSqlQuery query = CPreparedSqlQueryThreadForDB(
  35. QLatin1String("SELECT id, randomNumber FROM world WHERE id = :id"),
  36. QStringLiteral("postgres"));
  37. processQuery(c, query);
  38. }
  39. void SingleDatabaseQueryTest::db_mysql(Context *c)
  40. {
  41. QSqlQuery query = CPreparedSqlQueryThreadForDB(
  42. QLatin1String("SELECT id, randomNumber FROM world WHERE id = :id"),
  43. QStringLiteral("mysql"));
  44. processQuery(c, query);
  45. }
  46. void SingleDatabaseQueryTest::processQuery(Context *c, QSqlQuery &query)
  47. {
  48. int id = (qrand() % 10000) + 1;
  49. query.bindValue(QStringLiteral(":id"), id);
  50. if (Q_UNLIKELY(!query.exec() || !query.next())) {
  51. c->res()->setStatus(Response::InternalServerError);
  52. return;
  53. }
  54. c->response()->setJsonObjectBody({
  55. {QStringLiteral("id"), query.value(0).toInt()},
  56. {QStringLiteral("randomNumber"), query.value(1).toInt()}
  57. });
  58. }