db2 driver updates

This commit is contained in:
Mark Gregory
2026-11-11 11:03:23 +00:00
parent 2686fc6e0b
commit 984b52f39e
9 changed files with 1389 additions and 7 deletions
+29
View File
@@ -0,0 +1,29 @@
# Db2 LUW query compatibility
Phase 6 uses the live `db2_local` connection to verify scalar and IN subqueries,
ordered UNION ALL with offset and limit, EXISTS, random ordering, LIKE and
NOT LIKE, and Eloquent datetime hydration for the security settings passkey list.
Regular single-table result reads use the PDO_ODBC NULL workaround. Embedded
queries retain their declared projection and native SQL NULL semantics.
Nullable TIMESTAMP results handled by the workaround use a Carbon-compatible
format with six fractional digits. SQL NULL and empty strings remain distinct.
## Limits
- The NULL workaround covers eligible single-table reads through `get()` and
helpers such as `first()` and `pluck()`. It does not cover raw SQL, cursors,
joins, unions, or arbitrary expressions in the projection. In these cases
PDO_ODBC's native result handling applies.
- Case-insensitive LIKE uses Db2's UPPER function on both operands and follows
the database's string and collation rules.
- Pessimistic locks, joined writes, JSON predicates and seeded random ordering
were outside this phase's verification.
## Run the tests
```sh
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2/QueryCompatibilityTest.php
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2
APP_ENV=testing php artisan test --do-not-cache-result
```
+5
View File
@@ -79,6 +79,11 @@ class Db2Connection extends Connection
return $rows; return $rows;
} }
public function query()
{
return new Db2QueryBuilder($this, $this->getQueryGrammar(), $this->getPostProcessor());
}
protected function getDefaultQueryGrammar() protected function getDefaultQueryGrammar()
{ {
return new Db2QueryGrammar($this); return new Db2QueryGrammar($this);
@@ -0,0 +1,107 @@
<?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
);
// 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;
}
$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;
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Query\Builder;
class Db2QueryBuilder extends Builder
{
protected function runSelect()
{
$this->applyBeforeQueryCallbacks();
return $this->connection->select(
$this->grammar->compileResultSelect($this),
$this->getBindings(),
! $this->useWritePdo,
$this->fetchUsing
);
}
}
+40 -7
View File
@@ -300,7 +300,41 @@ class Db2QueryGrammar extends Grammar
/** A non-NULL value used only for nullable TIMESTAMP result columns. */ /** A non-NULL value used only for nullable TIMESTAMP result columns. */
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__'; public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
public function compileSelect(\Illuminate\Database\Query\Builder $query) protected function compileUnions(Builder $query)
{
$union = clone $query;
$union->unionLimit = null;
$union->unionOffset = null;
$sql = parent::compileUnions($union);
if ($query->unionOffset !== null) {
$sql .= ' '.$this->compileOffset($query, $query->unionOffset);
}
if ($query->unionLimit !== null) {
$sql .= $query->unionOffset > 0
? ' fetch next '.(int) $query->unionLimit.' rows only'
: ' fetch first '.(int) $query->unionLimit.' rows only';
}
return $sql;
}
protected function whereLike(Builder $query, $where)
{
$column = $this->wrap($where['column']);
$pattern = $this->parameter($where['value']);
$operator = $where['not'] ? 'not like' : 'like';
if (! $where['caseSensitive']) {
$column = 'UPPER('.$column.')';
$pattern = 'UPPER(CAST('.$pattern.' AS VARCHAR(32672 OCTETS)))';
}
return $column.' '.$operator.' '.$pattern;
}
// Only result queries can add and then decode the ODBC NULL indicators.
public function compileResultSelect(Builder $query)
{ {
if ( if (
! is_string($query->from) || ! is_string($query->from) ||
@@ -435,12 +469,11 @@ class Db2QueryGrammar extends Grammar
. $wrapped . $wrapped
. ", CAST('' AS VARCHAR({$length})))"; . ", CAST('' AS VARCHAR({$length})))";
} else { } else {
$expression = 'CASE WHEN ' $formatted = $type === 'TIMESTAMP'
. $wrapped ? "VARCHAR_FORMAT({$wrapped}, 'YYYY-MM-DD HH24:MI:SS.FF6')"
. " IS NULL THEN CAST('' AS VARCHAR(32))" : "CAST({$wrapped} AS VARCHAR(32))";
. ' ELSE CAST('
. $wrapped $expression = "COALESCE({$formatted}, CAST('' AS VARCHAR(32)))";
. ' AS VARCHAR(32)) END';
} }
$ordinary[] = new Expression( $ordinary[] = new Expression(
@@ -0,0 +1,495 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
class Db2QueryGrammar extends Grammar
{
protected $selectComponents = [
'aggregate',
'columns',
'from',
'indexHint',
'joins',
'wheres',
'groups',
'havings',
'orders',
'offset',
'limit',
'lock',
];
private array $db2ColumnCache = [];
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
/**
* Compile a Db2 MERGE statement for Laravel upserts.
*/
public function compileUpsert(
Builder $query,
array $values,
array $uniqueBy,
array $update
) {
$columns = $this->db2MergeColumns($values);
foreach ($uniqueBy as $column) {
if (! in_array($column, $columns, true)) {
throw new \InvalidArgumentException(
"Upsert key is missing from inserted values: {$column}"
);
}
}
$source = $this->db2MergeSource($values, $columns);
$matches = [];
foreach ($uniqueBy as $column) {
$wrapped = $this->wrap($column);
$matches[] = "target.{$wrapped} = source.{$wrapped}";
}
$updates = [];
foreach ($update as $key => $value) {
if (is_int($key)) {
if (! in_array($value, $columns, true)) {
throw new \InvalidArgumentException(
"Unknown upsert update column: {$value}"
);
}
$wrapped = $this->wrap($value);
$updates[] = "target.{$wrapped} = source.{$wrapped}";
} else {
$updates[] = "target."
. $this->wrap($key)
. " = "
. $this->parameter($value);
}
}
$insertColumns = $this->columnize($columns);
$insertValues = implode(', ', array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
));
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
. "USING ({$source}) AS source "
. "ON (" . implode(' AND ', $matches) . ") ";
if ($updates !== []) {
$sql .= "WHEN MATCHED THEN UPDATE SET "
. implode(', ', $updates) . " ";
}
return $sql
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
. "VALUES ({$insertValues})";
}
/**
* Insert rows without replacing existing rows.
*
* Db2 MERGE ignores rows that match the selected key.
*/
public function compileInsertOrIgnore(
Builder $query,
array $values
) {
$columns = $this->db2MergeColumns($values);
$source = $this->db2MergeSource($values, $columns);
$indexes = $this->connection
->getSchemaBuilder()
->getIndexes($query->from);
$uniqueConditions = [];
foreach ($indexes as $index) {
if (! ($index['unique'] ?? false)) {
continue;
}
$indexColumns = $index['columns'] ?? [];
if ($indexColumns === []) {
continue;
}
// A unique key can only be compared if every
// participating column exists in the source.
$conditions = [];
foreach ($indexColumns as $column) {
$matchedColumn = null;
foreach ($columns as $candidate) {
if (strcasecmp($candidate, $column) === 0) {
$matchedColumn = $candidate;
break;
}
}
if ($matchedColumn === null) {
$conditions = [];
break;
}
$wrapped = $this->wrap($matchedColumn);
$conditions[] = "target.{$wrapped} = source.{$wrapped}";
}
if ($conditions !== []) {
$uniqueConditions[] = '('
. implode(' AND ', $conditions)
. ')';
}
}
if ($uniqueConditions === []) {
throw new \RuntimeException(
'Db2 insertOrIgnore requires an applicable unique index.'
);
}
$insertColumns = $this->columnize($columns);
$insertValues = implode(', ', array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
));
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
. "USING ({$source}) AS source "
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
. "VALUES ({$insertValues})";
}
/**
* Validate the column layout of a multi-row MERGE.
*/
private function db2MergeColumns(array $values): array
{
if ($values === []) {
throw new \InvalidArgumentException(
'MERGE requires at least one row.'
);
}
$columns = array_keys(reset($values));
foreach ($values as $row) {
if (array_keys($row) !== $columns) {
throw new \InvalidArgumentException(
'All MERGE rows must contain the same columns.'
);
}
}
return $columns;
}
/**
* Build a parameterized Db2 MERGE source.
*/
private function db2MergeSource(
array $values,
array $columns
): string {
$selects = [];
foreach ($values as $row) {
$parts = [];
foreach ($columns as $column) {
$parts[] = $this->parameter($row[$column])
. ' AS '
. $this->wrap($column);
}
$selects[] = 'SELECT '
. implode(', ', $parts)
. ' FROM SYSIBM.SYSDUMMY1';
}
return implode(' UNION ALL ', $selects);
}
/**
* Compile a Db2 LUW savepoint statement.
*/
public function compileSavepoint($name)
{
return 'SAVEPOINT ' . $name
. ' ON ROLLBACK RETAIN CURSORS';
}
/**
* Compile a Db2 LUW rollback-to-savepoint statement.
*/
public function compileSavepointRollBack($name)
{
return 'ROLLBACK TO SAVEPOINT ' . $name;
}
protected function compileAggregate($query, $aggregate)
{
$column = $this->columnize($aggregate['columns']);
if (is_array($query->distinct)) {
$column = 'distinct '.$this->columnize($query->distinct);
} elseif ($query->distinct && $column !== '*') {
$column = 'distinct '.$column;
}
$function = strtolower($aggregate['function']);
$expression = "{$function}({$column})";
// PDO_ODBC may return Db2 integer aggregates as binary data.
// Cast migration batch aggregates, including custom repository tables.
if (
$function === 'max' &&
count($aggregate['columns']) === 1 &&
$aggregate['columns'][0] === 'batch'
) {
$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,529 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
class Db2QueryGrammar extends Grammar
{
protected $selectComponents = [
'aggregate',
'columns',
'from',
'indexHint',
'joins',
'wheres',
'groups',
'havings',
'orders',
'offset',
'limit',
'lock',
];
private array $db2ColumnCache = [];
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
/**
* Compile a Db2 MERGE statement for Laravel upserts.
*/
public function compileUpsert(
Builder $query,
array $values,
array $uniqueBy,
array $update
) {
$columns = $this->db2MergeColumns($values);
foreach ($uniqueBy as $column) {
if (! in_array($column, $columns, true)) {
throw new \InvalidArgumentException(
"Upsert key is missing from inserted values: {$column}"
);
}
}
$source = $this->db2MergeSource($values, $columns);
$matches = [];
foreach ($uniqueBy as $column) {
$wrapped = $this->wrap($column);
$matches[] = "target.{$wrapped} = source.{$wrapped}";
}
$updates = [];
foreach ($update as $key => $value) {
if (is_int($key)) {
if (! in_array($value, $columns, true)) {
throw new \InvalidArgumentException(
"Unknown upsert update column: {$value}"
);
}
$wrapped = $this->wrap($value);
$updates[] = "target.{$wrapped} = source.{$wrapped}";
} else {
$updates[] = "target."
. $this->wrap($key)
. " = "
. $this->parameter($value);
}
}
$insertColumns = $this->columnize($columns);
$insertValues = implode(', ', array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
));
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
. "USING ({$source}) AS source "
. "ON (" . implode(' AND ', $matches) . ") ";
if ($updates !== []) {
$sql .= "WHEN MATCHED THEN UPDATE SET "
. implode(', ', $updates) . " ";
}
return $sql
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
. "VALUES ({$insertValues})";
}
/**
* Insert rows without replacing existing rows.
*
* Db2 MERGE ignores rows that match the selected key.
*/
public function compileInsertOrIgnore(
Builder $query,
array $values
) {
$columns = $this->db2MergeColumns($values);
$source = $this->db2MergeSource($values, $columns);
$indexes = $this->connection
->getSchemaBuilder()
->getIndexes($query->from);
$uniqueConditions = [];
foreach ($indexes as $index) {
if (! ($index['unique'] ?? false)) {
continue;
}
$indexColumns = $index['columns'] ?? [];
if ($indexColumns === []) {
continue;
}
// A unique key can only be compared if every
// participating column exists in the source.
$conditions = [];
foreach ($indexColumns as $column) {
$matchedColumn = null;
foreach ($columns as $candidate) {
if (strcasecmp($candidate, $column) === 0) {
$matchedColumn = $candidate;
break;
}
}
if ($matchedColumn === null) {
$conditions = [];
break;
}
$wrapped = $this->wrap($matchedColumn);
$conditions[] = "target.{$wrapped} = source.{$wrapped}";
}
if ($conditions !== []) {
$uniqueConditions[] = '('
. implode(' AND ', $conditions)
. ')';
}
}
if ($uniqueConditions === []) {
throw new \RuntimeException(
'Db2 insertOrIgnore requires an applicable unique index.'
);
}
$insertColumns = $this->columnize($columns);
$insertValues = implode(', ', array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
));
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
. "USING ({$source}) AS source "
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
. "VALUES ({$insertValues})";
}
/**
* Validate the column layout of a multi-row MERGE.
*/
private function db2MergeColumns(array $values): array
{
if ($values === []) {
throw new \InvalidArgumentException(
'MERGE requires at least one row.'
);
}
$columns = array_keys(reset($values));
foreach ($values as $row) {
if (array_keys($row) !== $columns) {
throw new \InvalidArgumentException(
'All MERGE rows must contain the same columns.'
);
}
}
return $columns;
}
/**
* Build a parameterized Db2 MERGE source.
*/
private function db2MergeSource(
array $values,
array $columns
): string {
$selects = [];
foreach ($values as $row) {
$parts = [];
foreach ($columns as $column) {
$parts[] = $this->parameter($row[$column])
. ' AS '
. $this->wrap($column);
}
$selects[] = 'SELECT '
. implode(', ', $parts)
. ' FROM SYSIBM.SYSDUMMY1';
}
return implode(' UNION ALL ', $selects);
}
/**
* Compile a Db2 LUW savepoint statement.
*/
public function compileSavepoint($name)
{
return 'SAVEPOINT ' . $name
. ' ON ROLLBACK RETAIN CURSORS';
}
/**
* Compile a Db2 LUW rollback-to-savepoint statement.
*/
public function compileSavepointRollBack($name)
{
return 'ROLLBACK TO SAVEPOINT ' . $name;
}
protected function compileAggregate($query, $aggregate)
{
$column = $this->columnize($aggregate['columns']);
if (is_array($query->distinct)) {
$column = 'distinct '.$this->columnize($query->distinct);
} elseif ($query->distinct && $column !== '*') {
$column = 'distinct '.$column;
}
$function = strtolower($aggregate['function']);
$expression = "{$function}({$column})";
// PDO_ODBC may return Db2 integer aggregates as binary data.
// Cast migration batch aggregates, including custom repository tables.
if (
$function === 'max' &&
count($aggregate['columns']) === 1 &&
$aggregate['columns'][0] === 'batch'
) {
$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__';
protected function compileUnions(Builder $query)
{
$union = clone $query;
$union->unionLimit = null;
$union->unionOffset = null;
$sql = parent::compileUnions($union);
if ($query->unionOffset !== null) {
$sql .= ' '.$this->compileOffset($query, $query->unionOffset);
}
if ($query->unionLimit !== null) {
$sql .= $query->unionOffset > 0
? ' fetch next '.(int) $query->unionLimit.' rows only'
: ' '.$this->compileLimit($union, $query->unionLimit);
}
return $sql;
}
protected function whereLike(Builder $query, $where)
{
$column = $this->wrap($where['column']);
$pattern = $this->parameter($where['value']);
$operator = $where['not'] ? 'not like' : 'like';
if (! $where['caseSensitive']) {
$column = 'UPPER('.$column.')';
$pattern = 'UPPER(CAST('.$pattern.' AS VARCHAR(32672 OCTETS)))';
}
return $column.' '.$operator.' '.$pattern;
}
// Only result queries can add and then decode the ODBC NULL indicators.
public function compileResultSelect(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,90 @@
<?php
namespace Tests\Feature\Db2;
class QueryCompatibilityTest extends Db2TestCase
{
private ?string $table = null;
protected function setUp(): void
{
parent::setUp();
$table = 'DB2_TEST.DB2Q_'.strtoupper(bin2hex(random_bytes(6)));
$this->db()->statement("CREATE TABLE {$table} (ID INTEGER NOT NULL PRIMARY KEY, LABEL VARCHAR(40), CREATED_AT TIMESTAMP NOT NULL, LAST_USED_AT TIMESTAMP)");
$this->table = $table;
$this->db()->statement("INSERT INTO {$table} (ID, LABEL, CREATED_AT, LAST_USED_AT) VALUES
(1, 'Alpha', TIMESTAMP('2026-11-11 08:47:26.123456'), NULL),
(2, 'beta', TIMESTAMP('2026-11-11 08:47:26.123456'), TIMESTAMP('2026-11-12 10:11:12.654321')),
(3, NULL, TIMESTAMP('2026-11-11 08:47:26.123456'), NULL)");
}
protected function tearDown(): void
{
try {
if ($this->table !== null) {
$this->db()->statement("DROP TABLE {$this->table}");
}
} finally {
parent::tearDown();
}
}
public function test_scalar_subquery_with_nullable_projection(): void
{
$db = $this->db();
$label = $db->table($this->table)->select('LABEL')->where('ID', 1);
$row = $db->table($this->table)->selectSub($label, 'matched')->where('ID', 2)->first();
$this->assertSame('Alpha', $row->matched);
}
public function test_where_in_with_nullable_projection(): void
{
$db = $this->db();
$labels = $db->table($this->table)->select('LABEL')->where('ID', 2);
$this->assertSame([2], $db->table($this->table)->whereIn('LABEL', $labels)->pluck('ID')->map(fn ($id) => (int) $id)->all());
}
public function test_union_with_nullable_projection(): void
{
$db = $this->db();
$query = $db->table($this->table)->select('LABEL')->where('ID', 1)
->unionAll($db->table($this->table)->select('LABEL')->where('ID', 2))
->orderBy('LABEL')->offset(1)->limit(1);
$this->assertSame(['beta'], $query->pluck('LABEL')->all());
}
public function test_exists_returns_true_and_false(): void
{
$this->assertTrue($this->db()->table($this->table)->where('ID', 1)->exists());
$this->assertFalse($this->db()->table($this->table)->where('ID', 4)->exists());
}
public function test_where_like_honors_case_sensitivity(): void
{
$db = $this->db();
$this->assertSame([1], $db->table($this->table)->whereLike('LABEL', 'alpha%')->pluck('ID')->map(fn ($id) => (int) $id)->all());
$this->assertSame([], $db->table($this->table)->whereLike('LABEL', 'alpha%', caseSensitive: true)->pluck('ID')->map(fn ($id) => (int) $id)->all());
$this->assertSame([2], $db->table($this->table)->whereNotLike('LABEL', 'ALPHA%')->pluck('ID')->map(fn ($id) => (int) $id)->all());
}
public function test_random_order_executes_on_db2(): void
{
$this->assertCount(2, $this->db()->table($this->table)->select('ID')->inRandomOrder()->limit(2)->get());
}
public function test_eloquent_casts_db2_timestamps_for_security_settings(): void
{
$model = new class extends \Illuminate\Database\Eloquent\Model {
protected $casts = ['CREATED_AT' => 'datetime', 'LAST_USED_AT' => 'datetime'];
};
$model->setConnection('db2_local')->setTable($this->table);
$rows = $model->newQuery()->select('ID', 'CREATED_AT', 'LAST_USED_AT')->orderBy('ID')->get();
$this->assertSame('2026-11-11 08:47:26.123456', $rows[0]->CREATED_AT->format('Y-m-d H:i:s.u'));
$this->assertNull($rows[0]->LAST_USED_AT);
$this->assertSame('2026-11-12 10:11:12.654321', $rows[1]->LAST_USED_AT->format('Y-m-d H:i:s.u'));
}
}
@@ -0,0 +1,74 @@
<?php
namespace Tests\Feature\Db2;
class QueryCompatibilityTest extends Db2TestCase
{
private ?string $table = null;
protected function setUp(): void
{
parent::setUp();
$table = 'DB2_TEST.DB2Q_'.strtoupper(bin2hex(random_bytes(6)));
$this->db()->statement("CREATE TABLE {$table} (ID INTEGER NOT NULL PRIMARY KEY, LABEL VARCHAR(40))");
$this->table = $table;
$this->db()->statement("INSERT INTO {$table} VALUES (1, 'Alpha'), (2, 'beta'), (3, NULL)");
}
protected function tearDown(): void
{
try {
if ($this->table !== null) {
$this->db()->statement("DROP TABLE {$this->table}");
}
} finally {
parent::tearDown();
}
}
public function test_scalar_subquery_with_nullable_projection(): void
{
$db = $this->db();
$label = $db->table($this->table)->select('LABEL')->where('ID', 1);
$row = $db->table($this->table)->selectSub($label, 'matched')->where('ID', 2)->first();
$this->assertSame('Alpha', $row->matched);
}
public function test_where_in_with_nullable_projection(): void
{
$db = $this->db();
$labels = $db->table($this->table)->select('LABEL')->where('ID', 2);
$this->assertSame([2], $db->table($this->table)->whereIn('LABEL', $labels)->pluck('ID')->all());
}
public function test_union_with_nullable_projection(): void
{
$db = $this->db();
$query = $db->table($this->table)->select('LABEL')->where('ID', 1)
->unionAll($db->table($this->table)->select('LABEL')->where('ID', 2))
->orderBy('LABEL')->offset(1)->limit(1);
$this->assertSame(['beta'], $query->pluck('LABEL')->all());
}
public function test_exists_returns_true_and_false(): void
{
$this->assertTrue($this->db()->table($this->table)->where('ID', 1)->exists());
$this->assertFalse($this->db()->table($this->table)->where('ID', 4)->exists());
}
public function test_where_like_honors_case_sensitivity(): void
{
$db = $this->db();
$this->assertSame([1], $db->table($this->table)->whereLike('LABEL', 'alpha%')->pluck('ID')->all());
$this->assertSame([], $db->table($this->table)->whereLike('LABEL', 'alpha%', caseSensitive: true)->pluck('ID')->all());
$this->assertSame([2], $db->table($this->table)->whereNotLike('LABEL', 'ALPHA%')->pluck('ID')->all());
}
public function test_random_order_executes_on_db2(): void
{
$this->assertCount(2, $this->db()->table($this->table)->select('ID')->inRandomOrder()->limit(2)->get());
}
}