pq\LOB docs
[mdref/mdref-pq] / pq / Connection / : Asynchronous Usage.md
1 # pq\Connection: Asynchronous Usage
2
3 Whenever you start an asynchronous operation, you will have to probe pq\Connection::poll() to determine the current status of the operation.
4
5 You can then use the ***public readonly*** property pq\Connection::$socket with ```stream_select()``` to wait for read/write-readiness.
6
7 > ***NOTE:***
8 You cannot use the connection for anything else while an asynchronous operation is active.
9
10 ## Connect or reset asynchronously:
11
12 First, you can establish or reset a connection asynchronously.
13
14 ### Start asynchronous connect:
15
16 <?php
17
18 $c = new pq\Connection(null, pq\Connection::ASYNC);
19
20 ?>
21
22 ### Start asynchronous reset:
23
24 <?php
25
26 $c->resetAsync();
27
28 ?>
29
30 ### Complete asynchronous operation:
31
32 Keep in mind that you have to test for write-readiness once *before* starting the polling loop on connect/reset.
33
34 <?php
35
36 // wait until the stream becomes writable
37 $w = array($c->socket);
38 $r = $e = null;
39
40 if (stream_select($r, $w, $e, null)) {
41
42 // loop until the connection is established
43 while (true) {
44
45 switch ($c->poll()) {
46
47 case pq\Connection::POLLING_READING:
48 // we should wait for the stream to be read-ready
49 $r = array($c->socket);
50 stream_select($r, $w, $e, NULL);
51 break;
52
53 case pq\Connection::POLLING_WRITING:
54 // we should wait for the stream to be write-ready
55 $w = array($c->socket);
56 $r = $e = null;
57 stream_select($r, $w, $e, null);
58 break;
59
60 case pq\Connection::POLLING_FAILED:
61 printf("Connection failed: %s\n", $c->errorMessage);
62 break 2;
63
64 case pq\Connection::POLLING_OK:
65 printf("Connection completed\n");
66 break 2;
67 }
68 }
69
70 ?>
71
72
73 If you use an appropriate timeout in the ```stream_select()``` call and do something else at the end of the while loop, you probably got the idea...
74
75 ## Execute queries asynchronously:
76
77 <?php
78
79 $c = new pq\Connection;
80 $c->execAsync("SELECT 1+2+3; SELECT 2,3,4", function ($res) {
81 var_dump($res);
82 });
83
84 ?>
85
86 The body of the while loop looks slightly different, when executing queries asynchronously, because you only have to wait for read-readiness.
87
88 You can use the ***public readonly*** property pq\Connection::$busy to test if a call to pq\Connection::getResult() would block, and if so wait for read-readiness and then call pq\Connection::poll().
89
90 <?php
91
92 do {
93 while ($c->busy) {
94 $r = array($c->socket);
95 $w = $e = null;
96 if (stream_select($r, $w, $e, null)) {
97 $c->poll();
98 }
99 }
100 } while ($c->getResult());
101
102 ?>
103
104 If pq\Connection::getResult() returns NULL, there's nothing more in the pipeline.