We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

PDO ignoring ATTR_TIMEOUT

Ref. issue #3149

https://github.com/phalcon/cphalcon/issues/3149

  • I connect to an external MySql DB just on one page
  • In order to connect to this external Database, I'm using \Phalcon\Db\Adapter\Pdo\MySql object
  • I'm doing this because this new connection will be used by some Models built specifically for this external DB
  • Sometimes this external DB is not accessible or it takes a very long time to establish the connection
  • When I build this new connection, I'm using the following code:
ini_set( 'default_socket_timeout', $settings->EXTERNAL_CONNECTION_TIMEOUT );
ini_set( 'connect_timeout', $settings->EXTERNAL_CONNECTION_TIMEOUT );
ini_set( 'mysql.connect_timeout', $settings->EXTERNAL_CONNECTION_TIMEOUT );
ini_set( 'mysqlnd.net_read_timeout', $settings->EXTERNAL_CONNECTION_TIMEOUT );

$externalDB = new \Phalcon\Db\Adapter\Pdo\Mysql( array(
    'host'        => $hostname,
    'username'    => $dbUser,
    'password'    => $dbPassword,
    'dbname'      => $database->dbname,
    'charset'     => $database->charset,
    \PDO::ATTR_TIMEOUT => $settings->EXTERNAL_CONNECTION_TIMEOUT,
));

where $settings->EXTERNAL_CONNECTION_TIMEOUT is a parameter with the number of seconds for the timeout.

PROBLEM: actually the timeout is completely ignored by the application. Nginx will throw a 504 Gateway timeout error after 60 seconds.

If I put, for instance, $settings->EXTERNAL_CONNECTION_TIMEOUT = 1 second it will still wait 60 seconds before throwing 504.

Could you please help me?

I'm using Phalcon 3.0.3, PHP 7.0, Nginx.



79.0k
Accepted
answer
edited Jul '17

Nginx timeout has nothing to with PDO timeout.

And for additional PDO settings you need to put them into 'options' array.

example when $dbConfig is a single level array like your config is:

$dbConfig['options'] = [
        PDO::ATTR_DEFAULT_FETCH_MODE => 2
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ];

And try to get rid of array() syntax, in favor of []:

$externalDB = new \Phalcon\Db\Adapter\Pdo\Mysql([
    'host'        => $hostname,
    'username'    => $dbUser,
    'password'    => $dbPassword,
    'dbname'      => $database->dbname,
    'charset'     => $database->charset,
    'options' => [\PDO::ATTR_TIMEOUT => $settings->EXTERNAL_CONNECTION_TIMEOUT]
]);


12.9k

My fault. Stupidly, I had inserted the timeout configuration parameter directly into the connection array and not in the 'options' field.