497 lines
14 KiB
PHP
497 lines
14 KiB
PHP
<?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__';
|
|
/**
|
|
* Compile a Db2 MERGE statement for Laravel upserts.
|
|
*/
|
|
public function compileUpsert(
|
|
Builder $query,
|
|
array $values,
|
|
array $uniqueBy,
|
|
array $update
|
|
) {
|
|
$columns = $this->db2MergeColumns($values);
|
|
|
|
foreach ($uniqueBy as $column) {
|
|
if (! in_array($column, $columns, true)) {
|
|
throw new \InvalidArgumentException(
|
|
"Upsert key is missing from inserted values: {$column}"
|
|
);
|
|
}
|
|
}
|
|
|
|
$source = $this->db2MergeSource($values, $columns);
|
|
|
|
$matches = [];
|
|
|
|
foreach ($uniqueBy as $column) {
|
|
$wrapped = $this->wrap($column);
|
|
|
|
$matches[] = "target.{$wrapped} = source.{$wrapped}";
|
|
}
|
|
|
|
$updates = [];
|
|
|
|
foreach ($update as $key => $value) {
|
|
if (is_int($key)) {
|
|
if (! in_array($value, $columns, true)) {
|
|
throw new \InvalidArgumentException(
|
|
"Unknown upsert update column: {$value}"
|
|
);
|
|
}
|
|
|
|
$wrapped = $this->wrap($value);
|
|
|
|
$updates[] = "target.{$wrapped} = source.{$wrapped}";
|
|
} else {
|
|
$updates[] = "target."
|
|
. $this->wrap($key)
|
|
. " = "
|
|
. $this->parameter($value);
|
|
}
|
|
}
|
|
|
|
$insertColumns = $this->columnize($columns);
|
|
|
|
$insertValues = implode(', ', array_map(
|
|
fn ($column) => 'source.' . $this->wrap($column),
|
|
$columns
|
|
));
|
|
|
|
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
. "USING ({$source}) AS source "
|
|
. "ON (" . implode(' AND ', $matches) . ") ";
|
|
|
|
if ($updates !== []) {
|
|
$sql .= "WHEN MATCHED THEN UPDATE SET "
|
|
. implode(', ', $updates) . " ";
|
|
}
|
|
|
|
return $sql
|
|
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
. "VALUES ({$insertValues})";
|
|
}
|
|
|
|
/**
|
|
* Insert rows without replacing existing rows.
|
|
*
|
|
* Db2 MERGE ignores rows that match the selected key.
|
|
*/
|
|
public function compileInsertOrIgnore(
|
|
Builder $query,
|
|
array $values
|
|
) {
|
|
$columns = $this->db2MergeColumns($values);
|
|
$source = $this->db2MergeSource($values, $columns);
|
|
|
|
$indexes = $this->connection
|
|
->getSchemaBuilder()
|
|
->getIndexes($query->from);
|
|
|
|
$uniqueConditions = [];
|
|
|
|
foreach ($indexes as $index) {
|
|
if (! ($index['unique'] ?? false)) {
|
|
continue;
|
|
}
|
|
|
|
$indexColumns = $index['columns'] ?? [];
|
|
|
|
if ($indexColumns === []) {
|
|
continue;
|
|
}
|
|
|
|
// A unique key can only be compared if every
|
|
// participating column exists in the source.
|
|
$conditions = [];
|
|
|
|
foreach ($indexColumns as $column) {
|
|
$matchedColumn = null;
|
|
|
|
foreach ($columns as $candidate) {
|
|
if (strcasecmp($candidate, $column) === 0) {
|
|
$matchedColumn = $candidate;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if ($matchedColumn === null) {
|
|
$conditions = [];
|
|
break;
|
|
}
|
|
|
|
$wrapped = $this->wrap($matchedColumn);
|
|
|
|
$conditions[] = "target.{$wrapped} = source.{$wrapped}";
|
|
}
|
|
|
|
if ($conditions !== []) {
|
|
$uniqueConditions[] = '('
|
|
. implode(' AND ', $conditions)
|
|
. ')';
|
|
}
|
|
}
|
|
|
|
if ($uniqueConditions === []) {
|
|
throw new \RuntimeException(
|
|
'Db2 insertOrIgnore requires an applicable unique index.'
|
|
);
|
|
}
|
|
|
|
$insertColumns = $this->columnize($columns);
|
|
|
|
$insertValues = implode(', ', array_map(
|
|
fn ($column) => 'source.' . $this->wrap($column),
|
|
$columns
|
|
));
|
|
|
|
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
|
. "USING ({$source}) AS source "
|
|
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
|
|
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
|
|
. "VALUES ({$insertValues})";
|
|
}
|
|
|
|
/**
|
|
* Validate the column layout of a multi-row MERGE.
|
|
*/
|
|
private function db2MergeColumns(array $values): array
|
|
{
|
|
if ($values === []) {
|
|
throw new \InvalidArgumentException(
|
|
'MERGE requires at least one row.'
|
|
);
|
|
}
|
|
|
|
$columns = array_keys(reset($values));
|
|
|
|
foreach ($values as $row) {
|
|
if (array_keys($row) !== $columns) {
|
|
throw new \InvalidArgumentException(
|
|
'All MERGE rows must contain the same columns.'
|
|
);
|
|
}
|
|
}
|
|
|
|
return $columns;
|
|
}
|
|
|
|
/**
|
|
* Build a parameterized Db2 MERGE source.
|
|
*/
|
|
private function db2MergeSource(
|
|
array $values,
|
|
array $columns
|
|
): string {
|
|
$selects = [];
|
|
|
|
foreach ($values as $row) {
|
|
$parts = [];
|
|
|
|
foreach ($columns as $column) {
|
|
$parts[] = $this->parameter($row[$column])
|
|
. ' AS '
|
|
. $this->wrap($column);
|
|
}
|
|
|
|
$selects[] = 'SELECT '
|
|
. implode(', ', $parts)
|
|
. ' FROM SYSIBM.SYSDUMMY1';
|
|
}
|
|
|
|
return implode(' UNION ALL ', $selects);
|
|
}
|
|
|
|
/**
|
|
* Compile a Db2 LUW savepoint statement.
|
|
*/
|
|
public function compileSavepoint($name)
|
|
{
|
|
return 'SAVEPOINT ' . $name
|
|
. ' ON ROLLBACK RETAIN CURSORS';
|
|
}
|
|
|
|
/**
|
|
* Compile a Db2 LUW rollback-to-savepoint statement.
|
|
*/
|
|
public function compileSavepointRollBack($name)
|
|
{
|
|
return 'ROLLBACK TO SAVEPOINT ' . $name;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|