Pgsql.php 1.8 KB

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