add is_connected method to database (#7225)

This commit is contained in:
frytimo 2025-01-23 14:42:19 -04:00 committed by GitHub
parent 18bce0437d
commit 95faf83337
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 38 additions and 8 deletions

View File

@ -575,7 +575,7 @@
}
}
}
catch (PDOException $error) {
catch (PDOException $e) {
$message['message'] = $e->getMessage();
$message['code'] = $e->getCode();
$message['line'] = $e->getLine();
@ -603,7 +603,7 @@
$this->db = new PDO("pgsql:dbname=$this->db_name user=$this->username password=$this->password");
}
}
catch (PDOException $error) {
catch (PDOException $e) {
$message['message'] = $e->getMessage();
$message['code'] = $e->getCode();
$message['line'] = $e->getLine();
@ -755,11 +755,11 @@
//if unable to connect to the database
if (!$this->db) {
$message['message'] = $e->getMessage();
$message['code'] = $e->getCode();
$message['line'] = $e->getLine();
$message['file'] = $e->getFile();
$message['trace'] = $e->getTraceAsString();
$message['message'] = 'Unable to connect to database';
$message['code'] = '500';
$message['line'] = __LINE__;
$message['file'] = __FILE__;
$message['trace'] = '';
$message['debug'] = debug_backtrace();
$this->message = $message;
return false;
@ -2948,6 +2948,34 @@
return $this->message;
} //save method
/**
* Ensure the database is still connected and active.
* <p>NOTE:<br>
* There is no method in PDO that can reliably detect if the connection is active. Therefor, a lightweight
* query is executed using the statement <code>select 1</code>.</p>
* @return bool True if the database is connected. False otherwise.
*/
public function is_connected(): bool {
try {
$stmt = $this->db->query('SELECT 1');
return $stmt !== false;
} catch (PDOException $ex) {
//database is not connected
return false;
} catch (Exception $e) {
//some other error has occurred so record it
$message['message'] = $e->getMessage();
$message['code'] = $e->getCode();
$message['line'] = $e->getLine();
$message['file'] = $e->getFile();
$message['trace'] = $e->getTraceAsString();
$message['debug'] = debug_backtrace();
$this->message = $message;
return false;
}
return true;
}
/**
* Converts a plural English word to singular.
* @param string $word English word
@ -3171,8 +3199,10 @@
public static function new(array $params = []) {
if (self::$database === null) {
self::$database = new database($params);
if (!self::$database->is_connected()) {
self::$database->connect();
}
}
return self::$database;
}