icingaweb2/library/Icinga/Common/Database.php
Eric Lippmann 298f52456f Use Pdo\Mysql driver-specific constants
Replace deprecated `PDO::MYSQL_*` constant usage with the driver-specific
`Pdo\Mysql::ATTR_*` constants introduced in PHP 8.4.

This prepares the code for PHP 8.5, where accessing MySQL driver constants
through the generic `PDO` class is deprecated.

This change requires a compatibility shim on older PHP versions to provide
`Pdo\Mysql` for runtimes that do not expose the driver-specific class yet.  The
shim is provided in `ipl-sql`. As a consequence, the required version of the
Icinga PHP library has been raised.
2026-03-19 22:27:45 +01:00

57 lines
1.5 KiB
PHP

<?php
/* Icinga Web 2 | (c) 2020 Icinga GmbH | GPLv2+ */
namespace Icinga\Common;
use Icinga\Application\Config as IcingaConfig;
use Icinga\Data\ResourceFactory;
use ipl\Sql\Config as SqlConfig;
use ipl\Sql\Connection;
use LogicException;
use PDO;
use Pdo\Mysql;
/**
* Trait for accessing the Icinga Web database
*/
trait Database
{
/**
* Get a connection to the Icinga Web database
*
* @return Connection
*
* @throws \Icinga\Exception\ConfigurationError
*/
protected function getDb(): Connection
{
if (! $this->hasDb()) {
throw new LogicException('Please check if a db instance exists at all');
}
$config = new SqlConfig(ResourceFactory::getResourceConfig(
IcingaConfig::app()->get('global', 'config_resource')
));
if ($config->db === 'mysql') {
$config->charset = 'utf8mb4';
}
$config->options = [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ];
if ($config->db === 'mysql') {
$config->options[Mysql::ATTR_INIT_COMMAND] = "SET SESSION SQL_MODE='STRICT_TRANS_TABLES"
. ",NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'";
}
return new Connection($config);
}
/**
* Check if db exists
*
* @return bool true if a database was found otherwise false
*/
protected function hasDb()
{
return (bool) IcingaConfig::app()->get('global', 'config_resource');
}
}