Flourish PHP Unframework
This is an archived copy of the forum for reference purposes

Database connection timeout handling

posted by gabrielu 9 years ago

What is the proper way to handle database connection timeouts with flourish?

When extension_loaded('mysql') was run before extension_loaded('mysqli') I was able to set a 5 second database timeout as follows:

define('DB_DOWN_REDIRECT', '/updating');

function &Database()
{
	// avoid connecting to db when down
	if (fURL::get() == DB_DOWN_REDIRECT)
		return;
		
	static $database = NULL;
	
	if ($database == NULL) {
		try {
			ini_set('mysql.connect_timeout', '5');
			
			$database = new fDatabase('mysql', 'db', 'user', 'pass', 'localhost');
			
			if ($database->getExtension() == 'mysqli') {
				echo "Recommend you disable the mysqli extension for db timeout handling.  Change flourish fDatabase.php so that mysql extension is loaded before mysqli extension within determineExtension().";
				exit;
			}
			
			// attempt to connect now to avoid connection issues later
			$connected = $database->getConnection();
			
			fORMDatabase::attach($database);
		} catch (Exception $e) {
			// database connection failed
			fURL::redirect(DB_DOWN_REDIRECT);
		}
	}
	
	return $database;
}

Database();

You'll notice that in the code above I check if we loaded the "mysqli" extension and display a message to myself as a reminder for when I update flourish. At the moment my solution is to manually edit fDatabase.php so that "mysql" extension is checked/loaded first. I do this because there doesn't seem to be a simple solution to set the connection timeout to mysqli without removing the extension from the server.

Could timeout handling be added to fDatabase? or maybe integrate mysqli_real_connect() into fDatabase so that timeouts can be set?

Is there a better way to handle db timeouts with flourish?

Adding a parameter to fDatabase to control the timeout would be a good thing to do. Can you open a ticket for that?

In the meantime you can extend fDatabase and override the extension member to ensure you always use mysql.

class Database extends fDatabase {
    protected function determineExtension()
    {
        $this->extension = 'mysql';
    }
}

$db = new Database();
posted by wbond 9 years ago

Thanks @wbond. I had tried this method but forgot to use "protected" so it didn't work for me. This works! :)

Ticket submitted...

posted by gabrielu 9 years ago