<!--#
Test type 5: Database updates
TechEmpower Web Framework Benchmarks
-->
<!--#declaration
#include "world.h"

#ifdef U_STATIC_ORM_DRIVER_PGSQL
static char query[8192];

static void handlerResult(void* res, uint32_t num_result)
{
   U_TRACE(5, "::handlerResult(%p,%u)", res, num_result)

   U_INTERNAL_ASSERT_EQUALS(PQnfields((PGresult*)res), 1)
   U_INTERNAL_ASSERT_EQUALS(PQntuples((PGresult*)res), 1)

   (void) U_SYSCALL(PQgetvalue, "%p,%d,%d", (PGresult*)res, 0, 0);
}
#endif

static UOrmStatement* pstmt_update;

static void usp_init_update() { World::handlerInitSql(); }
static void usp_fork_update()
{
   U_TRACE(5, "::usp_fork_update()")

   World::handlerForkSql();

   if (World::psql_query)
      {
#  ifdef U_STATIC_ORM_DRIVER_PGSQL
      if (World::pstmt) (void) memcpy(query, U_CONSTANT_TO_PARAM("UPDATE World SET randomNumber = v.randomNumber FROM (VALUES"));
      else
#  endif
      {
      U_NEW(UOrmStatement, pstmt_update, UOrmStatement(*World::psql_query, U_CONSTANT_TO_PARAM("UPDATE World SET randomNumber = ? WHERE id = ?")));

      pstmt_update->use(World::pworld_query->randomNumber, World::pworld_query->id);
      }
      }
}
-->
<!--#header
-->
<!--#code
uint32_t i = 0, num_queries = UHTTP::getFormFirstNumericValue(1, 500);

World::initResult();

#ifdef U_STATIC_ORM_DRIVER_PGSQL
if (World::pstmt)
   {
   char* pquery = query + U_CONSTANT_SIZE("UPDATE World SET randomNumber = v.randomNumber FROM (VALUES");

   for (; i < num_queries; ++i)
      {
      World::sendQueryPrepared(i);

      *pquery = '(';
       pquery = u_num2str32(World::rnumber[i], pquery+1);
      *pquery = ',';
       pquery = u_num2str32(World::rnum = u_get_num_random_range1(10000), pquery+1);

      u_put_unalignedp16(pquery, U_MULTICHAR_CONSTANT16(')',','));
                         pquery += 2;

      World::handlerResult(i, World::rnum);
      }

   World::endResult();

   (void) memcpy(pquery-1, ") AS v (id,randomNumber) WHERE World.id = v.id;",
           U_CONSTANT_SIZE(") AS v (id,randomNumber) WHERE World.id = v.id;")+1);

   (void) U_SYSCALL(PQsendQueryParams, "%p,%S,%u,%p,%p,%p,%p,%u", World::conn, query, 0, 0, 0, 0, 0, 1);

   UServer_Base::handler_db1->handlerQuery(handlerResult, num_queries);
   }
else
#endif
{
for (; i < num_queries; ++i)
   {
   World::pworld_query->id = World::rnumber[i];

   World::pstmt_query->execute();

   World::pworld_query->randomNumber = u_get_num_random_range1(10000);

   pstmt_update->execute();

   World::handlerResult(i, World::pworld_query->randomNumber);
   }

World::endResult();
}
-->
