db2 driver updates

This commit is contained in:
Mark Gregory
2026-11-11 13:18:47 +00:00
parent 76037ff72b
commit e85ab1da7b
46 changed files with 100 additions and 6663 deletions
+2 -5
View File
@@ -3,11 +3,9 @@
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.
@@ -63,6 +61,7 @@ class Db2Connection extends Connection
}
$previousColumn = null;
continue;
}
@@ -107,6 +106,4 @@ class Db2Connection extends Connection
{
return new Db2Processor;
}
}
@@ -1,98 +0,0 @@
<?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;
}
}
@@ -1,107 +0,0 @@
<?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;
}
}
+1 -1
View File
@@ -32,4 +32,4 @@ class Db2Processor extends Processor
return is_numeric($id) ? (int) $id : $id;
}
}
}
+38 -35
View File
@@ -2,9 +2,9 @@
namespace App\Database\Db2;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
use Illuminate\Database\Query\Grammars\Grammar;
class Db2QueryGrammar extends Grammar
{
@@ -24,7 +24,9 @@ class Db2QueryGrammar extends Grammar
];
private array $db2ColumnCache = [];
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
/**
* Compile a Db2 MERGE statement for Laravel upserts.
*/
@@ -68,32 +70,32 @@ class Db2QueryGrammar extends Grammar
$updates[] = "target.{$wrapped} = source.{$wrapped}";
} else {
$updates[] = "target."
. $this->wrap($key)
. " = "
. $this->parameter($value);
$updates[] = 'target.'
.$this->wrap($key)
.' = '
.$this->parameter($value);
}
}
$insertColumns = $this->columnize($columns);
$insertValues = implode(', ', array_map(
fn ($column) => 'source.' . $this->wrap($column),
fn ($column) => 'source.'.$this->wrap($column),
$columns
));
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
. "USING ({$source}) AS source "
. "ON (" . implode(' AND ', $matches) . ") ";
."USING ({$source}) AS source "
.'ON ('.implode(' AND ', $matches).') ';
if ($updates !== []) {
$sql .= "WHEN MATCHED THEN UPDATE SET "
. implode(', ', $updates) . " ";
$sql .= 'WHEN MATCHED THEN UPDATE SET '
.implode(', ', $updates).' ';
}
return $sql
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
. "VALUES ({$insertValues})";
."WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
."VALUES ({$insertValues})";
}
/**
@@ -151,8 +153,8 @@ class Db2QueryGrammar extends Grammar
if ($conditions !== []) {
$uniqueConditions[] = '('
. implode(' AND ', $conditions)
. ')';
.implode(' AND ', $conditions)
.')';
}
}
@@ -165,15 +167,15 @@ class Db2QueryGrammar extends Grammar
$insertColumns = $this->columnize($columns);
$insertValues = implode(', ', array_map(
fn ($column) => 'source.' . $this->wrap($column),
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})";
."USING ({$source}) AS source "
.'ON ('.implode(' OR ', $uniqueConditions).') '
."WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
."VALUES ({$insertValues})";
}
/**
@@ -214,13 +216,13 @@ class Db2QueryGrammar extends Grammar
foreach ($columns as $column) {
$parts[] = $this->parameter($row[$column])
. ' AS '
. $this->wrap($column);
.' AS '
.$this->wrap($column);
}
$selects[] = 'SELECT '
. implode(', ', $parts)
. ' FROM SYSIBM.SYSDUMMY1';
.implode(', ', $parts)
.' FROM SYSIBM.SYSDUMMY1';
}
return implode(' UNION ALL ', $selects);
@@ -231,8 +233,8 @@ class Db2QueryGrammar extends Grammar
*/
public function compileSavepoint($name)
{
return 'SAVEPOINT ' . $name
. ' ON ROLLBACK RETAIN CURSORS';
return 'SAVEPOINT '.$name
.' ON ROLLBACK RETAIN CURSORS';
}
/**
@@ -240,7 +242,7 @@ class Db2QueryGrammar extends Grammar
*/
public function compileSavepointRollBack($name)
{
return 'ROLLBACK TO SAVEPOINT ' . $name;
return 'ROLLBACK TO SAVEPOINT '.$name;
}
protected function compileAggregate($query, $aggregate)
@@ -287,7 +289,7 @@ class Db2QueryGrammar extends Grammar
}
public function compileExists(
\Illuminate\Database\Query\Builder $query
Builder $query
) {
$select = $this->compileSelect($query);
@@ -443,6 +445,7 @@ class Db2QueryGrammar extends Grammar
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
$lobs[] = $selected;
continue;
}
@@ -466,8 +469,8 @@ class Db2QueryGrammar extends Grammar
}
$expression = 'COALESCE('
. $wrapped
. ", CAST('' AS VARCHAR({$length})))";
.$wrapped
.", CAST('' AS VARCHAR({$length})))";
} else {
$formatted = $type === 'TIMESTAMP'
? "VARCHAR_FORMAT({$wrapped}, 'YYYY-MM-DD HH24:MI:SS.FF6')"
@@ -477,24 +480,24 @@ class Db2QueryGrammar extends Grammar
}
$ordinary[] = new Expression(
$expression . ' AS ' . $alias
$expression.' AS '.$alias
);
// Character indicators avoid the PDO_ODBC numeric
// aggregate/binary conversion issue.
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
$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++;
$flagAlias = '__db2_null_flag_'.$indicatorIndex++;
}
$ordinary[] = new Expression(
'CASE WHEN '
. $wrapped
. " IS NULL THEN '1' ELSE '0' END AS "
. $this->wrap($flagAlias)
.$wrapped
." IS NULL THEN '1' ELSE '0' END AS "
.$this->wrap($flagAlias)
);
$hasNullIndicators = true;
@@ -1,258 +0,0 @@
<?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;
}
}
@@ -1,252 +0,0 @@
<?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;
}
}
@@ -1,278 +0,0 @@
<?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;
}
}
@@ -1,436 +0,0 @@
<?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;
}
}
@@ -1,479 +0,0 @@
<?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;
}
}
@@ -1,248 +0,0 @@
<?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);
}
}
@@ -1,496 +0,0 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\Expression;
class Db2QueryGrammar extends Grammar
{
protected $selectComponents = [
'aggregate',
'columns',
'from',
'indexHint',
'joins',
'wheres',
'groups',
'havings',
'orders',
'offset',
'limit',
'lock',
];
private array $db2ColumnCache = [];
public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__';
/**
* Compile a Db2 MERGE statement for Laravel upserts.
*/
public function compileUpsert(
Builder $query,
array $values,
array $uniqueBy,
array $update
) {
$columns = $this->db2MergeColumns($values);
foreach ($uniqueBy as $column) {
if (! in_array($column, $columns, true)) {
throw new \InvalidArgumentException(
"Upsert key is missing from inserted values: {$column}"
);
}
}
$source = $this->db2MergeSource($values, $columns);
$matches = [];
foreach ($uniqueBy as $column) {
$wrapped = $this->wrap($column);
$matches[] = "target.{$wrapped} = source.{$wrapped}";
}
$updates = [];
foreach ($update as $key => $value) {
if (is_int($key)) {
if (! in_array($value, $columns, true)) {
throw new \InvalidArgumentException(
"Unknown upsert update column: {$value}"
);
}
$wrapped = $this->wrap($value);
$updates[] = "target.{$wrapped} = source.{$wrapped}";
} else {
$updates[] = "target."
. $this->wrap($key)
. " = "
. $this->parameter($value);
}
}
$insertColumns = $this->columnize($columns);
$insertValues = implode(', ', array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
));
$sql = "MERGE INTO {$this->wrapTable($query->from)} AS target "
. "USING ({$source}) AS source "
. "ON (" . implode(' AND ', $matches) . ") ";
if ($updates !== []) {
$sql .= "WHEN MATCHED THEN UPDATE SET "
. implode(', ', $updates) . " ";
}
return $sql
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
. "VALUES ({$insertValues})";
}
/**
* Insert rows without replacing existing rows.
*
* Db2 MERGE ignores rows that match the selected key.
*/
public function compileInsertOrIgnore(
Builder $query,
array $values
) {
$columns = $this->db2MergeColumns($values);
$source = $this->db2MergeSource($values, $columns);
$indexes = $this->connection
->getSchemaBuilder()
->getIndexes($query->from);
$uniqueConditions = [];
foreach ($indexes as $index) {
if (! ($index['unique'] ?? false)) {
continue;
}
$indexColumns = $index['columns'] ?? [];
if ($indexColumns === []) {
continue;
}
// A unique key can only be compared if every
// participating column exists in the source.
$conditions = [];
foreach ($indexColumns as $column) {
$matchedColumn = null;
foreach ($columns as $candidate) {
if (strcasecmp($candidate, $column) === 0) {
$matchedColumn = $candidate;
break;
}
}
if ($matchedColumn === null) {
$conditions = [];
break;
}
$wrapped = $this->wrap($matchedColumn);
$conditions[] = "target.{$wrapped} = source.{$wrapped}";
}
if ($conditions !== []) {
$uniqueConditions[] = '('
. implode(' AND ', $conditions)
. ')';
}
}
if ($uniqueConditions === []) {
throw new \RuntimeException(
'Db2 insertOrIgnore requires an applicable unique index.'
);
}
$insertColumns = $this->columnize($columns);
$insertValues = implode(', ', array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
));
return "MERGE INTO {$this->wrapTable($query->from)} AS target "
. "USING ({$source}) AS source "
. "ON (" . implode(' OR ', $uniqueConditions) . ") "
. "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) "
. "VALUES ({$insertValues})";
}
/**
* Validate the column layout of a multi-row MERGE.
*/
private function db2MergeColumns(array $values): array
{
if ($values === []) {
throw new \InvalidArgumentException(
'MERGE requires at least one row.'
);
}
$columns = array_keys(reset($values));
foreach ($values as $row) {
if (array_keys($row) !== $columns) {
throw new \InvalidArgumentException(
'All MERGE rows must contain the same columns.'
);
}
}
return $columns;
}
/**
* Build a parameterized Db2 MERGE source.
*/
private function db2MergeSource(
array $values,
array $columns
): string {
$selects = [];
foreach ($values as $row) {
$parts = [];
foreach ($columns as $column) {
$parts[] = $this->parameter($row[$column])
. ' AS '
. $this->wrap($column);
}
$selects[] = 'SELECT '
. implode(', ', $parts)
. ' FROM SYSIBM.SYSDUMMY1';
}
return implode(' UNION ALL ', $selects);
}
/**
* Compile a Db2 LUW savepoint statement.
*/
public function compileSavepoint($name)
{
return 'SAVEPOINT ' . $name
. ' ON ROLLBACK RETAIN CURSORS';
}
/**
* Compile a Db2 LUW rollback-to-savepoint statement.
*/
public function compileSavepointRollBack($name)
{
return 'ROLLBACK TO SAVEPOINT ' . $name;
}
protected function compileAggregate($query, $aggregate)
{
$column = $this->columnize($aggregate['columns']);
if (is_array($query->distinct)) {
$column = 'distinct '.$this->columnize($query->distinct);
} elseif ($query->distinct && $column !== '*') {
$column = 'distinct '.$column;
}
$function = strtolower($aggregate['function']);
$expression = "{$function}({$column})";
// PDO_ODBC may return Db2 integer aggregates as binary data.
// Cast only the migration batch aggregate to VARCHAR.
if (
$function === 'max' &&
count($aggregate['columns']) === 1 &&
$aggregate['columns'][0] === 'batch' &&
$query->from === 'migrations'
) {
$expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))";
}
return 'select '.$expression.' as "aggregate"';
}
protected function compileLimit($query, $limit)
{
$limit = (int) $limit;
if ((int) ($query->offset ?? 0) > 0) {
return 'fetch next '.$limit.' rows only';
}
return 'fetch first '.$limit.' rows only';
}
protected function compileOffset($query, $offset)
{
return 'offset '.(int) $offset.' rows';
}
public function compileExists(
\Illuminate\Database\Query\Builder $query
) {
$select = $this->compileSelect($query);
return sprintf(
'SELECT CASE WHEN EXISTS (%s) THEN 1 ELSE 0 END AS "exists" FROM SYSIBM.SYSDUMMY1',
$select
);
}
/** A non-NULL value used only for nullable TIMESTAMP result columns. */
public const NULL_TIMESTAMP_SENTINEL = '__DB2_NULL_TIMESTAMP__';
public function compileSelect(\Illuminate\Database\Query\Builder $query)
{
if (
! is_string($query->from) ||
! preg_match(
'/^(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/',
$query->from
) ||
! empty($query->joins) ||
! empty($query->unions) ||
! empty($query->groups) ||
! empty($query->havings) ||
$query->aggregate !== null ||
$query->distinct
) {
return parent::compileSelect($query);
}
$table = $query->from;
if (! isset($this->db2ColumnCache[$table])) {
$this->db2ColumnCache[$table] = $this->connection
->getSchemaBuilder()
->getColumns($table);
}
$metadata = [];
foreach ($this->db2ColumnCache[$table] as $column) {
$metadata[strtolower($column['name'])] = $column;
}
$columns = $query->columns ?? ['*'];
if ($columns === ['*']) {
$columns = array_column(
$this->db2ColumnCache[$table],
'name'
);
}
$parsed = [];
$aliases = [];
// Validate the complete selection before modifying any SQL.
foreach ($columns as $column) {
if (
! is_string($column) ||
! preg_match(
'/^((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?)(?:\s+as\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*))?$/i',
$column,
$matches
)
) {
return parent::compileSelect($query);
}
$identifier = $matches[1];
$parts = explode('.', $identifier);
$name = trim(end($parts), '"');
$alias = isset($matches[2])
? trim($matches[2], '"')
: $name;
$info = $metadata[strtolower($name)] ?? null;
if ($info === null) {
return parent::compileSelect($query);
}
// Reserved indicator aliases must never be user columns.
if (preg_match('/^__db2_null_flag_[0-9]+$/i', $alias)) {
return parent::compileSelect($query);
}
// Duplicate output names cannot be mapped unambiguously.
$aliasKey = strtolower($alias);
if (isset($aliases[$aliasKey])) {
return parent::compileSelect($query);
}
$aliases[$aliasKey] = true;
$parsed[] = [
'original' => $column,
'identifier' => $identifier,
'alias' => $alias,
'info' => $info,
];
}
$ordinary = [];
$lobs = [];
$changed = false;
$indicatorIndex = 0;
$hasNullIndicators = false;
foreach ($parsed as $entry) {
$info = $entry['info'];
$type = strtoupper($info['type_name']);
$nullable = (bool) ($info['nullable'] ?? false);
$selected = $entry['original'];
$wrapped = $this->wrap($entry['identifier']);
$alias = $this->wrap($entry['alias']);
if (in_array($type, ['CLOB', 'BLOB', 'DBCLOB'], true)) {
$lobs[] = $selected;
continue;
}
if (
$nullable &&
in_array(
$type,
['CHAR', 'VARCHAR', 'DATE', 'TIME', 'TIMESTAMP'],
true
)
) {
if (in_array($type, ['CHAR', 'VARCHAR'], true)) {
$length = 1;
if (preg_match(
'/\((\d+)\)/',
$info['type'] ?? '',
$lengthMatch
)) {
$length = max(1, (int) $lengthMatch[1]);
}
$expression = 'COALESCE('
. $wrapped
. ", CAST('' AS VARCHAR({$length})))";
} else {
$expression = 'CASE WHEN '
. $wrapped
. " IS NULL THEN CAST('' AS VARCHAR(32))"
. ' ELSE CAST('
. $wrapped
. ' AS VARCHAR(32)) END';
}
$ordinary[] = new Expression(
$expression . ' AS ' . $alias
);
// Character indicators avoid the PDO_ODBC numeric
// aggregate/binary conversion issue.
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
// Ensure a generated alias cannot collide with any
// requested output column.
while (isset($aliases[strtolower($flagAlias)])) {
$flagAlias = '__db2_null_flag_' . $indicatorIndex++;
}
$ordinary[] = new Expression(
'CASE WHEN '
. $wrapped
. " IS NULL THEN '1' ELSE '0' END AS "
. $this->wrap($flagAlias)
);
$hasNullIndicators = true;
$changed = true;
} else {
$ordinary[] = $selected;
}
}
if ($lobs !== [] && $ordinary !== []) {
$changed = true;
}
if (! $changed) {
return parent::compileSelect($query);
}
$modified = clone $query;
$modified->columns = array_merge($ordinary, $lobs);
$sql = parent::compileSelect($modified);
// Only mark SELECT statements that actually contain
// generated NULL indicator columns.
if ($hasNullIndicators) {
$sql .= ' /* DB2_NULL_FLAGS_V1 */';
}
return $sql;
}
}
@@ -1,496 +0,0 @@
<?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' &&
$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;
}
}
@@ -1,495 +0,0 @@
<?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;
}
}
@@ -1,529 +0,0 @@
<?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;
}
}
+17 -19
View File
@@ -27,7 +27,7 @@ class Db2SchemaBuilder extends Builder
{
$schema = $this->connection->getConfig('schema');
if (!$schema || !preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
if (! $schema || ! preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('A valid Db2 schema is required for db:wipe.');
}
@@ -49,8 +49,8 @@ class Db2SchemaBuilder extends Builder
throw new \RuntimeException('Unable to read Db2 table name.');
}
$qualified = '"' . str_replace('"', '""', $schema) . '"."' .
str_replace('"', '""', trim($name)) . '"';
$qualified = '"'.str_replace('"', '""', $schema).'"."'.
str_replace('"', '""', trim($name)).'"';
$this->connection->statement(
"DROP TABLE {$qualified}"
@@ -58,14 +58,13 @@ class Db2SchemaBuilder extends Builder
}
}
// BEGIN DB2 SCHEMA INSPECTION
private function db2Schema($schema = null)
{
$schema = $schema ?? $this->connection->getConfig('schema');
if (!is_string($schema) || $schema === '') {
if (! is_string($schema) || $schema === '') {
throw new \RuntimeException('Invalid Db2 schema.');
}
@@ -76,12 +75,13 @@ class Db2SchemaBuilder extends Builder
$schema = str_replace('""', '"', $schema);
}
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
if (! preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('Invalid Db2 schema.');
}
return strtoupper($schema);
}
public function getTables($schema = null)
{
$schema = $this->db2Schema($schema);
@@ -102,9 +102,8 @@ class Db2SchemaBuilder extends Builder
return [
'name' => $name,
'schema' => $schema,
'schema_qualified_name' =>
'"' . str_replace('"', '""', $schema) .
'"."' . str_replace('"', '""', $name) . '"',
'schema_qualified_name' => '"'.str_replace('"', '""', $schema).
'"."'.str_replace('"', '""', $name).'"',
'type' => $row->TYPE === 'V' ? 'view' : 'table',
'size' => null,
'engine' => null,
@@ -140,11 +139,11 @@ class Db2SchemaBuilder extends Builder
$type = $typeName === 'CHARACTER' ? 'CHAR' : $typeName;
if (in_array(strtoupper($type), ['VARCHAR', 'CHAR', 'VARGRAPHIC', 'GRAPHIC'])) {
$type .= '(' . (int) $row->LENGTH . ')';
$type .= '('.(int) $row->LENGTH.')';
} elseif (in_array(strtoupper($type), ['DECIMAL', 'NUMERIC'])) {
$type .= '(' . (int) $row->LENGTH . ',' . (int) $row->SCALE . ')';
$type .= '('.(int) $row->LENGTH.','.(int) $row->SCALE.')';
} elseif (strtoupper($type) === 'TIMESTAMP') {
$type .= '(' . (int) $row->SCALE . ')';
$type .= '('.(int) $row->SCALE.')';
}
return [
@@ -167,7 +166,7 @@ class Db2SchemaBuilder extends Builder
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT I.INDNAME, I.UNIQUERULE,
'SELECT I.INDNAME, I.UNIQUERULE,
C.COLNAME, C.COLSEQ
FROM SYSCAT.INDEXES I
JOIN SYSCAT.INDEXCOLUSE C
@@ -175,7 +174,7 @@ class Db2SchemaBuilder extends Builder
AND I.INDNAME = C.INDNAME
WHERE I.TABSCHEMA = ?
AND I.TABNAME = ?
ORDER BY I.INDNAME, C.COLSEQ",
ORDER BY I.INDNAME, C.COLSEQ',
[$schema, $table]
);
@@ -184,7 +183,7 @@ class Db2SchemaBuilder extends Builder
foreach ($rows as $row) {
$name = trim($row->INDNAME);
if (!isset($indexes[$name])) {
if (! isset($indexes[$name])) {
$indexes[$name] = [
'name' => $name,
'columns' => [],
@@ -208,7 +207,7 @@ class Db2SchemaBuilder extends Builder
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT R.CONSTNAME,
'SELECT R.CONSTNAME,
R.REFTABSCHEMA,
R.REFTABNAME,
R.DELETERULE,
@@ -232,7 +231,7 @@ class Db2SchemaBuilder extends Builder
AND RK.COLSEQ = K.COLSEQ
WHERE R.TABSCHEMA = ?
AND R.TABNAME = ?
ORDER BY R.CONSTNAME, K.COLSEQ",
ORDER BY R.CONSTNAME, K.COLSEQ',
[$schema, $table]
);
@@ -242,7 +241,7 @@ class Db2SchemaBuilder extends Builder
foreach ($rows as $row) {
$name = trim($row->CONSTNAME);
if (!isset($foreignKeys[$name])) {
if (! isset($foreignKeys[$name])) {
$foreignKeys[$name] = [
'name' => $name,
'columns' => [],
@@ -278,5 +277,4 @@ class Db2SchemaBuilder extends Builder
trim($name, '"'),
];
}
}
@@ -1,277 +0,0 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Builder;
class Db2SchemaBuilder extends Builder
{
public function hasTable($table)
{
[$schema, $table] = $this->parseDb2TableName($table);
$schema ??= $this->connection->getConfig('schema');
$result = $this->connection->selectOne(
'SELECT COUNT(*) AS CNT
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TABNAME = ?',
[strtoupper($schema), $table]
);
return (int) $result->CNT > 0;
}
public function dropAllTables()
{
$schema = $this->connection->getConfig('schema');
if (!$schema || !preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('A valid Db2 schema is required for db:wipe.');
}
$schema = strtoupper($schema);
$tables = $this->connection->select(
"SELECT TABNAME
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE = 'T'
ORDER BY TABNAME",
[$schema]
);
foreach ($tables as $table) {
$name = $table->TABNAME ?? $table->tabname ?? null;
if ($name === null) {
throw new \RuntimeException('Unable to read Db2 table name.');
}
$qualified = '"' . str_replace('"', '""', $schema) . '"."' .
str_replace('"', '""', trim($name)) . '"';
$this->connection->statement(
"DROP TABLE {$qualified}"
);
}
}
// BEGIN DB2 SCHEMA INSPECTION
private function db2Schema($schema = null)
{
$schema = $schema ?? $this->connection->getConfig('schema');
if (!is_string($schema) || $schema === '') {
throw new \RuntimeException('Invalid Db2 schema.');
}
$schema = trim($schema);
if (str_starts_with($schema, '"') && str_ends_with($schema, '"')) {
$schema = substr($schema, 1, -1);
$schema = str_replace('""', '"', $schema);
}
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('Invalid Db2 schema.');
}
return strtoupper($schema);
}
public function getTables($schema = null)
{
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT TABSCHEMA, TABNAME, TYPE
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE IN ('T', 'V')
ORDER BY TABNAME",
[$schema]
);
return array_map(static function ($row) {
$name = trim($row->TABNAME);
$schema = trim($row->TABSCHEMA);
return [
'name' => $name,
'schema' => $schema,
'schema_qualified_name' =>
'"' . str_replace('"', '""', $schema) .
'"."' . str_replace('"', '""', $name) . '"',
'type' => $row->TYPE === 'V' ? 'view' : 'table',
'size' => null,
'engine' => null,
'collation' => null,
'comment' => null,
];
}, $rows);
}
public function getColumns($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
// Remove identifier quotes while preserving lowercase names.
$table = trim($table, '"');
$table = str_replace('""', '"', $table);
$rows = $this->connection->select(
"SELECT COLNAME, TYPENAME, LENGTH, SCALE,
NULLS, IDENTITY, COLNO
FROM SYSCAT.COLUMNS
WHERE TABSCHEMA = ?
AND TABNAME = ?
ORDER BY COLNO",
[$schema, $table]
);
return array_map(static function ($row) {
$type = trim($row->TYPENAME);
if (in_array(strtoupper($type), ['VARCHAR', 'CHAR', 'VARGRAPHIC', 'GRAPHIC'])) {
$type .= '(' . (int) $row->LENGTH . ')';
} elseif (in_array(strtoupper($type), ['DECIMAL', 'NUMERIC'])) {
$type .= '(' . (int) $row->LENGTH . ',' . (int) $row->SCALE . ')';
}
return [
'name' => trim($row->COLNAME),
'type_name' => trim($row->TYPENAME),
'type' => $type,
'collation' => null,
'nullable' => trim($row->NULLS) === 'Y',
'default' => null,
'auto_increment' => trim($row->IDENTITY) === 'Y',
'comment' => null,
'generation' => null,
];
}, $rows);
}
public function getIndexes($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT I.INDNAME, I.UNIQUERULE,
C.COLNAME, C.COLSEQ
FROM SYSCAT.INDEXES I
JOIN SYSCAT.INDEXCOLUSE C
ON I.INDSCHEMA = C.INDSCHEMA
AND I.INDNAME = C.INDNAME
WHERE I.TABSCHEMA = ?
AND I.TABNAME = ?
ORDER BY I.INDNAME, C.COLSEQ",
[$schema, $table]
);
$indexes = [];
foreach ($rows as $row) {
$name = trim($row->INDNAME);
if (!isset($indexes[$name])) {
$indexes[$name] = [
'name' => $name,
'columns' => [],
'type' => 'btree',
'unique' => in_array(
$row->UNIQUERULE, ['P', 'U'], true
),
'primary' => $row->UNIQUERULE === 'P',
];
}
$indexes[$name]['columns'][] = trim($row->COLNAME);
}
return array_values($indexes);
}
public function getForeignKeys($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT R.CONSTNAME,
R.REFTABSCHEMA,
R.REFTABNAME,
R.DELETERULE,
R.UPDATERULE,
K.COLNAME,
K.COLSEQ,
RK.COLNAME AS REFCOLNAME
FROM SYSCAT.REFERENCES R
JOIN SYSCAT.KEYCOLUSE K
ON R.TABSCHEMA = K.TABSCHEMA
AND R.TABNAME = K.TABNAME
AND R.CONSTNAME = K.CONSTNAME
JOIN SYSCAT.TABCONST TC
ON TC.TABSCHEMA = R.REFTABSCHEMA
AND TC.TABNAME = R.REFTABNAME
AND TC.TYPE = 'P'
JOIN SYSCAT.KEYCOLUSE RK
ON RK.TABSCHEMA = TC.TABSCHEMA
AND RK.TABNAME = TC.TABNAME
AND RK.CONSTNAME = TC.CONSTNAME
AND RK.COLSEQ = K.COLSEQ
WHERE R.TABSCHEMA = ?
AND R.TABNAME = ?
ORDER BY R.CONSTNAME, K.COLSEQ",
[$schema, $table]
);
$foreignKeys = [];
foreach ($rows as $row) {
$name = trim($row->CONSTNAME);
if (!isset($foreignKeys[$name])) {
$foreignKeys[$name] = [
'name' => $name,
'columns' => [],
'foreign_schema' => trim($row->REFTABSCHEMA),
'foreign_table' => trim($row->REFTABNAME),
'foreign_columns' => [],
'on_update' => trim($row->UPDATERULE),
'on_delete' => trim($row->DELETERULE),
];
}
$foreignKeys[$name]['columns'][] = trim($row->COLNAME);
$foreignKeys[$name]['foreign_columns'][] =
trim($row->REFCOLNAME);
}
return array_values($foreignKeys);
}
private function parseDb2TableName(string $table): array
{
if (preg_match('/^"((?:[^"]|"")*)"\."((?:[^"]|"")*)"$/', $table, $matches)) {
return [
str_replace('""', '"', $matches[1]),
str_replace('""', '"', $matches[2]),
];
}
[$schema, $name] = $this->parseSchemaAndTable($table);
return [
$schema === null ? null : trim($schema, '"'),
trim($name, '"'),
];
}
}
@@ -1,279 +0,0 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Builder;
class Db2SchemaBuilder extends Builder
{
public function hasTable($table)
{
[$schema, $table] = $this->parseDb2TableName($table);
$schema ??= $this->connection->getConfig('schema');
$result = $this->connection->selectOne(
'SELECT COUNT(*) AS CNT
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TABNAME = ?',
[strtoupper($schema), $table]
);
return (int) $result->CNT > 0;
}
public function dropAllTables()
{
$schema = $this->connection->getConfig('schema');
if (!$schema || !preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('A valid Db2 schema is required for db:wipe.');
}
$schema = strtoupper($schema);
$tables = $this->connection->select(
"SELECT TABNAME
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE = 'T'
ORDER BY TABNAME",
[$schema]
);
foreach ($tables as $table) {
$name = $table->TABNAME ?? $table->tabname ?? null;
if ($name === null) {
throw new \RuntimeException('Unable to read Db2 table name.');
}
$qualified = '"' . str_replace('"', '""', $schema) . '"."' .
str_replace('"', '""', trim($name)) . '"';
$this->connection->statement(
"DROP TABLE {$qualified}"
);
}
}
// BEGIN DB2 SCHEMA INSPECTION
private function db2Schema($schema = null)
{
$schema = $schema ?? $this->connection->getConfig('schema');
if (!is_string($schema) || $schema === '') {
throw new \RuntimeException('Invalid Db2 schema.');
}
$schema = trim($schema);
if (str_starts_with($schema, '"') && str_ends_with($schema, '"')) {
$schema = substr($schema, 1, -1);
$schema = str_replace('""', '"', $schema);
}
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('Invalid Db2 schema.');
}
return strtoupper($schema);
}
public function getTables($schema = null)
{
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT TABSCHEMA, TABNAME, TYPE
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE IN ('T', 'V')
ORDER BY TABNAME",
[$schema]
);
return array_map(static function ($row) {
$name = trim($row->TABNAME);
$schema = trim($row->TABSCHEMA);
return [
'name' => $name,
'schema' => $schema,
'schema_qualified_name' =>
'"' . str_replace('"', '""', $schema) .
'"."' . str_replace('"', '""', $name) . '"',
'type' => $row->TYPE === 'V' ? 'view' : 'table',
'size' => null,
'engine' => null,
'collation' => null,
'comment' => null,
];
}, $rows);
}
public function getColumns($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
// Remove identifier quotes while preserving lowercase names.
$table = trim($table, '"');
$table = str_replace('""', '"', $table);
$rows = $this->connection->select(
"SELECT COLNAME, TYPENAME, LENGTH, SCALE,
NULLS, IDENTITY, COLNO, \"DEFAULT\" AS COLDEFAULT, REMARKS,
CASE WHEN \"DEFAULT\" IS NULL THEN 1 ELSE 0 END AS NO_DEFAULT
FROM SYSCAT.COLUMNS
WHERE TABSCHEMA = ?
AND TABNAME = ?
ORDER BY COLNO",
[$schema, $table]
);
return array_map(static function ($row) {
$type = trim($row->TYPENAME);
if (in_array(strtoupper($type), ['VARCHAR', 'CHAR', 'VARGRAPHIC', 'GRAPHIC'])) {
$type .= '(' . (int) $row->LENGTH . ')';
} elseif (in_array(strtoupper($type), ['DECIMAL', 'NUMERIC'])) {
$type .= '(' . (int) $row->LENGTH . ',' . (int) $row->SCALE . ')';
}
return [
'name' => trim($row->COLNAME),
'type_name' => trim($row->TYPENAME),
'type' => $type,
'collation' => null,
'nullable' => trim($row->NULLS) === 'Y',
'default' => (int) $row->NO_DEFAULT === 1 ? null : trim($row->COLDEFAULT),
'auto_increment' => trim($row->IDENTITY) === 'Y',
'comment' => null,
'generation' => null,
];
}, $rows);
}
public function getIndexes($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT I.INDNAME, I.UNIQUERULE,
C.COLNAME, C.COLSEQ
FROM SYSCAT.INDEXES I
JOIN SYSCAT.INDEXCOLUSE C
ON I.INDSCHEMA = C.INDSCHEMA
AND I.INDNAME = C.INDNAME
WHERE I.TABSCHEMA = ?
AND I.TABNAME = ?
ORDER BY I.INDNAME, C.COLSEQ",
[$schema, $table]
);
$indexes = [];
foreach ($rows as $row) {
$name = trim($row->INDNAME);
if (!isset($indexes[$name])) {
$indexes[$name] = [
'name' => $name,
'columns' => [],
'type' => 'btree',
'unique' => in_array(
$row->UNIQUERULE, ['P', 'U'], true
),
'primary' => $row->UNIQUERULE === 'P',
];
}
$indexes[$name]['columns'][] = trim($row->COLNAME);
}
return array_values($indexes);
}
public function getForeignKeys($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT R.CONSTNAME,
R.REFTABSCHEMA,
R.REFTABNAME,
R.DELETERULE,
R.UPDATERULE,
K.COLNAME,
K.COLSEQ,
RK.COLNAME AS REFCOLNAME
FROM SYSCAT.REFERENCES R
JOIN SYSCAT.KEYCOLUSE K
ON R.TABSCHEMA = K.TABSCHEMA
AND R.TABNAME = K.TABNAME
AND R.CONSTNAME = K.CONSTNAME
JOIN SYSCAT.TABCONST TC
ON TC.TABSCHEMA = R.REFTABSCHEMA
AND TC.TABNAME = R.REFTABNAME
AND TC.CONSTNAME = R.REFKEYNAME
JOIN SYSCAT.KEYCOLUSE RK
ON RK.TABSCHEMA = TC.TABSCHEMA
AND RK.TABNAME = TC.TABNAME
AND RK.CONSTNAME = TC.CONSTNAME
AND RK.COLSEQ = K.COLSEQ
WHERE R.TABSCHEMA = ?
AND R.TABNAME = ?
ORDER BY R.CONSTNAME, K.COLSEQ",
[$schema, $table]
);
$rules = ['A' => 'no action', 'C' => 'cascade', 'N' => 'set null', 'R' => 'restrict'];
$foreignKeys = [];
foreach ($rows as $row) {
$name = trim($row->CONSTNAME);
if (!isset($foreignKeys[$name])) {
$foreignKeys[$name] = [
'name' => $name,
'columns' => [],
'foreign_schema' => trim($row->REFTABSCHEMA),
'foreign_table' => trim($row->REFTABNAME),
'foreign_columns' => [],
'on_update' => $rules[trim($row->UPDATERULE)] ?? trim($row->UPDATERULE),
'on_delete' => $rules[trim($row->DELETERULE)] ?? trim($row->DELETERULE),
];
}
$foreignKeys[$name]['columns'][] = trim($row->COLNAME);
$foreignKeys[$name]['foreign_columns'][] =
trim($row->REFCOLNAME);
}
return array_values($foreignKeys);
}
private function parseDb2TableName(string $table): array
{
if (preg_match('/^"((?:[^"]|"")*)"\."((?:[^"]|"")*)"$/', $table, $matches)) {
return [
str_replace('""', '"', $matches[1]),
str_replace('""', '"', $matches[2]),
];
}
[$schema, $name] = $this->parseSchemaAndTable($table);
return [
$schema === null ? null : trim($schema, '"'),
trim($name, '"'),
];
}
}
@@ -1,279 +0,0 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Builder;
class Db2SchemaBuilder extends Builder
{
public function hasTable($table)
{
[$schema, $table] = $this->parseDb2TableName($table);
$schema ??= $this->connection->getConfig('schema');
$result = $this->connection->selectOne(
'SELECT COUNT(*) AS CNT
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TABNAME = ?',
[strtoupper($schema), $table]
);
return (int) $result->CNT > 0;
}
public function dropAllTables()
{
$schema = $this->connection->getConfig('schema');
if (!$schema || !preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('A valid Db2 schema is required for db:wipe.');
}
$schema = strtoupper($schema);
$tables = $this->connection->select(
"SELECT TABNAME
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE = 'T'
ORDER BY TABNAME",
[$schema]
);
foreach ($tables as $table) {
$name = $table->TABNAME ?? $table->tabname ?? null;
if ($name === null) {
throw new \RuntimeException('Unable to read Db2 table name.');
}
$qualified = '"' . str_replace('"', '""', $schema) . '"."' .
str_replace('"', '""', trim($name)) . '"';
$this->connection->statement(
"DROP TABLE {$qualified}"
);
}
}
// BEGIN DB2 SCHEMA INSPECTION
private function db2Schema($schema = null)
{
$schema = $schema ?? $this->connection->getConfig('schema');
if (!is_string($schema) || $schema === '') {
throw new \RuntimeException('Invalid Db2 schema.');
}
$schema = trim($schema);
if (str_starts_with($schema, '"') && str_ends_with($schema, '"')) {
$schema = substr($schema, 1, -1);
$schema = str_replace('""', '"', $schema);
}
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('Invalid Db2 schema.');
}
return strtoupper($schema);
}
public function getTables($schema = null)
{
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT TABSCHEMA, TABNAME, TYPE
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE IN ('T', 'V')
ORDER BY TABNAME",
[$schema]
);
return array_map(static function ($row) {
$name = trim($row->TABNAME);
$schema = trim($row->TABSCHEMA);
return [
'name' => $name,
'schema' => $schema,
'schema_qualified_name' =>
'"' . str_replace('"', '""', $schema) .
'"."' . str_replace('"', '""', $name) . '"',
'type' => $row->TYPE === 'V' ? 'view' : 'table',
'size' => null,
'engine' => null,
'collation' => null,
'comment' => null,
];
}, $rows);
}
public function getColumns($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
// Remove identifier quotes while preserving lowercase names.
$table = trim($table, '"');
$table = str_replace('""', '"', $table);
$rows = $this->connection->select(
"SELECT COLNAME, TYPENAME, LENGTH, SCALE,
NULLS, IDENTITY, COLNO, CAST(COALESCE(\"DEFAULT\", '') AS VARCHAR(4096)) AS COLDEFAULT,
CASE WHEN \"DEFAULT\" IS NULL THEN 'Y' ELSE 'N' END AS NO_DEFAULT
FROM SYSCAT.COLUMNS
WHERE TABSCHEMA = ?
AND TABNAME = ?
ORDER BY COLNO",
[$schema, $table]
);
return array_map(static function ($row) {
$type = trim($row->TYPENAME);
if (in_array(strtoupper($type), ['VARCHAR', 'CHAR', 'VARGRAPHIC', 'GRAPHIC'])) {
$type .= '(' . (int) $row->LENGTH . ')';
} elseif (in_array(strtoupper($type), ['DECIMAL', 'NUMERIC'])) {
$type .= '(' . (int) $row->LENGTH . ',' . (int) $row->SCALE . ')';
}
return [
'name' => trim($row->COLNAME),
'type_name' => trim($row->TYPENAME),
'type' => $type,
'collation' => null,
'nullable' => trim($row->NULLS) === 'Y',
'default' => $row->NO_DEFAULT === 'Y' ? null : trim($row->COLDEFAULT),
'auto_increment' => trim($row->IDENTITY) === 'Y',
'comment' => null,
'generation' => null,
];
}, $rows);
}
public function getIndexes($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT I.INDNAME, I.UNIQUERULE,
C.COLNAME, C.COLSEQ
FROM SYSCAT.INDEXES I
JOIN SYSCAT.INDEXCOLUSE C
ON I.INDSCHEMA = C.INDSCHEMA
AND I.INDNAME = C.INDNAME
WHERE I.TABSCHEMA = ?
AND I.TABNAME = ?
ORDER BY I.INDNAME, C.COLSEQ",
[$schema, $table]
);
$indexes = [];
foreach ($rows as $row) {
$name = trim($row->INDNAME);
if (!isset($indexes[$name])) {
$indexes[$name] = [
'name' => $name,
'columns' => [],
'type' => 'btree',
'unique' => in_array(
$row->UNIQUERULE, ['P', 'U'], true
),
'primary' => $row->UNIQUERULE === 'P',
];
}
$indexes[$name]['columns'][] = trim($row->COLNAME);
}
return array_values($indexes);
}
public function getForeignKeys($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT R.CONSTNAME,
R.REFTABSCHEMA,
R.REFTABNAME,
R.DELETERULE,
R.UPDATERULE,
K.COLNAME,
K.COLSEQ,
RK.COLNAME AS REFCOLNAME
FROM SYSCAT.REFERENCES R
JOIN SYSCAT.KEYCOLUSE K
ON R.TABSCHEMA = K.TABSCHEMA
AND R.TABNAME = K.TABNAME
AND R.CONSTNAME = K.CONSTNAME
JOIN SYSCAT.TABCONST TC
ON TC.TABSCHEMA = R.REFTABSCHEMA
AND TC.TABNAME = R.REFTABNAME
AND TC.CONSTNAME = R.REFKEYNAME
JOIN SYSCAT.KEYCOLUSE RK
ON RK.TABSCHEMA = TC.TABSCHEMA
AND RK.TABNAME = TC.TABNAME
AND RK.CONSTNAME = TC.CONSTNAME
AND RK.COLSEQ = K.COLSEQ
WHERE R.TABSCHEMA = ?
AND R.TABNAME = ?
ORDER BY R.CONSTNAME, K.COLSEQ",
[$schema, $table]
);
$rules = ['A' => 'no action', 'C' => 'cascade', 'N' => 'set null', 'R' => 'restrict'];
$foreignKeys = [];
foreach ($rows as $row) {
$name = trim($row->CONSTNAME);
if (!isset($foreignKeys[$name])) {
$foreignKeys[$name] = [
'name' => $name,
'columns' => [],
'foreign_schema' => trim($row->REFTABSCHEMA),
'foreign_table' => trim($row->REFTABNAME),
'foreign_columns' => [],
'on_update' => $rules[trim($row->UPDATERULE)] ?? trim($row->UPDATERULE),
'on_delete' => $rules[trim($row->DELETERULE)] ?? trim($row->DELETERULE),
];
}
$foreignKeys[$name]['columns'][] = trim($row->COLNAME);
$foreignKeys[$name]['foreign_columns'][] =
trim($row->REFCOLNAME);
}
return array_values($foreignKeys);
}
private function parseDb2TableName(string $table): array
{
if (preg_match('/^"((?:[^"]|"")*)"\."((?:[^"]|"")*)"$/', $table, $matches)) {
return [
str_replace('""', '"', $matches[1]),
str_replace('""', '"', $matches[2]),
];
}
[$schema, $name] = $this->parseSchemaAndTable($table);
return [
$schema === null ? null : trim($schema, '"'),
trim($name, '"'),
];
}
}
@@ -1,281 +0,0 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Builder;
class Db2SchemaBuilder extends Builder
{
public function hasTable($table)
{
[$schema, $table] = $this->parseDb2TableName($table);
$schema ??= $this->connection->getConfig('schema');
$result = $this->connection->selectOne(
'SELECT COUNT(*) AS CNT
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TABNAME = ?',
[strtoupper($schema), $table]
);
return (int) $result->CNT > 0;
}
public function dropAllTables()
{
$schema = $this->connection->getConfig('schema');
if (!$schema || !preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('A valid Db2 schema is required for db:wipe.');
}
$schema = strtoupper($schema);
$tables = $this->connection->select(
"SELECT TABNAME
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE = 'T'
ORDER BY TABNAME",
[$schema]
);
foreach ($tables as $table) {
$name = $table->TABNAME ?? $table->tabname ?? null;
if ($name === null) {
throw new \RuntimeException('Unable to read Db2 table name.');
}
$qualified = '"' . str_replace('"', '""', $schema) . '"."' .
str_replace('"', '""', trim($name)) . '"';
$this->connection->statement(
"DROP TABLE {$qualified}"
);
}
}
// BEGIN DB2 SCHEMA INSPECTION
private function db2Schema($schema = null)
{
$schema = $schema ?? $this->connection->getConfig('schema');
if (!is_string($schema) || $schema === '') {
throw new \RuntimeException('Invalid Db2 schema.');
}
$schema = trim($schema);
if (str_starts_with($schema, '"') && str_ends_with($schema, '"')) {
$schema = substr($schema, 1, -1);
$schema = str_replace('""', '"', $schema);
}
if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', $schema)) {
throw new \RuntimeException('Invalid Db2 schema.');
}
return strtoupper($schema);
}
public function getTables($schema = null)
{
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT TABSCHEMA, TABNAME, TYPE
FROM SYSCAT.TABLES
WHERE TABSCHEMA = ?
AND TYPE IN ('T', 'V')
ORDER BY TABNAME",
[$schema]
);
return array_map(static function ($row) {
$name = trim($row->TABNAME);
$schema = trim($row->TABSCHEMA);
return [
'name' => $name,
'schema' => $schema,
'schema_qualified_name' =>
'"' . str_replace('"', '""', $schema) .
'"."' . str_replace('"', '""', $name) . '"',
'type' => $row->TYPE === 'V' ? 'view' : 'table',
'size' => null,
'engine' => null,
'collation' => null,
'comment' => null,
];
}, $rows);
}
public function getColumns($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
// Remove identifier quotes while preserving lowercase names.
$table = trim($table, '"');
$table = str_replace('""', '"', $table);
$rows = $this->connection->select(
"SELECT COLNAME, TYPENAME, LENGTH, SCALE,
NULLS, IDENTITY, COLNO, CAST(COALESCE(\"DEFAULT\", '') AS VARCHAR(4096)) AS COLDEFAULT,
CASE WHEN \"DEFAULT\" IS NULL THEN 'Y' ELSE 'N' END AS NO_DEFAULT
FROM SYSCAT.COLUMNS
WHERE TABSCHEMA = ?
AND TABNAME = ?
ORDER BY COLNO",
[$schema, $table]
);
return array_map(static function ($row) {
$type = trim($row->TYPENAME);
if (in_array(strtoupper($type), ['VARCHAR', 'CHAR', 'VARGRAPHIC', 'GRAPHIC'])) {
$type .= '(' . (int) $row->LENGTH . ')';
} elseif (in_array(strtoupper($type), ['DECIMAL', 'NUMERIC'])) {
$type .= '(' . (int) $row->LENGTH . ',' . (int) $row->SCALE . ')';
} elseif (strtoupper($type) === 'TIMESTAMP') {
$type .= '(' . (int) $row->SCALE . ')';
}
return [
'name' => trim($row->COLNAME),
'type_name' => trim($row->TYPENAME),
'type' => $type,
'collation' => null,
'nullable' => trim($row->NULLS) === 'Y',
'default' => $row->NO_DEFAULT === 'Y' ? null : trim($row->COLDEFAULT),
'auto_increment' => trim($row->IDENTITY) === 'Y',
'comment' => null,
'generation' => null,
];
}, $rows);
}
public function getIndexes($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT I.INDNAME, I.UNIQUERULE,
C.COLNAME, C.COLSEQ
FROM SYSCAT.INDEXES I
JOIN SYSCAT.INDEXCOLUSE C
ON I.INDSCHEMA = C.INDSCHEMA
AND I.INDNAME = C.INDNAME
WHERE I.TABSCHEMA = ?
AND I.TABNAME = ?
ORDER BY I.INDNAME, C.COLSEQ",
[$schema, $table]
);
$indexes = [];
foreach ($rows as $row) {
$name = trim($row->INDNAME);
if (!isset($indexes[$name])) {
$indexes[$name] = [
'name' => $name,
'columns' => [],
'type' => 'btree',
'unique' => in_array(
$row->UNIQUERULE, ['P', 'U'], true
),
'primary' => $row->UNIQUERULE === 'P',
];
}
$indexes[$name]['columns'][] = trim($row->COLNAME);
}
return array_values($indexes);
}
public function getForeignKeys($table)
{
[$schema, $table] = $this->parseSchemaAndTable($table);
$schema = $this->db2Schema($schema);
$rows = $this->connection->select(
"SELECT R.CONSTNAME,
R.REFTABSCHEMA,
R.REFTABNAME,
R.DELETERULE,
R.UPDATERULE,
K.COLNAME,
K.COLSEQ,
RK.COLNAME AS REFCOLNAME
FROM SYSCAT.REFERENCES R
JOIN SYSCAT.KEYCOLUSE K
ON R.TABSCHEMA = K.TABSCHEMA
AND R.TABNAME = K.TABNAME
AND R.CONSTNAME = K.CONSTNAME
JOIN SYSCAT.TABCONST TC
ON TC.TABSCHEMA = R.REFTABSCHEMA
AND TC.TABNAME = R.REFTABNAME
AND TC.CONSTNAME = R.REFKEYNAME
JOIN SYSCAT.KEYCOLUSE RK
ON RK.TABSCHEMA = TC.TABSCHEMA
AND RK.TABNAME = TC.TABNAME
AND RK.CONSTNAME = TC.CONSTNAME
AND RK.COLSEQ = K.COLSEQ
WHERE R.TABSCHEMA = ?
AND R.TABNAME = ?
ORDER BY R.CONSTNAME, K.COLSEQ",
[$schema, $table]
);
$rules = ['A' => 'no action', 'C' => 'cascade', 'N' => 'set null', 'R' => 'restrict'];
$foreignKeys = [];
foreach ($rows as $row) {
$name = trim($row->CONSTNAME);
if (!isset($foreignKeys[$name])) {
$foreignKeys[$name] = [
'name' => $name,
'columns' => [],
'foreign_schema' => trim($row->REFTABSCHEMA),
'foreign_table' => trim($row->REFTABNAME),
'foreign_columns' => [],
'on_update' => $rules[trim($row->UPDATERULE)] ?? trim($row->UPDATERULE),
'on_delete' => $rules[trim($row->DELETERULE)] ?? trim($row->DELETERULE),
];
}
$foreignKeys[$name]['columns'][] = trim($row->COLNAME);
$foreignKeys[$name]['foreign_columns'][] =
trim($row->REFCOLNAME);
}
return array_values($foreignKeys);
}
private function parseDb2TableName(string $table): array
{
if (preg_match('/^"((?:[^"]|"")*)"\."((?:[^"]|"")*)"$/', $table, $matches)) {
return [
str_replace('""', '"', $matches[1]),
str_replace('""', '"', $matches[2]),
];
}
[$schema, $name] = $this->parseSchemaAndTable($table);
return [
$schema === null ? null : trim($schema, '"'),
trim($name, '"'),
];
}
}
+14 -12
View File
@@ -2,8 +2,10 @@
namespace App\Database\Db2;
use Illuminate\Database\Schema\Grammars\Grammar;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\ColumnDefinition;
use Illuminate\Database\Schema\Grammars\Grammar;
use Illuminate\Support\Fluent;
class Db2SchemaGrammar extends Grammar
@@ -180,7 +182,7 @@ class Db2SchemaGrammar extends Grammar
protected function typeString(Fluent $column)
{
return 'VARCHAR(' . ($column->length ?: 255) . ')';
return 'VARCHAR('.($column->length ?: 255).')';
}
protected function typeChar(Fluent $column)
@@ -281,30 +283,30 @@ class Db2SchemaGrammar extends Grammar
);
}
protected function typeJson(\Illuminate\Database\Schema\ColumnDefinition $column)
protected function typeJson(ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeJsonb(\Illuminate\Database\Schema\ColumnDefinition $column)
protected function typeJsonb(ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeTinyText(\Illuminate\Database\Schema\ColumnDefinition $column)
protected function typeTinyText(ColumnDefinition $column)
{
return 'VARCHAR(255)';
}
public function compileInsertOrIgnore(
\Illuminate\Database\Query\Builder $query,
Builder $query,
array $values
) {
if (empty($values)) {
return '';
}
if (!is_array(reset($values))) {
if (! is_array(reset($values))) {
$values = [$values];
}
@@ -320,10 +322,10 @@ class Db2SchemaGrammar extends Grammar
$rows = [];
foreach ($values as $row) {
$rows[] = '(' . implode(
', ',
array_fill(0, count($columns), '?')
) . ')';
$rows[] = '('.implode(
', ',
array_fill(0, count($columns), '?')
).')';
}
$source = implode(', ', $rows);
@@ -351,7 +353,7 @@ class Db2SchemaGrammar extends Grammar
implode(
', ',
array_map(
fn ($column) => 'source.' . $this->wrap($column),
fn ($column) => 'source.'.$this->wrap($column),
$columns
)
)
@@ -1,227 +0,0 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Grammars\Grammar;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Fluent;
class Db2SchemaGrammar extends Grammar
{
protected $modifiers = ['Nullable', 'Default'];
public function compileCreate(Blueprint $blueprint, Fluent $command)
{
$columns = [];
$primaryKeys = [];
foreach ($blueprint->getAddedColumns() as $column) {
$sql = $this->wrap($column) . ' ' . $this->getType($column);
if ($column->autoIncrement) {
$sql .= ' GENERATED BY DEFAULT AS IDENTITY';
// Laravel's $table->id() does not explicitly
// set the primary attribute.
$primaryKeys[] = $column->name;
}
$sql .= $column->nullable ? '' : ' NOT NULL';
if (!is_null($column->default)) {
$sql .= ' DEFAULT ' . $this->getDefaultValue($column->default);
}
$columns[] = $sql;
}
// Db2 identity columns are not automatically primary keys.
if (!empty($primaryKeys)) {
$columns[] = sprintf(
'PRIMARY KEY (%s)',
$this->columnize($primaryKeys)
);
}
return sprintf(
'CREATE TABLE %s (%s)',
$this->wrapTable($blueprint),
implode(', ', $columns)
);
}
protected function typeBigInteger(Fluent $column)
{
return 'BIGINT';
}
protected function typeInteger(Fluent $column)
{
return 'INTEGER';
}
protected function typeSmallInteger(Fluent $column)
{
return 'SMALLINT';
}
protected function typeString(Fluent $column)
{
return 'VARCHAR(' . ($column->length ?: 255) . ')';
}
protected function typeText(Fluent $column)
{
return 'CLOB(1M)';
}
protected function typeLongText(Fluent $column)
{
return 'CLOB(2M)';
}
protected function typeBoolean(Fluent $column)
{
return 'SMALLINT';
}
protected function typeTimestamp(Fluent $column)
{
return 'TIMESTAMP';
}
protected function typeDateTime(Fluent $column)
{
return 'TIMESTAMP';
}
protected function typeDate(Fluent $column)
{
return 'DATE';
}
protected function typeBinary(Fluent $column)
{
return 'BLOB(1M)';
}
protected function typeDecimal(Fluent $column)
{
return sprintf(
'DECIMAL(%d,%d)',
$column->total ?? 8,
$column->places ?? 2
);
}
public function compilePrimary(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'ALTER TABLE %s ADD PRIMARY KEY (%s)',
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
protected function typeMediumText(Fluent $column)
{
return 'CLOB(16M)';
}
public function compileUnique(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'CREATE UNIQUE INDEX %s ON %s (%s)',
$this->wrap($command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
public function compileIndex(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'CREATE INDEX %s ON %s (%s)',
$this->wrap($command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
protected function typeJson(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeJsonb(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeTinyText(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'VARCHAR(255)';
}
public function compileInsertOrIgnore(
\Illuminate\Database\Query\Builder $query,
array $values
) {
if (empty($values)) {
return '';
}
if (!is_array(reset($values))) {
$values = [$values];
}
$columns = array_keys(reset($values));
$table = $this->wrapTable($query->from);
$sourceColumns = implode(
', ',
array_map(fn ($column) => $this->wrap($column), $columns)
);
$rows = [];
foreach ($values as $row) {
$rows[] = '(' . implode(
', ',
array_fill(0, count($columns), '?')
) . ')';
}
$source = implode(', ', $rows);
$conditions = [];
foreach ($columns as $column) {
$wrapped = $this->wrap($column);
$conditions[] = "target.$wrapped = source.$wrapped";
}
return sprintf(
'MERGE INTO %s AS target
USING (VALUES %s) AS source (%s)
ON %s
WHEN NOT MATCHED THEN
INSERT (%s)
VALUES (%s)',
$table,
$source,
$sourceColumns,
implode(' AND ', $conditions),
$sourceColumns,
implode(
', ',
array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
)
)
);
}
}
@@ -1,330 +0,0 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Grammars\Grammar;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Fluent;
class Db2SchemaGrammar extends Grammar
{
protected $modifiers = ['Nullable', 'Default'];
public function compileCreate(Blueprint $blueprint, Fluent $command)
{
$columns = [];
$primaryKeys = [];
foreach ($blueprint->getAddedColumns() as $column) {
$columns[] = $this->columnDefinition($column);
if ($column->autoIncrement) {
$primaryKeys[] = $column->name;
}
}
$explicitPrimary = collect($blueprint->getCommands())->contains('name', 'primary');
if ($primaryKeys !== [] && ! $explicitPrimary) {
$columns[] = sprintf(
'PRIMARY KEY (%s)',
$this->columnize($primaryKeys)
);
}
return sprintf(
'CREATE TABLE %s (%s)',
$this->wrapTable($blueprint),
implode(', ', $columns)
);
}
public function compileAdd(Blueprint $blueprint, Fluent $command)
{
return 'ALTER TABLE '.$this->wrapTable($blueprint).' ADD COLUMN '.$this->columnDefinition($command->column);
}
public function compileChange(Blueprint $blueprint, Fluent $command)
{
$column = $command->column;
if ($column->autoIncrement) {
throw new \RuntimeException('Changing a Db2 identity column is unsupported.');
}
$columns = array_column($this->connection->getSchemaBuilder()->getColumns($blueprint->getTable()), null, 'name');
$current = $columns[$column->name] ?? null;
if ($current === null || $current['auto_increment']) {
throw new \RuntimeException('Db2 change requires an existing non-identity column.');
}
$prefix = 'ALTER TABLE '.$this->wrapTable($blueprint).' ALTER COLUMN '.$this->wrap($column);
$type = $this->getType($column);
$statements = [];
if (strcasecmp($current['type'], $type) !== 0) {
$statements[] = $prefix.' SET DATA TYPE '.$type;
}
if ($current['nullable'] !== (bool) $column->nullable) {
$statements[] = $prefix.($column->nullable ? ' DROP NOT NULL' : ' SET NOT NULL');
}
if ($column->default !== null) {
$statements[] = $prefix.' SET DEFAULT '.$this->getDefaultValue($column->default);
} elseif ($current['default'] !== null) {
$statements[] = $prefix.' DROP DEFAULT';
}
return $statements;
}
public function compileDropColumn(Blueprint $blueprint, Fluent $command)
{
$columns = array_map(fn ($column) => 'DROP COLUMN '.$this->wrap($column), $command->columns);
return 'ALTER TABLE '.$this->wrapTable($blueprint).' '.implode(' ', $columns);
}
public function compileDrop(Blueprint $blueprint, Fluent $command)
{
return 'DROP TABLE '.$this->wrapTable($blueprint);
}
public function compileDropIfExists(Blueprint $blueprint, Fluent $command)
{
return 'DROP TABLE IF EXISTS '.$this->wrapTable($blueprint);
}
public function compileRename(Blueprint $blueprint, Fluent $command)
{
[$schema] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($blueprint->getTable());
[$targetSchema, $target] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($command->to);
if ($targetSchema !== null && $targetSchema !== ($schema ?? $this->connection->getConfig('schema'))) {
throw new \RuntimeException('Db2 cannot rename a table across schemas.');
}
return 'RENAME TABLE '.$this->wrapTable($blueprint).' TO '.$this->wrapTable($target);
}
public function compileRenameColumn(Blueprint $blueprint, Fluent $command)
{
return 'ALTER TABLE '.$this->wrapTable($blueprint)
.' RENAME COLUMN '.$this->wrap($command->from).' TO '.$this->wrap($command->to);
}
public function compileDropForeign(Blueprint $blueprint, Fluent $command)
{
return 'ALTER TABLE '.$this->wrapTable($blueprint).' DROP FOREIGN KEY '.$this->wrap($command->index);
}
public function compileDropPrimary(Blueprint $blueprint, Fluent $command)
{
return 'ALTER TABLE '.$this->wrapTable($blueprint).' DROP PRIMARY KEY';
}
public function compileDropUnique(Blueprint $blueprint, Fluent $command)
{
return $this->compileDropIndex($blueprint, $command);
}
public function compileDropIndex(Blueprint $blueprint, Fluent $command)
{
return 'DROP INDEX '.$this->wrapIndex($blueprint, $command->index);
}
private function wrapIndex(Blueprint $blueprint, string $name): string
{
[$schema] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($blueprint->getTable());
return $schema === null ? $this->wrapValue($name) : $this->wrapValue($schema).'.'.$this->wrapValue($name);
}
private function columnDefinition(Fluent $column): string
{
$sql = $this->wrap($column).' '.$this->getType($column);
if ($column->autoIncrement) {
$sql .= ' GENERATED BY DEFAULT AS IDENTITY';
}
if (! $column->nullable) {
$sql .= ' NOT NULL';
}
if ($column->default !== null) {
$sql .= ' DEFAULT '.$this->getDefaultValue($column->default);
}
return $sql;
}
protected function typeBigInteger(Fluent $column)
{
return 'BIGINT';
}
protected function typeInteger(Fluent $column)
{
return 'INTEGER';
}
protected function typeSmallInteger(Fluent $column)
{
return 'SMALLINT';
}
protected function typeString(Fluent $column)
{
return 'VARCHAR(' . ($column->length ?: 255) . ')';
}
protected function typeText(Fluent $column)
{
return 'CLOB(1M)';
}
protected function typeLongText(Fluent $column)
{
return 'CLOB(2M)';
}
protected function typeBoolean(Fluent $column)
{
return 'SMALLINT';
}
protected function typeTimestamp(Fluent $column)
{
return 'TIMESTAMP';
}
protected function typeDateTime(Fluent $column)
{
return 'TIMESTAMP';
}
protected function typeDate(Fluent $column)
{
return 'DATE';
}
protected function typeBinary(Fluent $column)
{
return 'BLOB(1M)';
}
protected function typeDecimal(Fluent $column)
{
return sprintf(
'DECIMAL(%d,%d)',
$column->total ?? 8,
$column->places ?? 2
);
}
public function compilePrimary(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'ALTER TABLE %s ADD CONSTRAINT %s PRIMARY KEY (%s)',
$this->wrapTable($blueprint),
$this->wrapValue($command->index),
$this->columnize($command->columns)
);
}
protected function typeMediumText(Fluent $column)
{
return 'CLOB(16M)';
}
public function compileUnique(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'CREATE UNIQUE INDEX %s ON %s (%s)',
$this->wrapIndex($blueprint, $command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
public function compileIndex(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'CREATE INDEX %s ON %s (%s)',
$this->wrapIndex($blueprint, $command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
protected function typeJson(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeJsonb(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeTinyText(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'VARCHAR(255)';
}
public function compileInsertOrIgnore(
\Illuminate\Database\Query\Builder $query,
array $values
) {
if (empty($values)) {
return '';
}
if (!is_array(reset($values))) {
$values = [$values];
}
$columns = array_keys(reset($values));
$table = $this->wrapTable($query->from);
$sourceColumns = implode(
', ',
array_map(fn ($column) => $this->wrap($column), $columns)
);
$rows = [];
foreach ($values as $row) {
$rows[] = '(' . implode(
', ',
array_fill(0, count($columns), '?')
) . ')';
}
$source = implode(', ', $rows);
$conditions = [];
foreach ($columns as $column) {
$wrapped = $this->wrap($column);
$conditions[] = "target.$wrapped = source.$wrapped";
}
return sprintf(
'MERGE INTO %s AS target
USING (VALUES %s) AS source (%s)
ON %s
WHEN NOT MATCHED THEN
INSERT (%s)
VALUES (%s)',
$table,
$source,
$sourceColumns,
implode(' AND ', $conditions),
$sourceColumns,
implode(
', ',
array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
)
)
);
}
}
@@ -1,355 +0,0 @@
<?php
namespace App\Database\Db2;
use Illuminate\Database\Schema\Grammars\Grammar;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Fluent;
class Db2SchemaGrammar extends Grammar
{
protected $modifiers = ['Nullable', 'Default'];
public function compileCreate(Blueprint $blueprint, Fluent $command)
{
$columns = [];
$primaryKeys = [];
foreach ($blueprint->getAddedColumns() as $column) {
$columns[] = $this->columnDefinition($column);
if ($column->autoIncrement) {
$primaryKeys[] = $column->name;
}
}
$explicitPrimary = collect($blueprint->getCommands())->contains('name', 'primary');
if ($primaryKeys !== [] && ! $explicitPrimary) {
$columns[] = sprintf(
'PRIMARY KEY (%s)',
$this->columnize($primaryKeys)
);
}
return sprintf(
'CREATE TABLE %s (%s)',
$this->wrapTable($blueprint),
implode(', ', $columns)
);
}
public function compileAdd(Blueprint $blueprint, Fluent $command)
{
return 'ALTER TABLE '.$this->wrapTable($blueprint).' ADD COLUMN '.$this->columnDefinition($command->column);
}
public function compileChange(Blueprint $blueprint, Fluent $command)
{
$column = $command->column;
if ($column->autoIncrement) {
throw new \RuntimeException('Changing a Db2 identity column is unsupported.');
}
$columns = array_column($this->connection->getSchemaBuilder()->getColumns($blueprint->getTable()), null, 'name');
$current = $columns[$column->name] ?? null;
if ($current === null || $current['auto_increment']) {
throw new \RuntimeException('Db2 change requires an existing non-identity column.');
}
$prefix = 'ALTER TABLE '.$this->wrapTable($blueprint).' ALTER COLUMN '.$this->wrap($column);
$type = $this->getType($column);
$statements = [];
if (strcasecmp($current['type'], $type === 'TIMESTAMP' ? 'TIMESTAMP(6)' : $type) !== 0) {
$statements[] = $prefix.' SET DATA TYPE '.$type;
}
if ($current['nullable'] !== (bool) $column->nullable) {
$statements[] = $prefix.($column->nullable ? ' DROP NOT NULL' : ' SET NOT NULL');
}
if ($column->default !== null) {
$statements[] = $prefix.' SET DEFAULT '.$this->getDefaultValue($column->default);
} elseif ($current['default'] !== null) {
$statements[] = $prefix.' DROP DEFAULT';
}
return $statements;
}
public function compileDropColumn(Blueprint $blueprint, Fluent $command)
{
$columns = array_map(fn ($column) => 'DROP COLUMN '.$this->wrap($column), $command->columns);
return 'ALTER TABLE '.$this->wrapTable($blueprint).' '.implode(' ', $columns);
}
public function compileDrop(Blueprint $blueprint, Fluent $command)
{
return 'DROP TABLE '.$this->wrapTable($blueprint);
}
public function compileDropIfExists(Blueprint $blueprint, Fluent $command)
{
return 'DROP TABLE IF EXISTS '.$this->wrapTable($blueprint);
}
public function compileRename(Blueprint $blueprint, Fluent $command)
{
[$schema] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($blueprint->getTable());
[$targetSchema, $target] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($command->to);
if ($targetSchema !== null && $targetSchema !== ($schema ?? $this->connection->getConfig('schema'))) {
throw new \RuntimeException('Db2 cannot rename a table across schemas.');
}
return 'RENAME TABLE '.$this->wrapTable($blueprint).' TO '.$this->wrapTable($target);
}
public function compileRenameColumn(Blueprint $blueprint, Fluent $command)
{
return 'ALTER TABLE '.$this->wrapTable($blueprint)
.' RENAME COLUMN '.$this->wrap($command->from).' TO '.$this->wrap($command->to);
}
public function compileDropForeign(Blueprint $blueprint, Fluent $command)
{
return 'ALTER TABLE '.$this->wrapTable($blueprint).' DROP FOREIGN KEY '.$this->wrap($command->index);
}
public function compileDropPrimary(Blueprint $blueprint, Fluent $command)
{
return 'ALTER TABLE '.$this->wrapTable($blueprint).' DROP PRIMARY KEY';
}
public function compileDropUnique(Blueprint $blueprint, Fluent $command)
{
return $this->compileDropIndex($blueprint, $command);
}
public function compileDropIndex(Blueprint $blueprint, Fluent $command)
{
return 'DROP INDEX '.$this->wrapIndex($blueprint, $command->index);
}
public function compileRenameIndex(Blueprint $blueprint, Fluent $command)
{
return 'RENAME INDEX '.$this->wrapIndex($blueprint, $command->from)
.' TO '.$this->wrapValue($command->to);
}
private function wrapIndex(Blueprint $blueprint, string $name): string
{
[$schema] = $this->connection->getSchemaBuilder()->parseSchemaAndTable($blueprint->getTable());
return $schema === null ? $this->wrapValue($name) : $this->wrapValue($schema).'.'.$this->wrapValue($name);
}
private function columnDefinition(Fluent $column): string
{
$sql = $this->wrap($column).' '.$this->getType($column);
if ($column->autoIncrement) {
$sql .= ' GENERATED BY DEFAULT AS IDENTITY';
}
if (! $column->nullable) {
$sql .= ' NOT NULL';
}
if ($column->default !== null) {
$sql .= ' DEFAULT '.$this->getDefaultValue($column->default);
}
return $sql;
}
protected function typeBigInteger(Fluent $column)
{
return 'BIGINT';
}
protected function typeInteger(Fluent $column)
{
return 'INTEGER';
}
protected function typeSmallInteger(Fluent $column)
{
return 'SMALLINT';
}
protected function typeString(Fluent $column)
{
return 'VARCHAR(' . ($column->length ?: 255) . ')';
}
protected function typeChar(Fluent $column)
{
return 'CHAR('.$column->length.')';
}
protected function typeUuid(Fluent $column)
{
return 'CHAR(36)';
}
protected function typeTime(Fluent $column)
{
if ($column->precision !== null && $column->precision !== 0) {
throw new \InvalidArgumentException('Db2 TIME does not support fractional-second precision.');
}
return 'TIME';
}
protected function typeText(Fluent $column)
{
return 'CLOB(1M)';
}
protected function typeLongText(Fluent $column)
{
return 'CLOB(2M)';
}
protected function typeBoolean(Fluent $column)
{
return 'SMALLINT';
}
protected function typeTimestamp(Fluent $column)
{
return $column->precision === null ? 'TIMESTAMP' : 'TIMESTAMP('.$column->precision.')';
}
protected function typeDateTime(Fluent $column)
{
return $this->typeTimestamp($column);
}
protected function typeDate(Fluent $column)
{
return 'DATE';
}
protected function typeBinary(Fluent $column)
{
return 'BLOB(1M)';
}
protected function typeDecimal(Fluent $column)
{
return sprintf(
'DECIMAL(%d,%d)',
$column->total ?? 8,
$column->places ?? 2
);
}
public function compilePrimary(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'ALTER TABLE %s ADD CONSTRAINT %s PRIMARY KEY (%s)',
$this->wrapTable($blueprint),
$this->wrapValue($command->index),
$this->columnize($command->columns)
);
}
protected function typeMediumText(Fluent $column)
{
return 'CLOB(16M)';
}
public function compileUnique(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'CREATE UNIQUE INDEX %s ON %s (%s)',
$this->wrapIndex($blueprint, $command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
public function compileIndex(Blueprint $blueprint, Fluent $command)
{
return sprintf(
'CREATE INDEX %s ON %s (%s)',
$this->wrapIndex($blueprint, $command->index),
$this->wrapTable($blueprint),
$this->columnize($command->columns)
);
}
protected function typeJson(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeJsonb(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'CLOB(1M)';
}
protected function typeTinyText(\Illuminate\Database\Schema\ColumnDefinition $column)
{
return 'VARCHAR(255)';
}
public function compileInsertOrIgnore(
\Illuminate\Database\Query\Builder $query,
array $values
) {
if (empty($values)) {
return '';
}
if (!is_array(reset($values))) {
$values = [$values];
}
$columns = array_keys(reset($values));
$table = $this->wrapTable($query->from);
$sourceColumns = implode(
', ',
array_map(fn ($column) => $this->wrap($column), $columns)
);
$rows = [];
foreach ($values as $row) {
$rows[] = '(' . implode(
', ',
array_fill(0, count($columns), '?')
) . ')';
}
$source = implode(', ', $rows);
$conditions = [];
foreach ($columns as $column) {
$wrapped = $this->wrap($column);
$conditions[] = "target.$wrapped = source.$wrapped";
}
return sprintf(
'MERGE INTO %s AS target
USING (VALUES %s) AS source (%s)
ON %s
WHEN NOT MATCHED THEN
INSERT (%s)
VALUES (%s)',
$table,
$source,
$sourceColumns,
implode(' AND ', $conditions),
$sourceColumns,
implode(
', ',
array_map(
fn ($column) => 'source.' . $this->wrap($column),
$columns
)
)
);
}
}
@@ -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
```
@@ -0,0 +1,31 @@
# Db2 driver release verification
Verified 11 November 2026 with Laravel 13.25.0, PHP 8.5.11, PDO_ODBC on
macOS, and Db2 LUW 12.1.5.0 (fix pack 0).
| Run | Passed | Assertions |
| --- | ---: | ---: |
| Release smoke test | 1 | 8 |
| Db2 integration suite | 45 | 139 |
| Full Laravel suite | 78 | 220 |
The smoke test creates a random Db2 schema, runs all five application migration
files, and uses an authenticated Laravel HTTP test to render the security
settings page with a Db2-backed passkey. It verifies the `failed_jobs.failed_at`
default, rolls back the migration batch, checks that the migration history is
empty, and drops the disposable schema. The Db2 account needs CREATE SCHEMA
and permissions to manage objects in that schema. The full suite uses SQLite
for the general Laravel feature tests and Db2 for its integration tests.
```sh
composer validate --no-check-publish --no-interaction
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2/ReleaseCompatibilityTest.php
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2
APP_ENV=testing php artisan test --do-not-cache-result
```
A skipped Db2 test does not verify compatibility. This matrix covers one
Db2 LUW and Laravel combination. It does not certify other releases, Db2 for
i or z/OS, or browser-based WebAuthn enrolment and authentication. See the
[schema compatibility notes](DB2-SCHEMA-COMPATIBILITY.md) and
[query compatibility notes](DB2-QUERY-COMPATIBILITY.md) for supported cases and limits.
@@ -0,0 +1,67 @@
# Db2 LUW schema and migrations
The Stage 5 tests use the configured `db2_local` connection. They create randomly named
tables and a separate migration history table, then remove them. A skipped test means
the connection was unavailable and provides no Db2 verification.
```sh
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2/SchemaTest.php
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2
APP_ENV=testing php artisan test --do-not-cache-result
```
The tests cover table creation, same-schema rename, conditional drop, adding and
dropping columns, widening VARCHAR, catalog defaults and identity metadata, composite
ordinary and unique index metadata and removal, foreign-key metadata and removal,
and Laravel migration registration and rollback.
## Limits
- Db2 applies its own rules to type conversions and dependent objects. Table
renames require the source and target to be in the same schema. Tables with
certain dependencies, including referential constraints, cannot be renamed.
- Dropping columns and some type or nullability changes can leave a table in
REORG-pending state. The driver does not run administrative utilities. Arrange
for a Db2 administrator to run REORG before subsequent operations that require it.
- Changing an identity column through Laravel's `change()` is unsupported.
Unsigned types, column positioning, expression indexes, full-text indexes
and spatial indexes are outside this implementation.
- Laravel `unique()` creates a Db2 unique index. Db2 foreign keys require a
referenced primary key or unique constraint. A standalone unique index does
not establish that constraint. Foreign-key actions must be supported by Db2
for the chosen operation.
- Column defaults are returned as SQL expressions from the catalog. Catalog
output does not reconstruct generated expressions or every Db2 type attribute.
- Laravel migration rollback runs `down()` and removes its history entry.
The driver does not advertise transactional schema migrations.
- Migration batch lookup casts query-builder `max('batch')` results to text so
Laravel can perform numeric arithmetic through PDO_ODBC. This applies to custom
migration history table names as well.
## Phase 7 data types and indexes
- `char(length)` creates a fixed-width Db2 character column. `uuid()` uses
`CHAR(36)` and leaves UUID validation and generation to the application.
- `time()` uses Db2 TIME at whole-second precision. Fractional TIME precision
raises an exception. Timestamp and datetime definitions accept Db2
fractional-second precision, and the catalog reports it for TIMESTAMP.
- `renameIndex()` uses Db2's same-schema rename for an application-created
index. It preserves key order and uniqueness. Db2 requires the target name
to be available in that schema.
- Time-zone-aware column types, binary UUID storage, expression indexes,
and automatic REORG remain outside the verified scope.
Run the focused live tests with:
```sh
APP_ENV=testing php artisan test --do-not-cache-result tests/Feature/Db2/SchemaTypesAndIndexesTest.php
```
## Selecting the default schema
Set `DB2_SCHEMA` to use a specific schema on the database selected by
`DB2_DSN`. If omitted or blank, the connector retains the DSN or server
default and reads `CURRENT SCHEMA` for Laravel catalog lookups. Set
`DB2_SCHEMA=AAMEDIUK` explicitly to retain the former default.