Raw.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * This file is part of webman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<[email protected]>
  10. * @copyright walkor<[email protected]>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace support\bootstrap\db;
  15. use Webman\Bootstrap;
  16. use Workerman\Worker;
  17. use PDOStatement;
  18. use PDO;
  19. /**
  20. * Class Raw
  21. * @package support\bootstrap\db
  22. */
  23. class Raw implements Bootstrap
  24. {
  25. public static PDO $pdo;
  26. public static PDOStatement $fortune;
  27. public static PDOStatement $random;
  28. /**
  29. * @var PDOStatement[]
  30. */
  31. public static array $update;
  32. /**
  33. * @param Worker $worker
  34. *
  35. * @return void
  36. */
  37. public static function start($worker)
  38. {
  39. $pdo = new PDO('pgsql:host=tfb-database;dbname=hello_world',
  40. 'benchmarkdbuser', 'benchmarkdbpass',
  41. [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  42. PDO::ATTR_EMULATE_PREPARES => false]
  43. );
  44. self::$random = $pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  45. self::$fortune = $pdo->prepare('SELECT id,message FROM Fortune');
  46. self::$pdo = $pdo;
  47. }
  48. /**
  49. * Postgres bulk update
  50. *
  51. * @param array $worlds
  52. * @return void
  53. */
  54. public static function update(array $worlds)
  55. {
  56. $rows = count($worlds);
  57. if (!isset(self::$update[$rows])) {
  58. $sql = 'UPDATE world SET randomNumber = CASE id'
  59. . str_repeat(' WHEN ?::INTEGER THEN ?::INTEGER ', $rows)
  60. . 'END WHERE id IN ('
  61. . str_repeat('?::INTEGER,', $rows - 1) . '?::INTEGER)';
  62. self::$update[$rows] = self::$pdo->prepare($sql);
  63. }
  64. $val = [];
  65. $keys = [];
  66. foreach ($worlds as $world) {
  67. $val[] = $keys[] = $world['id'];
  68. $val[] = $world['randomNumber'];
  69. }
  70. self::$update[$rows]->execute([...$val, ...$keys]);
  71. }
  72. }