m6w6 / ext-pq

PostgreSQL client library (libpq) binding
BSD 2-Clause "Simplified" License
39 stars 7 forks source link

listenAsync - don't work polling #11

Closed ParkFramework closed 8 years ago

ParkFramework commented 8 years ago

$db = new pq\Connection($dsn);

$db->listenAsync('name', function($name, $message)
{
    echo $message;
});

$r = [$db->socket];
$w = $e = null;

while(stream_select($r, $w, $e, 10))
{
    $db->poll();
}

Next for 10 seconds - psql:

NOTIFY name, 'Hello World!';

PHP script callback notification not called, if use $db->listen(...) then everything works.

m6w6 commented 8 years ago

PostgreSQL notifications don't work that way.

  1. See https://mdref.m6w6.name/pq/Connection/:%20Asynchronous%20Usage for how to properly perform asynchronous operations
  2. You have to fetch the result of the pq\Connection::listenAsync() with pq\Connection::getResult()
  3. PostgreSQL notifications do not arrive out of band, they are received while performing other queries

HTH

m6w6 commented 8 years ago

Here's a working example, but I'm not sure how applicable it is to real world situations:

$c = new pq\Connection;
$x = false;
$c->listenAsync('name', function($name, $message) use(&$x) {
        $x = true;
        echo $message;
});
do {
  while ($c->busy) {
    $r = array($c->socket);
    $w = $e = null;
    if (stream_select($r, $w, $e, 10)) {
      $c->poll();
    }
  }
} while (($c->getResult() && $c->execAsync("")) || !$x);
ParkFramework commented 8 years ago

Ok.

Block time listen() and notify() is very small, so it's best to use them without async.

Tthank.