DbHelpers, Connection: improve escapeBinary logic

hex-style for MySQL too, support array values
This commit is contained in:
Thomas Gelf 2022-07-01 08:39:12 +02:00
parent 14317a9c20
commit 0796635132
3 changed files with 94 additions and 4 deletions

View File

@ -20,15 +20,19 @@ class DbConnection extends IcingaDbConnection
public function quoteBinary($binary)
{
if ($binary instanceof Zend_Db_Expr) {
throw new RuntimeException('Trying to escape binary twice');
if ($binary === '') {
return '';
}
if (is_array($binary)) {
return array_map([$this, 'quoteBinary'], $binary);
}
if ($this->isPgsql()) {
return new Zend_Db_Expr("'\\x" . bin2hex($binary) . "'");
}
return $binary;
return new Zend_Db_Expr('0x' . bin2hex($binary));
}
public function binaryDbResult($value)

View File

@ -2,6 +2,14 @@
namespace Icinga\Module\Director\Db;
use gipfl\ZfDb\Adapter\Adapter;
use gipfl\ZfDb\Adapter\Pdo\Pgsql;
use gipfl\ZfDb\Expr;
use Zend_Db_Adapter_Abstract;
use Zend_Db_Adapter_Pdo_Pgsql;
use Zend_Db_Expr;
use function bin2hex;
use function is_array;
use function is_resource;
use function stream_get_contents;
@ -15,4 +23,74 @@ class DbUtil
return $value;
}
/**
* @param string|array $binary
* @param Zend_Db_Adapter_Abstract $db
* @return Zend_Db_Expr|Zend_Db_Expr[]
*/
public static function quoteBinaryLegacy($binary, $db)
{
if (is_array($binary)) {
return static::quoteArray($binary, 'quoteBinaryLegacy', $db);
}
if ($binary === null) {
return null;
}
if ($db instanceof Zend_Db_Adapter_Pdo_Pgsql) {
return new Zend_Db_Expr("'\\x" . bin2hex($binary) . "'");
}
return new Zend_Db_Expr('0x' . bin2hex($binary));
}
/**
* @param string|array $binary
* @param Adapter $db
* @return Expr|Expr[]
*/
public static function quoteBinary($binary, $db)
{
if (is_array($binary)) {
return static::quoteArray($binary, 'quoteBinary', $db);
}
if ($binary === null) {
return null;
}
if ($db instanceof Pgsql) {
return new Expr("'\\x" . bin2hex($binary) . "'");
}
return new Expr('0x' . bin2hex($binary));
}
/**
* @param string|array $binary
* @param Adapter|Zend_Db_Adapter_Abstract $db
* @return Expr|Zend_Db_Expr|Expr[]|Zend_Db_Expr[]
*/
public static function quoteBinaryCompat($binary, $db)
{
if ($db instanceof Adapter) {
return static::quoteBinary($binary, $db);
}
return static::quoteBinaryLegacy($binary, $db);
}
protected static function quoteArray($array, $method, $db)
{
$result = [];
foreach ($array as $bin) {
$quoted = static::$method($bin, $db);
$result[] = $quoted;
}
return $result;
}
}

View File

@ -17,11 +17,19 @@ trait DbHelper
public function quoteBinary($binary)
{
if ($binary === '') {
return '';
}
if (is_array($binary)) {
return array_map([$this, 'quoteBinary'], $binary);
}
if ($this->isPgsql()) {
return new Expr("'\\x" . bin2hex($binary) . "'");
}
return $binary;
return new Expr('0x' . bin2hex($binary));
}
public function isPgsql()