Pgsql.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. class Pgsql extends Mysql
  3. {
  4. protected PDO $pdo;
  5. protected PDOStatement $world;
  6. protected PDOStatement $fortune;
  7. protected PDOStatement $update;
  8. protected PDOStatement $random;
  9. protected array $updates = [];
  10. public function __construct()
  11. {
  12. $this->pdo = new PDO(
  13. 'pgsql:host=tfb-database;dbname=hello_world',
  14. 'benchmarkdbuser',
  15. 'benchmarkdbpass',
  16. [
  17. PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  18. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  19. PDO::ATTR_EMULATE_PREPARES => false
  20. ]
  21. );
  22. $this->world = $this->random = $this->pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  23. $this->fortune = $this->pdo->prepare('SELECT id,message FROM Fortune');
  24. $this->update = $this->pdo->prepare('UPDATE World SET randomNumber=? WHERE id=?');
  25. }
  26. function update($request): array
  27. {
  28. $query_count = 1;
  29. $q = (int)$request->get('q');
  30. if ($q > 1) {
  31. $query_count = min($q, 500);
  32. }
  33. $worlds = [];
  34. while ($query_count--) {
  35. $this->random->execute([\mt_rand(1, 10000)]);
  36. $world = $this->random->fetch();
  37. $world['randomNumber'] = \mt_rand(1, 10000);
  38. $worlds[] = $world;
  39. }
  40. $rows = count($worlds);
  41. if (!isset($this->updates[$rows])) {
  42. $sql = 'UPDATE world SET randomNumber = CASE id'
  43. . str_repeat(' WHEN ?::INTEGER THEN ?::INTEGER ', $rows)
  44. . 'END WHERE id IN ('
  45. . str_repeat('?::INTEGER,', $rows - 1) . '?::INTEGER)';
  46. $this->updates[$rows] = $this->pdo->prepare($sql);
  47. }
  48. $val = [];
  49. $keys = [];
  50. foreach ($worlds as $world) {
  51. $val[] = $keys[] = $world['id'];
  52. $val[] = $world['randomNumber'];
  53. }
  54. $this->updates[$rows]->execute([...$val, ...$keys]);
  55. return $worlds;
  56. }
  57. }