db2 driver updates

This commit is contained in:
Mark Gregory
2026-11-11 10:04:00 +00:00
parent 6a7f58cb98
commit 2e51121c5b
2 changed files with 166 additions and 78 deletions
+33 -14
View File
@@ -25,28 +25,47 @@ class Db2Connection extends Connection
$fetchUsing $fetchUsing
); );
foreach ($rows as $row) { foreach ($rows as &$row) {
if (! is_object($row)) { if (! is_object($row) && ! is_array($row)) {
continue; continue;
} }
foreach ($row as $key => $value) { $values = (array) $row;
if ($value === Db2QueryGrammar::NULL_TIMESTAMP_SENTINEL) { $result = [];
$row->{$key} = null; $previousColumn = null;
foreach ($values as $key => $value) {
if (
is_string($key) &&
preg_match('/^__db2_null_flag_[0-9]+$/i', $key)
) {
if ($previousColumn === null) {
throw new \RuntimeException(
'Db2 NULL indicator has no preceding column.'
);
}
if ((string) $value === '1') {
$result[$previousColumn] = null;
} elseif ((string) $value !== '0') {
throw new \RuntimeException(
'Unexpected Db2 NULL indicator value.'
);
}
$previousColumn = null;
continue; continue;
} }
if ( $result[$key] = $value;
in_array($key, [ $previousColumn = $key;
'two_factor_secret',
'two_factor_recovery_codes',
], true)
&& $value === Db2QueryGrammar::NULL_STRING_SENTINEL
) {
$row->{$key} = null;
}
} }
$row = is_object($row)
? (object) $result
: $result;
} }
unset($row);
return $rows; return $rows;
} }
+133 -64
View File
@@ -61,119 +61,188 @@ class Db2QueryGrammar extends Grammar
{ {
if ( if (
! is_string($query->from) || ! is_string($query->from) ||
! preg_match('/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/', $query->from) || ! preg_match(
! empty($query->joins) || ! empty($query->unions) || '/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
! empty($query->groups) || ! empty($query->havings) || $query->from
$query->aggregate !== null || $query->distinct ) ||
! empty($query->joins) ||
! empty($query->unions) ||
! empty($query->groups) ||
! empty($query->havings) ||
$query->aggregate !== null ||
$query->distinct
) { ) {
return parent::compileSelect($query); return parent::compileSelect($query);
} }
$table = $query->from; $table = $query->from;
if (! isset($this->db2ColumnCache[$table])) { if (! isset($this->db2ColumnCache[$table])) {
$this->db2ColumnCache[$table] = $this->connection $this->db2ColumnCache[$table] = $this->connection
->getSchemaBuilder()->getColumns($table); ->getSchemaBuilder()
->getColumns($table);
} }
$metadata = []; $metadata = [];
foreach ($this->db2ColumnCache[$table] as $column) { foreach ($this->db2ColumnCache[$table] as $column) {
$metadata[strtolower($column['name'])] = $column; $metadata[strtolower($column['name'])] = $column;
} }
$columns = $query->columns ?? ['*']; $columns = $query->columns ?? ['*'];
if ($columns === ['*']) { if ($columns === ['*']) {
$columns = array_column($this->db2ColumnCache[$table], 'name'); $columns = array_column(
$this->db2ColumnCache[$table],
'name'
);
} }
$ordinary = []; $parsed = [];
$lobs = []; $aliases = [];
$changed = false;
// Validate the complete selection before modifying any SQL.
foreach ($columns as $column) { foreach ($columns as $column) {
// Expressions and partial wildcards cannot be safely rearranged. if (
if (! is_string($column) || ! preg_match( ! is_string($column) ||
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i', ! preg_match(
$column, $matches '/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
)) { $column,
$matches
)
) {
return parent::compileSelect($query); return parent::compileSelect($query);
} }
$identifier = $matches[1]; $identifier = $matches[1];
$parts = explode('.', $identifier); $parts = explode('.', $identifier);
$name = trim(end($parts), '"'); $name = trim(end($parts), '"');
$alias = isset($matches[2])
? trim($matches[2], '"')
: $name;
$info = $metadata[strtolower($name)] ?? null; $info = $metadata[strtolower($name)] ?? null;
if ($info === null) { if ($info === null) {
return parent::compileSelect($query); return parent::compileSelect($query);
} }
// Reserved indicator aliases must never be user columns.
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
return parent::compileSelect($query);
}
// Duplicate output names cannot be mapped unambiguously.
$aliasKey = strtolower($alias);
if (isset($aliases[$aliasKey])) {
return parent::compileSelect($query);
}
$aliases[$aliasKey] = true;
$parsed[] = [
'original' => $column,
'identifier' => $identifier,
'alias' => $alias,
'info' => $info,
];
}
$ordinary = [];
$lobs = [];
$changed = false;
$indicatorIndex = 0;
foreach ($parsed as $entry) {
$info = $entry['info'];
$type = strtoupper($info['type_name']); $type = strtoupper($info['type_name']);
$selected = $column; $nullable = (bool) ($info['nullable'] ?? false);
// Work around PDO_ODBC attempting a 4 GiB allocation $selected = $entry['original'];
// when fetching NULL Fortify VARCHAR(4096) columns. $wrapped = $this->wrap($entry['identifier']);
if ( $alias = $this->wrap($entry['alias']);
($info['nullable'] ?? false)
&& $type === 'VARCHAR'
&& in_array($name, [
'two_factor_secret',
'two_factor_recovery_codes',
], true)
) {
$alias = isset($matches[2])
? trim($matches[2], '"')
: $name;
$wrapped = $this->wrap($identifier);
$selected = new Expression(
'COALESCE('
. $wrapped
. ", CAST('__DB2_NULL_STRING__' AS VARCHAR(4096))) AS "
. $this->wrap($alias)
);
$changed = true;
}
if (($info['nullable'] ?? false) && in_array($type, ['TIMESTAMP', 'DATE', 'TIME'], true)) {
// Never return a SQL NULL date/time to the broken PDO_ODBC
// retrieval path. Use a non-NULL character expression instead.
$format = match ($type) {
'DATE' => 'YYYY-MM-DD',
'TIME' => 'HH24:MI:SS',
default => 'YYYY-MM-DD HH24:MI:SS.FF6',
};
$alias = isset($matches[2]) ? trim($matches[2], '"') : $name;
$wrapped = $this->wrap($identifier);
$selected = new Expression(
'CASE WHEN '.$wrapped.' IS NULL THEN '.
"'".self::NULL_TIMESTAMP_SENTINEL."'".
' ELSE VARCHAR_FORMAT('.$wrapped.", '".$format."') END AS ".
$this->wrap($alias)
);
$changed = true;
}
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) { if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
$lobs[] = $selected; $lobs[] = $selected;
continue;
}
if (
$nullable &&
in_array(
$type,
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
true
)
) {
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
$length = 1;
if (preg_match(
'/\((\d+)\)/',
$info['type'] ?? '',
$lengthMatch
)) {
$length = max(1, (int) $lengthMatch[1]);
}
$expression = 'COALESCE('
. $wrapped
. ", CAST('' AS VARCHAR({$length})))";
} else {
$format = match ($type) {
'DATE' => 'YYYY-MM-DD',
'TIME' => 'HH24:MI:SS',
default => 'YYYY-MM-DD HH24:MI:SS.FF6',
};
$expression = 'CASE WHEN '
. $wrapped
. " IS NULL THEN CAST('' AS VARCHAR(32))"
. ' ELSE VARCHAR_FORMAT('
. $wrapped
. ", '{$format}') END";
}
$ordinary[] = new Expression(
$expression . ' AS ' . $alias
);
// Character indicators avoid the PDO_ODBC numeric
// aggregate/binary conversion issue.
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
// Ensure a generated alias cannot collide with any
// requested output column.
while (isset($aliases[strtolower($flagAlias)])) {
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
}
$ordinary[] = new Expression(
'CASE WHEN '
. $wrapped
. " IS NULL THEN '1' ELSE '0' END AS "
. $this->wrap($flagAlias)
);
$changed = true;
} else { } else {
$ordinary[] = $selected; $ordinary[] = $selected;
} }
} }
if ($lobs !== [] && $ordinary !== [] && $columns !== array_merge( if ($lobs !== [] && $ordinary !== []) {
array_filter($ordinary, 'is_string'),
array_filter($lobs, 'is_string')
)) {
$changed = true; $changed = true;
} }
if (! $changed && $lobs === []) { if (! $changed) {
return parent::compileSelect($query); return parent::compileSelect($query);
} }
$modified = clone $query; $modified = clone $query;
$modified->columns = array_merge($ordinary, $lobs); $modified->columns = array_merge($ordinary, $lobs);
return parent::compileSelect($modified); return parent::compileSelect($modified);
} }
} }