PgsqlSwoole.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. use Swoole\Database\PDOConfig;
  3. use Swoole\Database\PDOPool;
  4. class PgsqlSwoole extends MysqlSwoole
  5. {
  6. protected Pool|PDOPool $pool;
  7. public function __construct($size)
  8. {
  9. $config = (new PDOConfig())
  10. ->withDriver('pgsql')
  11. ->withHost('tfb-database')
  12. ->withPort(5432)
  13. ->withDbName('hello_world')
  14. ->withUsername('benchmarkdbuser')
  15. ->withPassword('benchmarkdbpass');
  16. $this->pool = new PDOPool($config, $size);
  17. }
  18. function update($request): array
  19. {
  20. $query_count = 1;
  21. $q = (int)$request->get('q');
  22. if ($q > 1) {
  23. $query_count = min($q, 500);
  24. }
  25. $worlds = [];
  26. $pdo = $this->pool->get();
  27. $random = $pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  28. while ($query_count--) {
  29. $random->execute([mt_rand(1, 10000)]);
  30. $world = $random->fetch(PDO::FETCH_ASSOC);
  31. $world['randomNumber'] = mt_rand(1, 10000);
  32. $worlds[] = $world;
  33. }
  34. $rows = count($worlds);
  35. $sql = 'UPDATE world SET randomNumber = CASE id'
  36. . str_repeat(' WHEN ?::INTEGER THEN ?::INTEGER ', $rows)
  37. . 'END WHERE id IN ('
  38. . str_repeat('?::INTEGER,', $rows - 1) . '?::INTEGER)';
  39. $update = $pdo->prepare($sql);
  40. $val = [];
  41. $keys = [];
  42. foreach ($worlds as $world) {
  43. $val[] = $keys[] = $world['id'];
  44. $val[] = $world['randomNumber'];
  45. }
  46. $update->execute([...$val, ...$keys]);
  47. $this->pool->put($pdo);
  48. return $worlds;
  49. }
  50. }