Repository navigation
Expand file tree
/
Copy pathpdo_pgsql.php
More file actions
executable file
·55 lines (48 loc) · 1.81 KB
/
Copy pathpdo_pgsql.php
File metadata and controls
executable file
·55 lines (48 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env php
<?php
declare(strict_types=1);
/**
* This example shows how to interact with PostgreSQL using the PDO_PGSQL driver.
*
* In this example, we make five PostgreSQL connections, and perform a three-second query in each connection. It takes
* barely over three seconds to run this script.
*
* The PDO_PGSQL driver works in coroutines only when Swoole is compiled with the --enable-swoole-pgsql option, as it is
* in the Docker images used by this repository.
*
* How to run this script:
* docker compose exec -t client bash -c "./hooks/pdo_pgsql.php"
*
* You can run the following command to see how much time it takes to run the script:
* docker compose exec -t client bash -c "time ./hooks/pdo_pgsql.php"
*/
use Swoole\Constant;
use Swoole\Coroutine;
use function Swoole\Coroutine\go;
use function Swoole\Coroutine\run;
// This statement is optional because hook flags are set to SWOOLE_HOOK_ALL by default, and flag SWOOLE_HOOK_ALL has
// flag SWOOLE_HOOK_PDO_PGSQL included already.
Coroutine::set([Constant::OPTION_HOOK_FLAGS => SWOOLE_HOOK_PDO_PGSQL]);
run(function (): void {
for ($i = 0; $i < 5; $i++) {
go(function (): void {
$pdo = new PDO('pgsql:host=postgresql;port=5432;dbname=test', 'username', 'password');
$stmt = $pdo->prepare('SELECT pg_sleep(3)');
if ($stmt === false) {
echo 'Failed to prepare the statement.', PHP_EOL;
return;
}
$stmt->execute(); // The query finishes in 3 seconds.
$stmt->fetchAll();
// The result array returned is:
// [
// [
// 'pg_sleep' => '',
// 0 => '',
// ]
// ];
$stmt = null;
$pdo = null;
});
}
});