Pgsql.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. $queries = $request->get('q');
  29. $worlds = $keys = $values = [];
  30. $count = min(max((int) $queries, 1), 500);
  31. for ($i = 0; $i < $count; ++ $i) {
  32. $values[] = $keys[] = $id = mt_rand(1, 10000);
  33. $this->random->execute([$id]);
  34. $row = $this->random->fetch();
  35. $values[] = $row['randomNumber'] = mt_rand(1, 10000);
  36. $worlds[] = $row;
  37. }
  38. if (!isset($this->updates[$count])) {
  39. $sql = 'UPDATE World SET randomNumber = CASE id' . str_repeat(' WHEN ?::INTEGER THEN ?::INTEGER ', $count) . 'END WHERE id IN (' . str_repeat('?::INTEGER,', $count - 1) . '?::INTEGER)';
  40. $this->updates[$count] = $this->pdo->prepare($sql);
  41. }
  42. $this->updates[$count]->execute([...$values, ...$keys]);
  43. return $worlds;
  44. }
  45. }