db2 driver updates
This commit is contained in:
@@ -25,6 +25,15 @@ class Db2Connection extends Connection
|
||||
$fetchUsing
|
||||
);
|
||||
|
||||
// Never interpret ordinary raw-query columns as
|
||||
// internal NULL indicators.
|
||||
if (
|
||||
! is_string($query) ||
|
||||
! str_contains($query, '/* DB2_NULL_FLAGS_V1 */')
|
||||
) {
|
||||
return $rows;
|
||||
}
|
||||
|
||||
foreach ($rows as &$row) {
|
||||
if (! is_object($row) && ! is_array($row)) {
|
||||
continue;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Db2;
|
||||
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Database\Query\Grammars\Grammar as QueryGrammar;
|
||||
use App\Database\Db2\Db2Processor;
|
||||
class Db2Connection extends Connection
|
||||
{
|
||||
|
||||
/**
|
||||
* Restore SQL NULL values from Db2 workaround expressions
|
||||
* before Eloquent processes the results.
|
||||
*/
|
||||
public function select(
|
||||
$query,
|
||||
$bindings = [],
|
||||
$useReadPdo = true,
|
||||
array $fetchUsing = []
|
||||
) {
|
||||
$rows = parent::select(
|
||||
$query,
|
||||
$bindings,
|
||||
$useReadPdo,
|
||||
$fetchUsing
|
||||
);
|
||||
|
||||
foreach ($rows as &$row) {
|
||||
if (! is_object($row) && ! is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$values = (array) $row;
|
||||
$result = [];
|
||||
$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;
|
||||
}
|
||||
|
||||
$result[$key] = $value;
|
||||
$previousColumn = $key;
|
||||
}
|
||||
|
||||
$row = is_object($row)
|
||||
? (object) $result
|
||||
: $result;
|
||||
}
|
||||
unset($row);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
protected function getDefaultQueryGrammar()
|
||||
{
|
||||
return new Db2QueryGrammar($this);
|
||||
}
|
||||
|
||||
protected function getDefaultSchemaGrammar()
|
||||
{
|
||||
return new Db2SchemaGrammar($this);
|
||||
}
|
||||
|
||||
public function getSchemaBuilder()
|
||||
{
|
||||
if (is_null($this->schemaGrammar)) {
|
||||
$this->useDefaultSchemaGrammar();
|
||||
}
|
||||
|
||||
return new Db2SchemaBuilder($this);
|
||||
}
|
||||
|
||||
protected function getDefaultPostProcessor()
|
||||
{
|
||||
return new Db2Processor;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -8,8 +8,241 @@ 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']);
|
||||
@@ -35,12 +268,23 @@ class Db2QueryGrammar extends Grammar
|
||||
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
|
||||
}
|
||||
|
||||
return 'select '.$expression.' as aggregate';
|
||||
return 'select '.$expression.' as "aggregate"';
|
||||
}
|
||||
|
||||
protected function compileLimit($query, $limit)
|
||||
{
|
||||
return 'fetch first '.(int) $limit.' rows only';
|
||||
$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(
|
||||
@@ -153,6 +397,7 @@ class Db2QueryGrammar extends Grammar
|
||||
$lobs = [];
|
||||
$changed = false;
|
||||
$indicatorIndex = 0;
|
||||
$hasNullIndicators = false;
|
||||
|
||||
foreach ($parsed as $entry) {
|
||||
$info = $entry['info'];
|
||||
@@ -191,18 +436,12 @@ class Db2QueryGrammar extends Grammar
|
||||
. $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('
|
||||
. ' ELSE CAST('
|
||||
. $wrapped
|
||||
. ", '{$format}') END";
|
||||
. ' AS VARCHAR(32)) END';
|
||||
}
|
||||
|
||||
$ordinary[] = new Expression(
|
||||
@@ -226,6 +465,7 @@ class Db2QueryGrammar extends Grammar
|
||||
. $this->wrap($flagAlias)
|
||||
);
|
||||
|
||||
$hasNullIndicators = true;
|
||||
$changed = true;
|
||||
} else {
|
||||
$ordinary[] = $selected;
|
||||
@@ -243,6 +483,14 @@ class Db2QueryGrammar extends Grammar
|
||||
$modified = clone $query;
|
||||
$modified->columns = array_merge($ordinary, $lobs);
|
||||
|
||||
return parent::compileSelect($modified);
|
||||
$sql = parent::compileSelect($modified);
|
||||
|
||||
// Only mark SELECT statements that actually contain
|
||||
// generated NULL indicator columns.
|
||||
if ($hasNullIndicators) {
|
||||
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
|
||||
}
|
||||
|
||||
return $sql;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
<?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
|
||||
{
|
||||
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)
|
||||
{
|
||||
return 'fetch first '.(int) $limit.' rows only';
|
||||
}
|
||||
|
||||
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 {
|
||||
$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)
|
||||
);
|
||||
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
<?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
|
||||
{
|
||||
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)
|
||||
{
|
||||
return 'fetch first '.(int) $limit.' rows only';
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
<?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);
|
||||
|
||||
$insertColumns = $this->columnize($columns);
|
||||
|
||||
$insertValues = implode(', ', array_map(
|
||||
fn ($column) => 'source.' . $this->wrap($column),
|
||||
$columns
|
||||
));
|
||||
|
||||
// Match all supplied columns. A later stage will add
|
||||
// catalog-aware matching for unique constraints.
|
||||
$matches = [];
|
||||
|
||||
foreach ($columns as $column) {
|
||||
$wrapped = $this->wrap($column);
|
||||
|
||||
$matches[] = "target.{$wrapped} = source.{$wrapped}";
|
||||
}
|
||||
|
||||
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
|
||||
. "USING ({$source}) AS source "
|
||||
. "ON (" . implode(' AND ', $matches) . ") "
|
||||
. "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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
<?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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
<?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
|
||||
{
|
||||
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)
|
||||
{
|
||||
return 'fetch first '.(int) $limit.' rows only';
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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 {
|
||||
$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 {
|
||||
$ordinary[] = $selected;
|
||||
}
|
||||
}
|
||||
|
||||
if ($lobs !== [] && $ordinary !== []) {
|
||||
$changed = true;
|
||||
}
|
||||
|
||||
if (! $changed) {
|
||||
return parent::compileSelect($query);
|
||||
}
|
||||
|
||||
$modified = clone $query;
|
||||
$modified->columns = array_merge($ordinary, $lobs);
|
||||
|
||||
return parent::compileSelect($modified);
|
||||
}
|
||||
}
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Foundation\Configuration\Exceptions;
|
||||
use Illuminate\Foundation\Configuration\Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
return Application::configure(basePath: dirname(__DIR__))
|
||||
->withRouting(
|
||||
web: __DIR__.'/../routes/web.php',
|
||||
commands: __DIR__.'/../routes/console.php',
|
||||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
//
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions): void {
|
||||
$exceptions->shouldRenderJsonWhen(
|
||||
fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
|
||||
);
|
||||
})->create();
|
||||
Executable → Regular
+2
-1
@@ -18,7 +18,8 @@
|
||||
</include>
|
||||
</source>
|
||||
<php>
|
||||
<env name="APP_ENV" value="testing"/>
|
||||
<env name="APP_ENV" value="testing" force="true"/>
|
||||
<env name="APP_URL" value="http://localhost"/>
|
||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
||||
<env name="BCRYPT_ROUNDS" value="4"/>
|
||||
<env name="BROADCAST_CONNECTION" value="null"/>
|
||||
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true"
|
||||
>
|
||||
<testsuites>
|
||||
<testsuite name="Unit">
|
||||
<directory>tests/Unit</directory>
|
||||
</testsuite>
|
||||
<testsuite name="Feature">
|
||||
<directory>tests/Feature</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<source>
|
||||
<include>
|
||||
<directory>app</directory>
|
||||
</include>
|
||||
</source>
|
||||
<php>
|
||||
<env name="APP_ENV" value="testing"/>
|
||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
||||
<env name="BCRYPT_ROUNDS" value="4"/>
|
||||
<env name="BROADCAST_CONNECTION" value="null"/>
|
||||
<env name="CACHE_STORE" value="array"/>
|
||||
<env name="DB_CONNECTION" value="sqlite"/>
|
||||
<env name="DB_DATABASE" value=":memory:"/>
|
||||
<env name="DB_URL" value=""/>
|
||||
<env name="MAIL_MAILER" value="array"/>
|
||||
<env name="QUEUE_CONNECTION" value="sync"/>
|
||||
<env name="SESSION_DRIVER" value="array"/>
|
||||
<env name="PULSE_ENABLED" value="false"/>
|
||||
<env name="TELESCOPE_ENABLED" value="false"/>
|
||||
<env name="NIGHTWATCH_ENABLED" value="false"/>
|
||||
</php>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true"
|
||||
>
|
||||
<testsuites>
|
||||
<testsuite name="Unit">
|
||||
<directory>tests/Unit</directory>
|
||||
</testsuite>
|
||||
<testsuite name="Feature">
|
||||
<directory>tests/Feature</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<source>
|
||||
<include>
|
||||
<directory>app</directory>
|
||||
</include>
|
||||
</source>
|
||||
<php>
|
||||
<env name="APP_ENV" value="testing"/>
|
||||
<env name="APP_URL" value="http://localhost"/>
|
||||
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
|
||||
<env name="BCRYPT_ROUNDS" value="4"/>
|
||||
<env name="BROADCAST_CONNECTION" value="null"/>
|
||||
<env name="CACHE_STORE" value="array"/>
|
||||
<env name="DB_CONNECTION" value="sqlite"/>
|
||||
<env name="DB_DATABASE" value=":memory:"/>
|
||||
<env name="DB_URL" value=""/>
|
||||
<env name="MAIL_MAILER" value="array"/>
|
||||
<env name="QUEUE_CONNECTION" value="sync"/>
|
||||
<env name="SESSION_DRIVER" value="array"/>
|
||||
<env name="PULSE_ENABLED" value="false"/>
|
||||
<env name="TELESCOPE_ENABLED" value="false"/>
|
||||
<env name="NIGHTWATCH_ENABLED" value="false"/>
|
||||
</php>
|
||||
</phpunit>
|
||||
Executable → Regular
+3
-3
@@ -20,7 +20,7 @@ test('reset password link can be requested', function () {
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('password.request'), ['email' => $user->email]);
|
||||
$this->post(route('password.email'), ['email' => $user->email]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class);
|
||||
});
|
||||
@@ -30,7 +30,7 @@ test('reset password screen can be rendered', function () {
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('password.request'), ['email' => $user->email]);
|
||||
$this->post(route('password.email'), ['email' => $user->email]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class, function ($notification) {
|
||||
$response = $this->get(route('password.reset', $notification->token));
|
||||
@@ -46,7 +46,7 @@ test('password can be reset with valid token', function () {
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('password.request'), ['email' => $user->email]);
|
||||
$this->post(route('password.email'), ['email' => $user->email]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
|
||||
$response = $this->post(route('password.update'), [
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Notifications\ResetPassword;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Laravel\Fortify\Features;
|
||||
|
||||
beforeEach(function () {
|
||||
$this->skipUnlessFortifyHas(Features::resetPasswords());
|
||||
});
|
||||
|
||||
test('reset password link screen can be rendered', function () {
|
||||
$response = $this->get(route('password.request'));
|
||||
|
||||
$response->assertOk();
|
||||
});
|
||||
|
||||
test('reset password link can be requested', function () {
|
||||
Notification::fake();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('password.request'), ['email' => $user->email]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class);
|
||||
});
|
||||
|
||||
test('reset password screen can be rendered', function () {
|
||||
Notification::fake();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('password.request'), ['email' => $user->email]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class, function ($notification) {
|
||||
$response = $this->get(route('password.reset', $notification->token));
|
||||
|
||||
$response->assertOk();
|
||||
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
test('password can be reset with valid token', function () {
|
||||
Notification::fake();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('password.request'), ['email' => $user->email]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
|
||||
$response = $this->post(route('password.update'), [
|
||||
'token' => $notification->token,
|
||||
'email' => $user->email,
|
||||
'password' => 'password',
|
||||
'password_confirmation' => 'password',
|
||||
]);
|
||||
|
||||
$response
|
||||
->assertSessionHasNoErrors()
|
||||
->assertRedirect(route('login', absolute: false));
|
||||
|
||||
return true;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCase;
|
||||
|
||||
abstract class Db2TestCase extends TestCase
|
||||
{
|
||||
protected function db()
|
||||
{
|
||||
return DB::connection('db2_local');
|
||||
}
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
if (! extension_loaded('pdo_odbc')) {
|
||||
$this->markTestSkipped('PDO_ODBC extension unavailable.');
|
||||
}
|
||||
|
||||
if (! config('database.connections.db2_local')) {
|
||||
$this->markTestSkipped('db2_local is not configured.');
|
||||
}
|
||||
|
||||
try {
|
||||
$this->db()->select(
|
||||
'SELECT 1 AS "health" FROM SYSIBM.SYSDUMMY1'
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
$this->markTestSkipped(
|
||||
'Db2 connection unavailable: ' . $e->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class NullHandlingTest extends Db2TestCase
|
||||
{
|
||||
private string $fixtureTable = '';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
// Each test owns a unique permanent table.
|
||||
// Db2 catalog metadata can discover its columns.
|
||||
$this->fixtureTable = 'DB2_TEST.DB2T_' .
|
||||
strtoupper(bin2hex(random_bytes(6)));
|
||||
|
||||
$db = $this->db();
|
||||
|
||||
$db->statement("
|
||||
CREATE TABLE {$this->fixtureTable} (
|
||||
ID INTEGER NOT NULL PRIMARY KEY,
|
||||
NULLABLE_TEXT VARCHAR(100),
|
||||
NULLABLE_DATE DATE,
|
||||
NULLABLE_TIME TIME,
|
||||
NULLABLE_TIMESTAMP TIMESTAMP
|
||||
)
|
||||
");
|
||||
|
||||
$db->statement("
|
||||
INSERT INTO {$this->fixtureTable}
|
||||
(ID, NULLABLE_TEXT, NULLABLE_DATE,
|
||||
NULLABLE_TIME, NULLABLE_TIMESTAMP)
|
||||
VALUES (1, NULL, NULL, NULL, NULL)
|
||||
");
|
||||
|
||||
$db->statement("
|
||||
INSERT INTO {$this->fixtureTable}
|
||||
(ID, NULLABLE_TEXT, NULLABLE_DATE,
|
||||
NULLABLE_TIME, NULLABLE_TIMESTAMP)
|
||||
VALUES (
|
||||
2,
|
||||
'',
|
||||
DATE('2026-11-11'),
|
||||
TIME('10:15:30'),
|
||||
TIMESTAMP('2026-11-11 10:15:30')
|
||||
)
|
||||
");
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
try {
|
||||
if ($this->fixtureTable !== '') {
|
||||
$this->db()->statement(
|
||||
"DROP TABLE {$this->fixtureTable}"
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_null_values_are_restored(): void
|
||||
{
|
||||
$row = $this->db()->table($this->fixtureTable)
|
||||
->where('ID', 1)
|
||||
->first();
|
||||
|
||||
$this->assertNull($row->NULLABLE_TEXT);
|
||||
$this->assertNull($row->NULLABLE_DATE);
|
||||
$this->assertNull($row->NULLABLE_TIME);
|
||||
$this->assertNull($row->NULLABLE_TIMESTAMP);
|
||||
}
|
||||
|
||||
public function test_empty_string_is_not_converted_to_null(): void
|
||||
{
|
||||
$row = $this->db()->table($this->fixtureTable)
|
||||
->where('ID', 2)
|
||||
->first();
|
||||
|
||||
$this->assertSame('', $row->NULLABLE_TEXT);
|
||||
}
|
||||
|
||||
public function test_non_null_temporal_values_survive(): void
|
||||
{
|
||||
$row = $this->db()->table($this->fixtureTable)
|
||||
->where('ID', 2)
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($row->NULLABLE_DATE);
|
||||
$this->assertNotNull($row->NULLABLE_TIME);
|
||||
$this->assertNotNull($row->NULLABLE_TIMESTAMP);
|
||||
}
|
||||
|
||||
public function test_generated_indicators_are_hidden(): void
|
||||
{
|
||||
$row = $this->db()->table($this->fixtureTable)
|
||||
->where('ID', 1)
|
||||
->first();
|
||||
|
||||
foreach (array_keys((array) $row) as $column) {
|
||||
$this->assertDoesNotMatchRegularExpression(
|
||||
'/^__db2_null_flag_\d+$/i',
|
||||
$column
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_nullable_aliases_are_preserved(): void
|
||||
{
|
||||
$row = $this->db()->table($this->fixtureTable)
|
||||
->select('NULLABLE_TEXT as aliased_text')
|
||||
->where('ID', 1)
|
||||
->first();
|
||||
|
||||
$this->assertTrue(
|
||||
property_exists($row, 'aliased_text')
|
||||
);
|
||||
|
||||
$this->assertNull($row->aliased_text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class NullHandlingTest extends Db2TestCase
|
||||
{
|
||||
private const TABLE = 'DB2_LARAVEL_TEST_NULLS';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$db = $this->db();
|
||||
|
||||
$db->statement('
|
||||
DECLARE GLOBAL TEMPORARY TABLE
|
||||
SESSION.DB2_LARAVEL_TEST_NULLS (
|
||||
ID INTEGER NOT NULL,
|
||||
NULLABLE_TEXT VARCHAR(4096),
|
||||
NULLABLE_DATE DATE,
|
||||
NULLABLE_TIME TIME,
|
||||
NULLABLE_TIMESTAMP TIMESTAMP
|
||||
)
|
||||
ON COMMIT PRESERVE ROWS
|
||||
NOT LOGGED
|
||||
');
|
||||
|
||||
$db->statement('
|
||||
INSERT INTO SESSION.DB2_LARAVEL_TEST_NULLS
|
||||
(ID, NULLABLE_TEXT, NULLABLE_DATE,
|
||||
NULLABLE_TIME, NULLABLE_TIMESTAMP)
|
||||
VALUES (1, NULL, NULL, NULL, NULL)
|
||||
');
|
||||
|
||||
$db->statement("
|
||||
INSERT INTO SESSION.DB2_LARAVEL_TEST_NULLS
|
||||
(ID, NULLABLE_TEXT, NULLABLE_DATE,
|
||||
NULLABLE_TIME, NULLABLE_TIMESTAMP)
|
||||
VALUES (
|
||||
2,
|
||||
'',
|
||||
DATE('2026-11-11'),
|
||||
TIME('10:15:30'),
|
||||
TIMESTAMP('2026-11-11 10:15:30')
|
||||
)
|
||||
");
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
try {
|
||||
$this->db()->statement(
|
||||
'DROP TABLE SESSION.DB2_LARAVEL_TEST_NULLS'
|
||||
);
|
||||
} finally {
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_null_values_are_restored(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->where('ID', 1)
|
||||
->first();
|
||||
|
||||
$this->assertNull($row->NULLABLE_TEXT);
|
||||
$this->assertNull($row->NULLABLE_DATE);
|
||||
$this->assertNull($row->NULLABLE_TIME);
|
||||
$this->assertNull($row->NULLABLE_TIMESTAMP);
|
||||
}
|
||||
|
||||
public function test_empty_string_is_not_converted_to_null(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->where('ID', 2)
|
||||
->first();
|
||||
|
||||
$this->assertSame('', $row->NULLABLE_TEXT);
|
||||
}
|
||||
|
||||
public function test_non_null_temporal_values_survive(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->where('ID', 2)
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($row->NULLABLE_DATE);
|
||||
$this->assertNotNull($row->NULLABLE_TIME);
|
||||
$this->assertNotNull($row->NULLABLE_TIMESTAMP);
|
||||
}
|
||||
|
||||
public function test_generated_indicators_are_hidden(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->where('ID', 1)
|
||||
->first();
|
||||
|
||||
foreach (array_keys((array) $row) as $column) {
|
||||
$this->assertDoesNotMatchRegularExpression(
|
||||
'/^__db2_null_flag_\d+$/i',
|
||||
$column
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_nullable_aliases_are_preserved(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->select('NULLABLE_TEXT as aliased_text')
|
||||
->where('ID', 1)
|
||||
->first();
|
||||
|
||||
$this->assertTrue(
|
||||
property_exists($row, 'aliased_text')
|
||||
);
|
||||
|
||||
$this->assertNull($row->aliased_text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class NullHandlingTest extends Db2TestCase
|
||||
{
|
||||
private const TABLE = 'DB2_LARAVEL_TEST_NULLS';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$db = $this->db();
|
||||
|
||||
$db->statement('
|
||||
DECLARE GLOBAL TEMPORARY TABLE
|
||||
SESSION.DB2_LARAVEL_TEST_NULLS (
|
||||
ID INTEGER NOT NULL,
|
||||
NULLABLE_TEXT VARCHAR(100),
|
||||
NULLABLE_DATE DATE,
|
||||
NULLABLE_TIME TIME,
|
||||
NULLABLE_TIMESTAMP TIMESTAMP
|
||||
)
|
||||
ON COMMIT PRESERVE ROWS
|
||||
NOT LOGGED
|
||||
');
|
||||
|
||||
$db->statement('
|
||||
INSERT INTO SESSION.DB2_LARAVEL_TEST_NULLS
|
||||
(ID, NULLABLE_TEXT, NULLABLE_DATE,
|
||||
NULLABLE_TIME, NULLABLE_TIMESTAMP)
|
||||
VALUES (1, NULL, NULL, NULL, NULL)
|
||||
');
|
||||
|
||||
$db->statement("
|
||||
INSERT INTO SESSION.DB2_LARAVEL_TEST_NULLS
|
||||
(ID, NULLABLE_TEXT, NULLABLE_DATE,
|
||||
NULLABLE_TIME, NULLABLE_TIMESTAMP)
|
||||
VALUES (
|
||||
2,
|
||||
'',
|
||||
DATE('2026-11-11'),
|
||||
TIME('10:15:30'),
|
||||
TIMESTAMP('2026-11-11 10:15:30')
|
||||
)
|
||||
");
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
try {
|
||||
$this->db()->statement(
|
||||
'DROP TABLE SESSION.DB2_LARAVEL_TEST_NULLS'
|
||||
);
|
||||
} finally {
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_null_values_are_restored(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->where('ID', 1)
|
||||
->first();
|
||||
|
||||
$this->assertNull($row->NULLABLE_TEXT);
|
||||
$this->assertNull($row->NULLABLE_DATE);
|
||||
$this->assertNull($row->NULLABLE_TIME);
|
||||
$this->assertNull($row->NULLABLE_TIMESTAMP);
|
||||
}
|
||||
|
||||
public function test_empty_string_is_not_converted_to_null(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->where('ID', 2)
|
||||
->first();
|
||||
|
||||
$this->assertSame('', $row->NULLABLE_TEXT);
|
||||
}
|
||||
|
||||
public function test_non_null_temporal_values_survive(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->where('ID', 2)
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($row->NULLABLE_DATE);
|
||||
$this->assertNotNull($row->NULLABLE_TIME);
|
||||
$this->assertNotNull($row->NULLABLE_TIMESTAMP);
|
||||
}
|
||||
|
||||
public function test_generated_indicators_are_hidden(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->where('ID', 1)
|
||||
->first();
|
||||
|
||||
foreach (array_keys((array) $row) as $column) {
|
||||
$this->assertDoesNotMatchRegularExpression(
|
||||
'/^__db2_null_flag_\d+$/i',
|
||||
$column
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_nullable_aliases_are_preserved(): void
|
||||
{
|
||||
$row = $this->db()->table('SESSION.' . self::TABLE)
|
||||
->select('NULLABLE_TEXT as aliased_text')
|
||||
->where('ID', 1)
|
||||
->first();
|
||||
|
||||
$this->assertTrue(
|
||||
property_exists($row, 'aliased_text')
|
||||
);
|
||||
|
||||
$this->assertNull($row->aliased_text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
class PaginationIdentityTest extends Db2TestCase
|
||||
{
|
||||
private string $tableName = '';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->tableName = 'DB2_TEST.DB2T_' .
|
||||
strtoupper(bin2hex(random_bytes(6)));
|
||||
|
||||
$this->db()->statement("
|
||||
CREATE TABLE {$this->tableName} (
|
||||
ID INTEGER GENERATED ALWAYS AS IDENTITY
|
||||
(START WITH 1 INCREMENT BY 1),
|
||||
NAME VARCHAR(100) NOT NULL,
|
||||
PRIMARY KEY (ID)
|
||||
)
|
||||
");
|
||||
|
||||
foreach (range(1, 20) as $number) {
|
||||
$this->db()->table($this->tableName)->insert([
|
||||
'NAME' => sprintf('Item %02d', $number),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
try {
|
||||
if ($this->tableName !== '') {
|
||||
$this->db()->statement(
|
||||
"DROP TABLE {$this->tableName}"
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_limit_returns_requested_rows(): void
|
||||
{
|
||||
$rows = $this->db()->table($this->tableName)
|
||||
->orderBy('ID')
|
||||
->limit(5)
|
||||
->get();
|
||||
|
||||
$this->assertCount(5, $rows);
|
||||
$this->assertSame('Item 01', $rows[0]->NAME);
|
||||
$this->assertSame('Item 05', $rows[4]->NAME);
|
||||
}
|
||||
|
||||
public function test_offset_skips_correct_rows(): void
|
||||
{
|
||||
$rows = $this->db()->table($this->tableName)
|
||||
->orderBy('ID')
|
||||
->offset(10)
|
||||
->limit(5)
|
||||
->get();
|
||||
|
||||
$this->assertCount(5, $rows);
|
||||
$this->assertSame('Item 11', $rows[0]->NAME);
|
||||
$this->assertSame('Item 15', $rows[4]->NAME);
|
||||
}
|
||||
|
||||
public function test_offset_without_limit(): void
|
||||
{
|
||||
$rows = $this->db()->table($this->tableName)
|
||||
->orderBy('ID')
|
||||
->offset(15)
|
||||
->get();
|
||||
|
||||
$this->assertCount(5, $rows);
|
||||
$this->assertSame('Item 16', $rows[0]->NAME);
|
||||
}
|
||||
|
||||
public function test_standard_pagination(): void
|
||||
{
|
||||
$page = $this->db()->table($this->tableName)
|
||||
->orderBy('ID')
|
||||
->paginate(5, ['*'], 'page', 3);
|
||||
|
||||
$this->assertSame(20, $page->total());
|
||||
$this->assertSame(4, $page->lastPage());
|
||||
$this->assertSame(3, $page->currentPage());
|
||||
$this->assertCount(5, $page->items());
|
||||
$this->assertSame('Item 11', $page->items()[0]->NAME);
|
||||
}
|
||||
|
||||
public function test_simple_pagination(): void
|
||||
{
|
||||
$page = $this->db()->table($this->tableName)
|
||||
->orderBy('ID')
|
||||
->simplePaginate(5, ['*'], 'page', 2);
|
||||
|
||||
$this->assertSame(2, $page->currentPage());
|
||||
$this->assertCount(5, $page->items());
|
||||
$this->assertSame('Item 06', $page->items()[0]->NAME);
|
||||
$this->assertTrue($page->hasMorePages());
|
||||
}
|
||||
|
||||
public function test_insert_get_id_returns_generated_identity(): void
|
||||
{
|
||||
$id = $this->db()->table($this->tableName)
|
||||
->insertGetId(['NAME' => 'New Item']);
|
||||
|
||||
$this->assertEquals(21, $id);
|
||||
|
||||
$row = $this->db()->table($this->tableName)
|
||||
->where('ID', $id)
|
||||
->first();
|
||||
|
||||
$this->assertNotNull($row);
|
||||
$this->assertSame('New Item', $row->NAME);
|
||||
}
|
||||
|
||||
public function test_pagination_does_not_duplicate_rows(): void
|
||||
{
|
||||
$ids = [];
|
||||
|
||||
for ($page = 1; $page <= 4; $page++) {
|
||||
$result = $this->db()->table($this->tableName)
|
||||
->orderBy('ID')
|
||||
->paginate(5, ['*'], 'page', $page);
|
||||
|
||||
foreach ($result->items() as $row) {
|
||||
$ids[] = (int) $row->ID;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertCount(20, $ids);
|
||||
$this->assertSame(range(1, 20), $ids);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
class RawQueryTest extends Db2TestCase
|
||||
{
|
||||
public function test_raw_query_columns_are_not_removed(): void
|
||||
{
|
||||
$row = $this->db()->selectOne("
|
||||
SELECT
|
||||
CAST('ordinary value' AS VARCHAR(30))
|
||||
AS \"data\",
|
||||
CAST('1' AS VARCHAR(1))
|
||||
AS \"__db2_null_flag_0\"
|
||||
FROM SYSIBM.SYSDUMMY1
|
||||
");
|
||||
|
||||
$this->assertSame('ordinary value', $row->data);
|
||||
|
||||
$this->assertTrue(
|
||||
property_exists($row, '__db2_null_flag_0')
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'1',
|
||||
$row->__db2_null_flag_0
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
use Illuminate\Database\QueryException;
|
||||
use RuntimeException;
|
||||
|
||||
class TransactionTest extends Db2TestCase
|
||||
{
|
||||
private string $tableName = '';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->tableName = 'DB2_TEST.DB2T_' .
|
||||
strtoupper(bin2hex(random_bytes(6)));
|
||||
|
||||
$this->db()->statement("
|
||||
CREATE TABLE {$this->tableName} (
|
||||
ID INTEGER NOT NULL PRIMARY KEY,
|
||||
NAME VARCHAR(100) NOT NULL
|
||||
)
|
||||
");
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
try {
|
||||
if ($this->tableName !== '') {
|
||||
$db = $this->db();
|
||||
|
||||
while ($db->transactionLevel() > 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
|
||||
$db->statement("DROP TABLE {$this->tableName}");
|
||||
}
|
||||
} finally {
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
|
||||
private function insertRow(int $id, string $name): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->insert([
|
||||
'ID' => $id,
|
||||
'NAME' => $name,
|
||||
]);
|
||||
}
|
||||
|
||||
private function rowCount(): int
|
||||
{
|
||||
return $this->db()->table($this->tableName)->count();
|
||||
}
|
||||
|
||||
public function test_transaction_commit(): void
|
||||
{
|
||||
$this->db()->beginTransaction();
|
||||
|
||||
$this->insertRow(1, 'Committed');
|
||||
|
||||
$this->assertSame(1, $this->db()->transactionLevel());
|
||||
|
||||
$this->db()->commit();
|
||||
|
||||
$this->assertSame(0, $this->db()->transactionLevel());
|
||||
$this->assertSame(1, $this->rowCount());
|
||||
}
|
||||
|
||||
public function test_transaction_rollback(): void
|
||||
{
|
||||
$this->db()->beginTransaction();
|
||||
|
||||
$this->insertRow(1, 'Rolled back');
|
||||
|
||||
$this->db()->rollBack();
|
||||
|
||||
$this->assertSame(0, $this->db()->transactionLevel());
|
||||
$this->assertSame(0, $this->rowCount());
|
||||
}
|
||||
|
||||
public function test_transaction_closure_commits(): void
|
||||
{
|
||||
$result = $this->db()->transaction(function () {
|
||||
$this->insertRow(1, 'Closure');
|
||||
|
||||
return 'success';
|
||||
});
|
||||
|
||||
$this->assertSame('success', $result);
|
||||
$this->assertSame(1, $this->rowCount());
|
||||
$this->assertSame(0, $this->db()->transactionLevel());
|
||||
}
|
||||
|
||||
public function test_transaction_closure_rolls_back_on_exception(): void
|
||||
{
|
||||
try {
|
||||
$this->db()->transaction(function () {
|
||||
$this->insertRow(1, 'Rollback');
|
||||
|
||||
throw new RuntimeException('Expected failure');
|
||||
});
|
||||
|
||||
$this->fail('Expected exception was not thrown.');
|
||||
} catch (RuntimeException $e) {
|
||||
$this->assertSame('Expected failure', $e->getMessage());
|
||||
}
|
||||
|
||||
$this->assertSame(0, $this->rowCount());
|
||||
$this->assertSame(0, $this->db()->transactionLevel());
|
||||
}
|
||||
|
||||
public function test_nested_transaction_commit(): void
|
||||
{
|
||||
$db = $this->db();
|
||||
|
||||
$db->beginTransaction();
|
||||
$this->insertRow(1, 'Outer');
|
||||
|
||||
$db->beginTransaction();
|
||||
$this->insertRow(2, 'Inner');
|
||||
|
||||
$this->assertSame(2, $db->transactionLevel());
|
||||
|
||||
$db->commit();
|
||||
$this->assertSame(1, $db->transactionLevel());
|
||||
|
||||
$db->commit();
|
||||
|
||||
$this->assertSame(0, $db->transactionLevel());
|
||||
$this->assertSame(2, $this->rowCount());
|
||||
}
|
||||
|
||||
public function test_nested_rollback_preserves_outer_transaction(): void
|
||||
{
|
||||
$db = $this->db();
|
||||
|
||||
$db->beginTransaction();
|
||||
$this->insertRow(1, 'Outer');
|
||||
|
||||
$db->beginTransaction();
|
||||
$this->insertRow(2, 'Inner');
|
||||
|
||||
$db->rollBack();
|
||||
|
||||
$this->assertSame(1, $db->transactionLevel());
|
||||
$this->assertSame(1, $this->rowCount());
|
||||
|
||||
$db->commit();
|
||||
|
||||
$this->assertSame(0, $db->transactionLevel());
|
||||
$this->assertSame(1, $this->rowCount());
|
||||
}
|
||||
|
||||
public function test_nested_exception_preserves_outer_changes(): void
|
||||
{
|
||||
$db = $this->db();
|
||||
|
||||
$db->beginTransaction();
|
||||
$this->insertRow(1, 'Outer');
|
||||
|
||||
try {
|
||||
$db->transaction(function () {
|
||||
$this->insertRow(2, 'Inner');
|
||||
|
||||
throw new RuntimeException('Inner failure');
|
||||
});
|
||||
} catch (RuntimeException $e) {
|
||||
$this->assertSame('Inner failure', $e->getMessage());
|
||||
}
|
||||
|
||||
$this->assertSame(1, $db->transactionLevel());
|
||||
|
||||
$db->commit();
|
||||
|
||||
$this->assertSame(1, $this->rowCount());
|
||||
}
|
||||
|
||||
public function test_sql_error_rolls_back_transaction(): void
|
||||
{
|
||||
$db = $this->db();
|
||||
|
||||
try {
|
||||
$db->transaction(function () {
|
||||
$this->insertRow(1, 'Valid');
|
||||
$this->insertRow(1, 'Duplicate');
|
||||
});
|
||||
|
||||
$this->fail('Expected duplicate-key exception.');
|
||||
} catch (QueryException $e) {
|
||||
$this->assertSame('23505', $e->getCode());
|
||||
}
|
||||
|
||||
$this->assertSame(0, $db->transactionLevel());
|
||||
$this->assertSame(0, $this->rowCount());
|
||||
}
|
||||
|
||||
public function test_transaction_level_is_restored(): void
|
||||
{
|
||||
$db = $this->db();
|
||||
|
||||
$this->assertSame(0, $db->transactionLevel());
|
||||
|
||||
$db->beginTransaction();
|
||||
$this->assertSame(1, $db->transactionLevel());
|
||||
|
||||
$db->beginTransaction();
|
||||
$this->assertSame(2, $db->transactionLevel());
|
||||
|
||||
$db->rollBack();
|
||||
$this->assertSame(1, $db->transactionLevel());
|
||||
|
||||
$db->rollBack();
|
||||
$this->assertSame(0, $db->transactionLevel());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
class UpsertTest extends Db2TestCase
|
||||
{
|
||||
private string $tableName = '';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->tableName = 'DB2_TEST.DB2T_' .
|
||||
strtoupper(bin2hex(random_bytes(6)));
|
||||
|
||||
$this->db()->statement("
|
||||
CREATE TABLE {$this->tableName} (
|
||||
ID INTEGER NOT NULL,
|
||||
CODE VARCHAR(30) NOT NULL,
|
||||
NAME VARCHAR(100) NOT NULL,
|
||||
STATUS VARCHAR(20) NOT NULL,
|
||||
PRIMARY KEY (ID),
|
||||
CONSTRAINT UQ_CODE UNIQUE (CODE)
|
||||
)
|
||||
");
|
||||
|
||||
$this->db()->table($this->tableName)->insert([
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Original',
|
||||
'STATUS' => 'active',
|
||||
]);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
try {
|
||||
if ($this->tableName !== '') {
|
||||
$this->db()->statement(
|
||||
"DROP TABLE {$this->tableName}"
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_upsert_inserts_new_row(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->upsert(
|
||||
[[
|
||||
'ID' => 2,
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'Second',
|
||||
'STATUS' => 'active',
|
||||
]],
|
||||
['ID'],
|
||||
['NAME', 'STATUS']
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'Second',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 2)->first()->NAME
|
||||
);
|
||||
}
|
||||
|
||||
public function test_upsert_updates_existing_row(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->upsert(
|
||||
[[
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Updated',
|
||||
'STATUS' => 'inactive',
|
||||
]],
|
||||
['ID'],
|
||||
['NAME', 'STATUS']
|
||||
);
|
||||
|
||||
$row = $this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first();
|
||||
|
||||
$this->assertSame('Updated', $row->NAME);
|
||||
$this->assertSame('inactive', $row->STATUS);
|
||||
}
|
||||
|
||||
public function test_upsert_multiple_rows(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->upsert(
|
||||
[
|
||||
[
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Changed',
|
||||
'STATUS' => 'active',
|
||||
],
|
||||
[
|
||||
'ID' => 2,
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'New',
|
||||
'STATUS' => 'active',
|
||||
],
|
||||
],
|
||||
['ID'],
|
||||
['NAME']
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
2,
|
||||
$this->db()->table($this->tableName)->count()
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'Changed',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first()->NAME
|
||||
);
|
||||
}
|
||||
|
||||
public function test_upsert_preserves_unselected_columns(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->upsert(
|
||||
[[
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Changed',
|
||||
'STATUS' => 'inactive',
|
||||
]],
|
||||
['ID'],
|
||||
['NAME']
|
||||
);
|
||||
|
||||
$row = $this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first();
|
||||
|
||||
$this->assertSame('Changed', $row->NAME);
|
||||
$this->assertSame('active', $row->STATUS);
|
||||
}
|
||||
|
||||
public function test_insert_or_ignore_inserts_new_row(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->insertOrIgnore([
|
||||
'ID' => 2,
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'Second',
|
||||
'STATUS' => 'active',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
2,
|
||||
$this->db()->table($this->tableName)->count()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_insert_or_ignore_skips_duplicate(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->insertOrIgnore([
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Duplicate',
|
||||
'STATUS' => 'inactive',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'Original',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first()->NAME
|
||||
);
|
||||
}
|
||||
|
||||
public function test_insert_or_ignore_multiple_rows(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->insertOrIgnore([
|
||||
[
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Duplicate',
|
||||
'STATUS' => 'inactive',
|
||||
],
|
||||
[
|
||||
'ID' => 2,
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'New',
|
||||
'STATUS' => 'active',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
2,
|
||||
$this->db()->table($this->tableName)->count()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_insert_or_ignore_duplicate_unique_code(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->insertOrIgnore([
|
||||
'ID' => 99,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Different',
|
||||
'STATUS' => 'inactive',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
1,
|
||||
$this->db()->table($this->tableName)->count()
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'Original',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first()->NAME
|
||||
);
|
||||
}
|
||||
|
||||
public function test_insert_or_ignore_does_not_hide_check_violations(): void
|
||||
{
|
||||
$this->expectException(
|
||||
\Illuminate\Database\QueryException::class
|
||||
);
|
||||
|
||||
$this->db()->table($this->tableName)->insertOrIgnore([
|
||||
'ID' => 99,
|
||||
'CODE' => 'A099',
|
||||
'NAME' => 'Invalid',
|
||||
'STATUS' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_update_or_insert(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->updateOrInsert(
|
||||
['ID' => 1],
|
||||
['NAME' => 'Updated']
|
||||
);
|
||||
|
||||
$this->db()->table($this->tableName)->updateOrInsert(
|
||||
['ID' => 2],
|
||||
[
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'Inserted',
|
||||
'STATUS' => 'active',
|
||||
]
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'Updated',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first()->NAME
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'Inserted',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 2)->first()->NAME
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Db2;
|
||||
|
||||
class UpsertTest extends Db2TestCase
|
||||
{
|
||||
private string $tableName = '';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->tableName = 'DB2_TEST.DB2T_' .
|
||||
strtoupper(bin2hex(random_bytes(6)));
|
||||
|
||||
$this->db()->statement("
|
||||
CREATE TABLE {$this->tableName} (
|
||||
ID INTEGER NOT NULL,
|
||||
CODE VARCHAR(30) NOT NULL,
|
||||
NAME VARCHAR(100) NOT NULL,
|
||||
STATUS VARCHAR(20) NOT NULL,
|
||||
PRIMARY KEY (ID),
|
||||
CONSTRAINT UQ_CODE UNIQUE (CODE)
|
||||
)
|
||||
");
|
||||
|
||||
$this->db()->table($this->tableName)->insert([
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Original',
|
||||
'STATUS' => 'active',
|
||||
]);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
try {
|
||||
if ($this->tableName !== '') {
|
||||
$this->db()->statement(
|
||||
"DROP TABLE {$this->tableName}"
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_upsert_inserts_new_row(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->upsert(
|
||||
[[
|
||||
'ID' => 2,
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'Second',
|
||||
'STATUS' => 'active',
|
||||
]],
|
||||
['ID'],
|
||||
['NAME', 'STATUS']
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'Second',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 2)->first()->NAME
|
||||
);
|
||||
}
|
||||
|
||||
public function test_upsert_updates_existing_row(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->upsert(
|
||||
[[
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Updated',
|
||||
'STATUS' => 'inactive',
|
||||
]],
|
||||
['ID'],
|
||||
['NAME', 'STATUS']
|
||||
);
|
||||
|
||||
$row = $this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first();
|
||||
|
||||
$this->assertSame('Updated', $row->NAME);
|
||||
$this->assertSame('inactive', $row->STATUS);
|
||||
}
|
||||
|
||||
public function test_upsert_multiple_rows(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->upsert(
|
||||
[
|
||||
[
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Changed',
|
||||
'STATUS' => 'active',
|
||||
],
|
||||
[
|
||||
'ID' => 2,
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'New',
|
||||
'STATUS' => 'active',
|
||||
],
|
||||
],
|
||||
['ID'],
|
||||
['NAME']
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
2,
|
||||
$this->db()->table($this->tableName)->count()
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'Changed',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first()->NAME
|
||||
);
|
||||
}
|
||||
|
||||
public function test_upsert_preserves_unselected_columns(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->upsert(
|
||||
[[
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Changed',
|
||||
'STATUS' => 'inactive',
|
||||
]],
|
||||
['ID'],
|
||||
['NAME']
|
||||
);
|
||||
|
||||
$row = $this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first();
|
||||
|
||||
$this->assertSame('Changed', $row->NAME);
|
||||
$this->assertSame('active', $row->STATUS);
|
||||
}
|
||||
|
||||
public function test_insert_or_ignore_inserts_new_row(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->insertOrIgnore([
|
||||
'ID' => 2,
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'Second',
|
||||
'STATUS' => 'active',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
2,
|
||||
$this->db()->table($this->tableName)->count()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_insert_or_ignore_skips_duplicate(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->insertOrIgnore([
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Duplicate',
|
||||
'STATUS' => 'inactive',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'Original',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first()->NAME
|
||||
);
|
||||
}
|
||||
|
||||
public function test_insert_or_ignore_multiple_rows(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->insertOrIgnore([
|
||||
[
|
||||
'ID' => 1,
|
||||
'CODE' => 'A001',
|
||||
'NAME' => 'Duplicate',
|
||||
'STATUS' => 'inactive',
|
||||
],
|
||||
[
|
||||
'ID' => 2,
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'New',
|
||||
'STATUS' => 'active',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
2,
|
||||
$this->db()->table($this->tableName)->count()
|
||||
);
|
||||
}
|
||||
|
||||
public function test_update_or_insert(): void
|
||||
{
|
||||
$this->db()->table($this->tableName)->updateOrInsert(
|
||||
['ID' => 1],
|
||||
['NAME' => 'Updated']
|
||||
);
|
||||
|
||||
$this->db()->table($this->tableName)->updateOrInsert(
|
||||
['ID' => 2],
|
||||
[
|
||||
'CODE' => 'A002',
|
||||
'NAME' => 'Inserted',
|
||||
'STATUS' => 'active',
|
||||
]
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'Updated',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 1)->first()->NAME
|
||||
);
|
||||
|
||||
$this->assertSame(
|
||||
'Inserted',
|
||||
$this->db()->table($this->tableName)
|
||||
->where('ID', 2)->first()->NAME
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user