1+ <?php
2+
3+ use Swoole \Database \PDOConfig ;
4+ use Swoole \Database \PDOPool ;
5+ class MysqlSwoole
6+ {
7+
8+ protected Pool |PDOPool $ pool ;
9+
10+ public function __construct ($ size )
11+ {
12+ $ config = (new PDOConfig ())
13+ ->withDriver ('mysql ' )
14+ ->withHost ('tfb-database ' )
15+ ->withPort (3306 )
16+ ->withDbName ('hello_world ' )
17+ ->withUsername ('benchmarkdbuser ' )
18+ ->withPassword ('benchmarkdbpass ' );
19+ $ this ->pool = new PDOPool ($ config , $ size );
20+ }
21+
22+ function db (): array
23+ {
24+ $ pdo = $ this ->pool ->get ();
25+ $ stmt = $ pdo ->prepare ('SELECT id,randomNumber FROM World WHERE id=? ' );
26+ $ stmt ->execute ([mt_rand (1 , 10000 )]);
27+ $ result = $ stmt ->fetch (PDO ::FETCH_ASSOC );
28+ $ this ->pool ->put ($ pdo );
29+ return $ result ;
30+ }
31+
32+ function query ($ request ): array
33+ {
34+ $ query_count = 1 ;
35+ $ q = (int )$ request ->get ('q ' );
36+ if ($ q > 1 ) {
37+ $ query_count = min ($ q , 500 );
38+ }
39+ $ pdo = $ this ->pool ->get ();
40+ $ stmt = $ pdo ->prepare ('SELECT id,randomNumber FROM World WHERE id=? ' );
41+ $ arr = [];
42+ while ($ query_count --) {
43+ $ stmt ->execute ([mt_rand (1 , 10000 )]);
44+ $ arr [] = $ stmt ->fetch (PDO ::FETCH_ASSOC );
45+ }
46+ $ this ->pool ->put ($ pdo );
47+ return $ arr ;
48+ }
49+
50+ function update ($ request ): array
51+ {
52+ $ query_count = 1 ;
53+ $ q = (int )$ request ->get ('q ' );
54+ if ($ q > 1 ) {
55+ $ query_count = min ($ q , 500 );
56+ }
57+ $ arr = [];
58+ $ pdo = $ this ->pool ->get ();
59+ $ world = $ pdo ->prepare ('SELECT id,randomNumber FROM World WHERE id=? ' );
60+ $ update = $ pdo ->prepare ('UPDATE World SET randomNumber=? WHERE id=? ' );
61+ while ($ query_count --) {
62+ $ id = mt_rand (1 , 10000 );
63+ $ world ->execute ([$ id ]);
64+ $ item = $ world ->fetch (PDO ::FETCH_ASSOC );
65+ $ update ->execute (
66+ [$ item ['randomNumber ' ] = mt_rand (1 , 10000 ), $ id ]
67+ );
68+ $ arr [] = $ item ;
69+ }
70+ $ this ->pool ->put ($ pdo );
71+ return $ arr ;
72+ }
73+
74+ function fortune (): string
75+ {
76+ $ pdo = $ this ->pool ->get ();
77+ $ stmt = $ pdo ->prepare ('SELECT id,message FROM Fortune ' );
78+ $ stmt ->execute ();
79+ $ arr = $ stmt ->fetchAll (PDO ::FETCH_KEY_PAIR );
80+ $ this ->pool ->put ($ pdo );
81+ $ arr [0 ] = 'Additional fortune added at request time. ' ;
82+ asort ($ arr );
83+ $ html = '' ;
84+ foreach ($ arr as $ id => $ message ) {
85+ $ message = htmlspecialchars ($ message , ENT_QUOTES , 'UTF-8 ' );
86+ $ html .= "<tr><td> $ id</td><td> $ message</td></tr> " ;
87+ }
88+ return "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr> $ html</table></body></html> " ;
89+ }
90+
91+ }
0 commit comments