Files
Testbed/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103411
T
2026-11-11 10:48:53 +00:00

279 lines
8.2 KiB
Plaintext

<?php
namespace App\Database\Db2;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
class Db2QueryGrammar extends Grammar
{
protected $selectComponents = [
'aggregate',
'columns',
'from',
'indexHint',
'joins',
'wheres',
'groups',
'havings',
'orders',
'offset',
'limit',
'lock',
];
private array $db2ColumnCache = [];
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
protected function compileAggregate($query, $aggregate)
{
$column = $this->columnize($aggregate['columns']);
if (is_array($query->distinct)) {
$column = 'distinct '.$this->columnize($query->distinct);
} elseif ($query->distinct && $column !== '*') {
$column = 'distinct '.$column;
}
$function = strtolower($aggregate['function']);
$expression = "{$function}({$column})";
// PDO_ODBC may return Db2 integer aggregates as binary data.
// Cast only the migration batch aggregate to VARCHAR.
if (
$function === 'max' &&
count($aggregate['columns']) === 1 &&
$aggregate['columns'][0] === 'batch' &&
$query->from === 'migrations'
) {
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
}
return 'select '.$expression.' as "aggregate"';
}
protected function compileLimit($query, $limit)
{
$limit = (int) $limit;
if ((int) ($query->offset ?? 0) > 0) {
return 'fetch next '.$limit.' rows only';
}
return 'fetch first '.$limit.' rows only';
}
protected function compileOffset($query, $offset)
{
return 'offset '.(int) $offset.' rows';
}
public function compileExists(
\Illuminate\Database\Query\Builder $query
) {
$select = $this->compileSelect($query);
return sprintf(
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
$select
);
}
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
public function compileSelect(\Illuminate\Database\Query\Builder $query)
{
if (
! is_string($query->from) ||
! preg_match(
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
$query->from
) ||
! empty($query->joins) ||
! empty($query->unions) ||
! empty($query->groups) ||
! empty($query->havings) ||
$query->aggregate !== null ||
$query->distinct
) {
return parent::compileSelect($query);
}
$table = $query->from;
if (! isset($this->db2ColumnCache[$table])) {
$this->db2ColumnCache[$table] = $this->connection
->getSchemaBuilder()
->getColumns($table);
}
$metadata = [];
foreach ($this->db2ColumnCache[$table] as $column) {
$metadata[strtolower($column['name'])] = $column;
}
$columns = $query->columns ?? ['*'];
if ($columns === ['*']) {
$columns = array_column(
$this->db2ColumnCache[$table],
'name'
);
}
$parsed = [];
$aliases = [];
// Validate the complete selection before modifying any SQL.
foreach ($columns as $column) {
if (
! is_string($column) ||
! preg_match(
'/^((?:"[^"]+"|[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);
}
$identifier = $matches[1];
$parts = explode('.', $identifier);
$name = trim(end($parts), '"');
$alias = isset($matches[2])
? trim($matches[2], '"')
: $name;
$info = $metadata[strtolower($name)] ?? null;
if ($info === null) {
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;
$hasNullIndicators = false;
foreach ($parsed as $entry) {
$info = $entry['info'];
$type = strtoupper($info['type_name']);
$nullable = (bool) ($info['nullable'] ?? false);
$selected = $entry['original'];
$wrapped = $this->wrap($entry['identifier']);
$alias = $this->wrap($entry['alias']);
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
$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 {
$expression = 'CASE WHEN '
. $wrapped
. " IS NULL THEN CAST('' AS VARCHAR(32))"
. ' ELSE CAST('
. $wrapped
. ' AS VARCHAR(32)) 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)
);
$hasNullIndicators = true;
$changed = true;
} else {
$ordinary[] = $selected;
}
}
if ($lobs !== [] && $ordinary !== []) {
$changed = true;
}
if (! $changed) {
return parent::compileSelect($query);
}
$modified = clone $query;
$modified->columns = array_merge($ordinary, $lobs);
$sql = parent::compileSelect($modified);
// Only mark SELECT statements that actually contain
// generated NULL indicator columns.
if ($hasNullIndicators) {
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
}
return $sql;
}
}