diff --git a/app/Database/Db2/Db2Connection.php b/app/Database/Db2/Db2Connection.php index f754fbb..b31d2b2 100644 --- a/app/Database/Db2/Db2Connection.php +++ b/app/Database/Db2/Db2Connection.php @@ -25,6 +25,15 @@ class Db2Connection extends Connection $fetchUsing ); + // Never interpret ordinary raw-query columns as + // internal NULL indicators. + if ( + ! is_string($query) || + ! str_contains($query, '/* DB2_NULL_FLAGS_V1 */') + ) { + return $rows; + } + foreach ($rows as &$row) { if (! is_object($row) && ! is_array($row)) { continue; diff --git a/app/Database/Db2/Db2Connection.php.bak-stage01-20261111-101134 b/app/Database/Db2/Db2Connection.php.bak-stage01-20261111-101134 new file mode 100644 index 0000000..f754fbb --- /dev/null +++ b/app/Database/Db2/Db2Connection.php.bak-stage01-20261111-101134 @@ -0,0 +1,98 @@ + $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; + } + + +} diff --git a/app/Database/Db2/Db2QueryGrammar.php b/app/Database/Db2/Db2QueryGrammar.php index 0368b3d..eb9ad3d 100644 --- a/app/Database/Db2/Db2QueryGrammar.php +++ b/app/Database/Db2/Db2QueryGrammar.php @@ -8,8 +8,241 @@ use Illuminate\Database\Query\Expression; class Db2QueryGrammar extends Grammar { + protected $selectComponents = [ + 'aggregate', + 'columns', + 'from', + 'indexHint', + 'joins', + 'wheres', + 'groups', + 'havings', + 'orders', + 'offset', + 'limit', + 'lock', + ]; + private array $db2ColumnCache = []; public const NULL_STRING_SENTINEL = '__DB2_NULL_STRING__'; + /** + * Compile a Db2 MERGE statement for Laravel upserts. + */ + public function compileUpsert( + Builder $query, + array $values, + array $uniqueBy, + array $update + ) { + $columns = $this->db2MergeColumns($values); + + foreach ($uniqueBy as $column) { + if (! in_array($column, $columns, true)) { + throw new \InvalidArgumentException( + "Upsert key is missing from inserted values: {$column}" + ); + } + } + + $source = $this->db2MergeSource($values, $columns); + + $matches = []; + + foreach ($uniqueBy as $column) { + $wrapped = $this->wrap($column); + + $matches[] = "target.{$wrapped} = source.{$wrapped}"; + } + + $updates = []; + + foreach ($update as $key => $value) { + if (is_int($key)) { + if (! in_array($value, $columns, true)) { + throw new \InvalidArgumentException( + "Unknown upsert update column: {$value}" + ); + } + + $wrapped = $this->wrap($value); + + $updates[] = "target.{$wrapped} = source.{$wrapped}"; + } else { + $updates[] = "target." + . $this->wrap($key) + . " = " + . $this->parameter($value); + } + } + + $insertColumns = $this->columnize($columns); + + $insertValues = implode(', ', array_map( + fn ($column) => 'source.' . $this->wrap($column), + $columns + )); + + $sql = "MERGE INTO {$this->wrapTable($query->from)} AS target " + . "USING ({$source}) AS source " + . "ON (" . implode(' AND ', $matches) . ") "; + + if ($updates !== []) { + $sql .= "WHEN MATCHED THEN UPDATE SET " + . implode(', ', $updates) . " "; + } + + return $sql + . "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) " + . "VALUES ({$insertValues})"; + } + + /** + * Insert rows without replacing existing rows. + * + * Db2 MERGE ignores rows that match the selected key. + */ + public function compileInsertOrIgnore( + Builder $query, + array $values + ) { + $columns = $this->db2MergeColumns($values); + $source = $this->db2MergeSource($values, $columns); + + $indexes = $this->connection + ->getSchemaBuilder() + ->getIndexes($query->from); + + $uniqueConditions = []; + + foreach ($indexes as $index) { + if (! ($index['unique'] ?? false)) { + continue; + } + + $indexColumns = $index['columns'] ?? []; + + if ($indexColumns === []) { + continue; + } + + // A unique key can only be compared if every + // participating column exists in the source. + $conditions = []; + + foreach ($indexColumns as $column) { + $matchedColumn = null; + + foreach ($columns as $candidate) { + if (strcasecmp($candidate, $column) === 0) { + $matchedColumn = $candidate; + break; + } + } + + if ($matchedColumn === null) { + $conditions = []; + break; + } + + $wrapped = $this->wrap($matchedColumn); + + $conditions[] = "target.{$wrapped} = source.{$wrapped}"; + } + + if ($conditions !== []) { + $uniqueConditions[] = '(' + . implode(' AND ', $conditions) + . ')'; + } + } + + if ($uniqueConditions === []) { + throw new \RuntimeException( + 'Db2 insertOrIgnore requires an applicable unique index.' + ); + } + + $insertColumns = $this->columnize($columns); + + $insertValues = implode(', ', array_map( + fn ($column) => 'source.' . $this->wrap($column), + $columns + )); + + return "MERGE INTO {$this->wrapTable($query->from)} AS target " + . "USING ({$source}) AS source " + . "ON (" . implode(' OR ', $uniqueConditions) . ") " + . "WHEN NOT MATCHED THEN INSERT ({$insertColumns}) " + . "VALUES ({$insertValues})"; + } + + /** + * Validate the column layout of a multi-row MERGE. + */ + private function db2MergeColumns(array $values): array + { + if ($values === []) { + throw new \InvalidArgumentException( + 'MERGE requires at least one row.' + ); + } + + $columns = array_keys(reset($values)); + + foreach ($values as $row) { + if (array_keys($row) !== $columns) { + throw new \InvalidArgumentException( + 'All MERGE rows must contain the same columns.' + ); + } + } + + return $columns; + } + + /** + * Build a parameterized Db2 MERGE source. + */ + private function db2MergeSource( + array $values, + array $columns + ): string { + $selects = []; + + foreach ($values as $row) { + $parts = []; + + foreach ($columns as $column) { + $parts[] = $this->parameter($row[$column]) + . ' AS ' + . $this->wrap($column); + } + + $selects[] = 'SELECT ' + . implode(', ', $parts) + . ' FROM SYSIBM.SYSDUMMY1'; + } + + return implode(' UNION ALL ', $selects); + } + + /** + * Compile a Db2 LUW savepoint statement. + */ + public function compileSavepoint($name) + { + return 'SAVEPOINT ' . $name + . ' ON ROLLBACK RETAIN CURSORS'; + } + + /** + * Compile a Db2 LUW rollback-to-savepoint statement. + */ + public function compileSavepointRollBack($name) + { + return 'ROLLBACK TO SAVEPOINT ' . $name; + } + protected function compileAggregate($query, $aggregate) { $column = $this->columnize($aggregate['columns']); @@ -35,12 +268,23 @@ class Db2QueryGrammar extends Grammar $expression = "CAST(COALESCE({$expression}, 0) AS VARCHAR(20))"; } - return 'select '.$expression.' as aggregate'; + return 'select '.$expression.' as "aggregate"'; } protected function compileLimit($query, $limit) { - return 'fetch first '.(int) $limit.' rows only'; + $limit = (int) $limit; + + if ((int) ($query->offset ?? 0) > 0) { + return 'fetch next '.$limit.' rows only'; + } + + return 'fetch first '.$limit.' rows only'; + } + + protected function compileOffset($query, $offset) + { + return 'offset '.(int) $offset.' rows'; } public function compileExists( @@ -153,6 +397,7 @@ class Db2QueryGrammar extends Grammar $lobs = []; $changed = false; $indicatorIndex = 0; + $hasNullIndicators = false; foreach ($parsed as $entry) { $info = $entry['info']; @@ -191,18 +436,12 @@ class Db2QueryGrammar extends Grammar . $wrapped . ", CAST('' AS VARCHAR({$length})))"; } else { - $format = match ($type) { - 'DATE' => 'YYYY-MM-DD', - 'TIME' => 'HH24:MI:SS', - default => 'YYYY-MM-DD HH24:MI:SS.FF6', - }; - $expression = 'CASE WHEN ' . $wrapped . " IS NULL THEN CAST('' AS VARCHAR(32))" - . ' ELSE VARCHAR_FORMAT(' + . ' ELSE CAST(' . $wrapped - . ", '{$format}') END"; + . ' AS VARCHAR(32)) END'; } $ordinary[] = new Expression( @@ -226,6 +465,7 @@ class Db2QueryGrammar extends Grammar . $this->wrap($flagAlias) ); + $hasNullIndicators = true; $changed = true; } else { $ordinary[] = $selected; @@ -243,6 +483,14 @@ class Db2QueryGrammar extends Grammar $modified = clone $query; $modified->columns = array_merge($ordinary, $lobs); - return parent::compileSelect($modified); + $sql = parent::compileSelect($modified); + + // Only mark SELECT statements that actually contain + // generated NULL indicator columns. + if ($hasNullIndicators) { + $sql .= ' /* DB2_NULL_FLAGS_V1 */'; + } + + return $sql; } } diff --git a/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-102612 b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-102612 new file mode 100644 index 0000000..200daa5 --- /dev/null +++ b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-102612 @@ -0,0 +1,258 @@ +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; + } +} diff --git a/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103126 b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103126 new file mode 100644 index 0000000..b35c8c7 --- /dev/null +++ b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103126 @@ -0,0 +1,252 @@ +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; + } +} diff --git a/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103411 b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103411 new file mode 100644 index 0000000..9aa74d0 --- /dev/null +++ b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103411 @@ -0,0 +1,278 @@ +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; + } +} diff --git a/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103712 b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103712 new file mode 100644 index 0000000..0ff64cf --- /dev/null +++ b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-103712 @@ -0,0 +1,436 @@ +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; + } +} diff --git a/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-104110 b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-104110 new file mode 100644 index 0000000..e2fe576 --- /dev/null +++ b/app/Database/Db2/Db2QueryGrammar.php.bak-20261111-104110 @@ -0,0 +1,479 @@ +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; + } +} diff --git a/app/Database/Db2/Db2QueryGrammar.php.bak-stage01-20261111-101134 b/app/Database/Db2/Db2QueryGrammar.php.bak-stage01-20261111-101134 new file mode 100644 index 0000000..0368b3d --- /dev/null +++ b/app/Database/Db2/Db2QueryGrammar.php.bak-stage01-20261111-101134 @@ -0,0 +1,248 @@ +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); + } +} diff --git a/bootstrap/app.php.bak-20261111-101633 b/bootstrap/app.php.bak-20261111-101633 new file mode 100755 index 0000000..1085719 --- /dev/null +++ b/bootstrap/app.php.bak-20261111-101633 @@ -0,0 +1,21 @@ +withRouting( + web: __DIR__.'/../routes/web.php', + commands: __DIR__.'/../routes/console.php', + health: '/up', + ) + ->withMiddleware(function (Middleware $middleware): void { + // + }) + ->withExceptions(function (Exceptions $exceptions): void { + $exceptions->shouldRenderJsonWhen( + fn (Request $request) => $request->is('api/*') || $request->expectsJson(), + ); + })->create(); diff --git a/phpunit.xml b/phpunit.xml old mode 100755 new mode 100644 index e7f0a48..9cd7359 --- a/phpunit.xml +++ b/phpunit.xml @@ -18,7 +18,8 @@ - + + diff --git a/phpunit.xml.bak-20261111-101527 b/phpunit.xml.bak-20261111-101527 new file mode 100755 index 0000000..e7f0a48 --- /dev/null +++ b/phpunit.xml.bak-20261111-101527 @@ -0,0 +1,36 @@ + + + + + tests/Unit + + + tests/Feature + + + + + app + + + + + + + + + + + + + + + + + + + diff --git a/phpunit.xml.bak-20261111-101759 b/phpunit.xml.bak-20261111-101759 new file mode 100644 index 0000000..fbcfdaf --- /dev/null +++ b/phpunit.xml.bak-20261111-101759 @@ -0,0 +1,37 @@ + + + + + tests/Unit + + + tests/Feature + + + + + app + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Feature/Auth/PasswordResetTest.php b/tests/Feature/Auth/PasswordResetTest.php old mode 100755 new mode 100644 index 9f55aba..b2ebf1a --- a/tests/Feature/Auth/PasswordResetTest.php +++ b/tests/Feature/Auth/PasswordResetTest.php @@ -20,7 +20,7 @@ test('reset password link can be requested', function () { $user = User::factory()->create(); - $this->post(route('password.request'), ['email' => $user->email]); + $this->post(route('password.email'), ['email' => $user->email]); Notification::assertSentTo($user, ResetPassword::class); }); @@ -30,7 +30,7 @@ test('reset password screen can be rendered', function () { $user = User::factory()->create(); - $this->post(route('password.request'), ['email' => $user->email]); + $this->post(route('password.email'), ['email' => $user->email]); Notification::assertSentTo($user, ResetPassword::class, function ($notification) { $response = $this->get(route('password.reset', $notification->token)); @@ -46,7 +46,7 @@ test('password can be reset with valid token', function () { $user = User::factory()->create(); - $this->post(route('password.request'), ['email' => $user->email]); + $this->post(route('password.email'), ['email' => $user->email]); Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) { $response = $this->post(route('password.update'), [ diff --git a/tests/Feature/Auth/PasswordResetTest.php.bak-20261111-101527 b/tests/Feature/Auth/PasswordResetTest.php.bak-20261111-101527 new file mode 100755 index 0000000..9f55aba --- /dev/null +++ b/tests/Feature/Auth/PasswordResetTest.php.bak-20261111-101527 @@ -0,0 +1,65 @@ +skipUnlessFortifyHas(Features::resetPasswords()); +}); + +test('reset password link screen can be rendered', function () { + $response = $this->get(route('password.request')); + + $response->assertOk(); +}); + +test('reset password link can be requested', function () { + Notification::fake(); + + $user = User::factory()->create(); + + $this->post(route('password.request'), ['email' => $user->email]); + + Notification::assertSentTo($user, ResetPassword::class); +}); + +test('reset password screen can be rendered', function () { + Notification::fake(); + + $user = User::factory()->create(); + + $this->post(route('password.request'), ['email' => $user->email]); + + Notification::assertSentTo($user, ResetPassword::class, function ($notification) { + $response = $this->get(route('password.reset', $notification->token)); + + $response->assertOk(); + + return true; + }); +}); + +test('password can be reset with valid token', function () { + Notification::fake(); + + $user = User::factory()->create(); + + $this->post(route('password.request'), ['email' => $user->email]); + + Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) { + $response = $this->post(route('password.update'), [ + 'token' => $notification->token, + 'email' => $user->email, + 'password' => 'password', + 'password_confirmation' => 'password', + ]); + + $response + ->assertSessionHasNoErrors() + ->assertRedirect(route('login', absolute: false)); + + return true; + }); +}); diff --git a/tests/Feature/Db2/Db2TestCase.php b/tests/Feature/Db2/Db2TestCase.php new file mode 100644 index 0000000..bf7bd76 --- /dev/null +++ b/tests/Feature/Db2/Db2TestCase.php @@ -0,0 +1,37 @@ +markTestSkipped('PDO_ODBC extension unavailable.'); + } + + if (! config('database.connections.db2_local')) { + $this->markTestSkipped('db2_local is not configured.'); + } + + try { + $this->db()->select( + 'SELECT 1 AS "health" FROM SYSIBM.SYSDUMMY1' + ); + } catch (\Throwable $e) { + $this->markTestSkipped( + 'Db2 connection unavailable: ' . $e->getMessage() + ); + } + } +} diff --git a/tests/Feature/Db2/NullHandlingTest.php b/tests/Feature/Db2/NullHandlingTest.php new file mode 100644 index 0000000..ad32a21 --- /dev/null +++ b/tests/Feature/Db2/NullHandlingTest.php @@ -0,0 +1,125 @@ +fixtureTable = 'DB2_TEST.DB2T_' . + strtoupper(bin2hex(random_bytes(6))); + + $db = $this->db(); + + $db->statement(" + CREATE TABLE {$this->fixtureTable} ( + ID INTEGER NOT NULL PRIMARY KEY, + NULLABLE_TEXT VARCHAR(100), + NULLABLE_DATE DATE, + NULLABLE_TIME TIME, + NULLABLE_TIMESTAMP TIMESTAMP + ) + "); + + $db->statement(" + INSERT INTO {$this->fixtureTable} + (ID, NULLABLE_TEXT, NULLABLE_DATE, + NULLABLE_TIME, NULLABLE_TIMESTAMP) + VALUES (1, NULL, NULL, NULL, NULL) + "); + + $db->statement(" + INSERT INTO {$this->fixtureTable} + (ID, NULLABLE_TEXT, NULLABLE_DATE, + NULLABLE_TIME, NULLABLE_TIMESTAMP) + VALUES ( + 2, + '', + DATE('2026-11-11'), + TIME('10:15:30'), + TIMESTAMP('2026-11-11 10:15:30') + ) + "); + } + + protected function tearDown(): void + { + try { + if ($this->fixtureTable !== '') { + $this->db()->statement( + "DROP TABLE {$this->fixtureTable}" + ); + } + } finally { + parent::tearDown(); + } + } + + public function test_null_values_are_restored(): void + { + $row = $this->db()->table($this->fixtureTable) + ->where('ID', 1) + ->first(); + + $this->assertNull($row->NULLABLE_TEXT); + $this->assertNull($row->NULLABLE_DATE); + $this->assertNull($row->NULLABLE_TIME); + $this->assertNull($row->NULLABLE_TIMESTAMP); + } + + public function test_empty_string_is_not_converted_to_null(): void + { + $row = $this->db()->table($this->fixtureTable) + ->where('ID', 2) + ->first(); + + $this->assertSame('', $row->NULLABLE_TEXT); + } + + public function test_non_null_temporal_values_survive(): void + { + $row = $this->db()->table($this->fixtureTable) + ->where('ID', 2) + ->first(); + + $this->assertNotNull($row->NULLABLE_DATE); + $this->assertNotNull($row->NULLABLE_TIME); + $this->assertNotNull($row->NULLABLE_TIMESTAMP); + } + + public function test_generated_indicators_are_hidden(): void + { + $row = $this->db()->table($this->fixtureTable) + ->where('ID', 1) + ->first(); + + foreach (array_keys((array) $row) as $column) { + $this->assertDoesNotMatchRegularExpression( + '/^__db2_null_flag_\d+$/i', + $column + ); + } + } + + public function test_nullable_aliases_are_preserved(): void + { + $row = $this->db()->table($this->fixtureTable) + ->select('NULLABLE_TEXT as aliased_text') + ->where('ID', 1) + ->first(); + + $this->assertTrue( + property_exists($row, 'aliased_text') + ); + + $this->assertNull($row->aliased_text); + } +} diff --git a/tests/Feature/Db2/NullHandlingTest.php.bak-20261111-102014 b/tests/Feature/Db2/NullHandlingTest.php.bak-20261111-102014 new file mode 100644 index 0000000..1451a29 --- /dev/null +++ b/tests/Feature/Db2/NullHandlingTest.php.bak-20261111-102014 @@ -0,0 +1,121 @@ +db(); + + $db->statement(' + DECLARE GLOBAL TEMPORARY TABLE + SESSION.DB2_LARAVEL_TEST_NULLS ( + ID INTEGER NOT NULL, + NULLABLE_TEXT VARCHAR(4096), + NULLABLE_DATE DATE, + NULLABLE_TIME TIME, + NULLABLE_TIMESTAMP TIMESTAMP + ) + ON COMMIT PRESERVE ROWS + NOT LOGGED + '); + + $db->statement(' + INSERT INTO SESSION.DB2_LARAVEL_TEST_NULLS + (ID, NULLABLE_TEXT, NULLABLE_DATE, + NULLABLE_TIME, NULLABLE_TIMESTAMP) + VALUES (1, NULL, NULL, NULL, NULL) + '); + + $db->statement(" + INSERT INTO SESSION.DB2_LARAVEL_TEST_NULLS + (ID, NULLABLE_TEXT, NULLABLE_DATE, + NULLABLE_TIME, NULLABLE_TIMESTAMP) + VALUES ( + 2, + '', + DATE('2026-11-11'), + TIME('10:15:30'), + TIMESTAMP('2026-11-11 10:15:30') + ) + "); + } + + protected function tearDown(): void + { + try { + $this->db()->statement( + 'DROP TABLE SESSION.DB2_LARAVEL_TEST_NULLS' + ); + } finally { + parent::tearDown(); + } + } + + public function test_null_values_are_restored(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->where('ID', 1) + ->first(); + + $this->assertNull($row->NULLABLE_TEXT); + $this->assertNull($row->NULLABLE_DATE); + $this->assertNull($row->NULLABLE_TIME); + $this->assertNull($row->NULLABLE_TIMESTAMP); + } + + public function test_empty_string_is_not_converted_to_null(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->where('ID', 2) + ->first(); + + $this->assertSame('', $row->NULLABLE_TEXT); + } + + public function test_non_null_temporal_values_survive(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->where('ID', 2) + ->first(); + + $this->assertNotNull($row->NULLABLE_DATE); + $this->assertNotNull($row->NULLABLE_TIME); + $this->assertNotNull($row->NULLABLE_TIMESTAMP); + } + + public function test_generated_indicators_are_hidden(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->where('ID', 1) + ->first(); + + foreach (array_keys((array) $row) as $column) { + $this->assertDoesNotMatchRegularExpression( + '/^__db2_null_flag_\d+$/i', + $column + ); + } + } + + public function test_nullable_aliases_are_preserved(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->select('NULLABLE_TEXT as aliased_text') + ->where('ID', 1) + ->first(); + + $this->assertTrue( + property_exists($row, 'aliased_text') + ); + + $this->assertNull($row->aliased_text); + } +} diff --git a/tests/Feature/Db2/NullHandlingTest.php.bak-20261111-102334 b/tests/Feature/Db2/NullHandlingTest.php.bak-20261111-102334 new file mode 100644 index 0000000..cd7193e --- /dev/null +++ b/tests/Feature/Db2/NullHandlingTest.php.bak-20261111-102334 @@ -0,0 +1,121 @@ +db(); + + $db->statement(' + DECLARE GLOBAL TEMPORARY TABLE + SESSION.DB2_LARAVEL_TEST_NULLS ( + ID INTEGER NOT NULL, + NULLABLE_TEXT VARCHAR(100), + NULLABLE_DATE DATE, + NULLABLE_TIME TIME, + NULLABLE_TIMESTAMP TIMESTAMP + ) + ON COMMIT PRESERVE ROWS + NOT LOGGED + '); + + $db->statement(' + INSERT INTO SESSION.DB2_LARAVEL_TEST_NULLS + (ID, NULLABLE_TEXT, NULLABLE_DATE, + NULLABLE_TIME, NULLABLE_TIMESTAMP) + VALUES (1, NULL, NULL, NULL, NULL) + '); + + $db->statement(" + INSERT INTO SESSION.DB2_LARAVEL_TEST_NULLS + (ID, NULLABLE_TEXT, NULLABLE_DATE, + NULLABLE_TIME, NULLABLE_TIMESTAMP) + VALUES ( + 2, + '', + DATE('2026-11-11'), + TIME('10:15:30'), + TIMESTAMP('2026-11-11 10:15:30') + ) + "); + } + + protected function tearDown(): void + { + try { + $this->db()->statement( + 'DROP TABLE SESSION.DB2_LARAVEL_TEST_NULLS' + ); + } finally { + parent::tearDown(); + } + } + + public function test_null_values_are_restored(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->where('ID', 1) + ->first(); + + $this->assertNull($row->NULLABLE_TEXT); + $this->assertNull($row->NULLABLE_DATE); + $this->assertNull($row->NULLABLE_TIME); + $this->assertNull($row->NULLABLE_TIMESTAMP); + } + + public function test_empty_string_is_not_converted_to_null(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->where('ID', 2) + ->first(); + + $this->assertSame('', $row->NULLABLE_TEXT); + } + + public function test_non_null_temporal_values_survive(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->where('ID', 2) + ->first(); + + $this->assertNotNull($row->NULLABLE_DATE); + $this->assertNotNull($row->NULLABLE_TIME); + $this->assertNotNull($row->NULLABLE_TIMESTAMP); + } + + public function test_generated_indicators_are_hidden(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->where('ID', 1) + ->first(); + + foreach (array_keys((array) $row) as $column) { + $this->assertDoesNotMatchRegularExpression( + '/^__db2_null_flag_\d+$/i', + $column + ); + } + } + + public function test_nullable_aliases_are_preserved(): void + { + $row = $this->db()->table('SESSION.' . self::TABLE) + ->select('NULLABLE_TEXT as aliased_text') + ->where('ID', 1) + ->first(); + + $this->assertTrue( + property_exists($row, 'aliased_text') + ); + + $this->assertNull($row->aliased_text); + } +} diff --git a/tests/Feature/Db2/PaginationIdentityTest.php b/tests/Feature/Db2/PaginationIdentityTest.php new file mode 100644 index 0000000..a858c50 --- /dev/null +++ b/tests/Feature/Db2/PaginationIdentityTest.php @@ -0,0 +1,138 @@ +tableName = 'DB2_TEST.DB2T_' . + strtoupper(bin2hex(random_bytes(6))); + + $this->db()->statement(" + CREATE TABLE {$this->tableName} ( + ID INTEGER GENERATED ALWAYS AS IDENTITY + (START WITH 1 INCREMENT BY 1), + NAME VARCHAR(100) NOT NULL, + PRIMARY KEY (ID) + ) + "); + + foreach (range(1, 20) as $number) { + $this->db()->table($this->tableName)->insert([ + 'NAME' => sprintf('Item %02d', $number), + ]); + } + } + + protected function tearDown(): void + { + try { + if ($this->tableName !== '') { + $this->db()->statement( + "DROP TABLE {$this->tableName}" + ); + } + } finally { + parent::tearDown(); + } + } + + public function test_limit_returns_requested_rows(): void + { + $rows = $this->db()->table($this->tableName) + ->orderBy('ID') + ->limit(5) + ->get(); + + $this->assertCount(5, $rows); + $this->assertSame('Item 01', $rows[0]->NAME); + $this->assertSame('Item 05', $rows[4]->NAME); + } + + public function test_offset_skips_correct_rows(): void + { + $rows = $this->db()->table($this->tableName) + ->orderBy('ID') + ->offset(10) + ->limit(5) + ->get(); + + $this->assertCount(5, $rows); + $this->assertSame('Item 11', $rows[0]->NAME); + $this->assertSame('Item 15', $rows[4]->NAME); + } + + public function test_offset_without_limit(): void + { + $rows = $this->db()->table($this->tableName) + ->orderBy('ID') + ->offset(15) + ->get(); + + $this->assertCount(5, $rows); + $this->assertSame('Item 16', $rows[0]->NAME); + } + + public function test_standard_pagination(): void + { + $page = $this->db()->table($this->tableName) + ->orderBy('ID') + ->paginate(5, ['*'], 'page', 3); + + $this->assertSame(20, $page->total()); + $this->assertSame(4, $page->lastPage()); + $this->assertSame(3, $page->currentPage()); + $this->assertCount(5, $page->items()); + $this->assertSame('Item 11', $page->items()[0]->NAME); + } + + public function test_simple_pagination(): void + { + $page = $this->db()->table($this->tableName) + ->orderBy('ID') + ->simplePaginate(5, ['*'], 'page', 2); + + $this->assertSame(2, $page->currentPage()); + $this->assertCount(5, $page->items()); + $this->assertSame('Item 06', $page->items()[0]->NAME); + $this->assertTrue($page->hasMorePages()); + } + + public function test_insert_get_id_returns_generated_identity(): void + { + $id = $this->db()->table($this->tableName) + ->insertGetId(['NAME' => 'New Item']); + + $this->assertEquals(21, $id); + + $row = $this->db()->table($this->tableName) + ->where('ID', $id) + ->first(); + + $this->assertNotNull($row); + $this->assertSame('New Item', $row->NAME); + } + + public function test_pagination_does_not_duplicate_rows(): void + { + $ids = []; + + for ($page = 1; $page <= 4; $page++) { + $result = $this->db()->table($this->tableName) + ->orderBy('ID') + ->paginate(5, ['*'], 'page', $page); + + foreach ($result->items() as $row) { + $ids[] = (int) $row->ID; + } + } + + $this->assertCount(20, $ids); + $this->assertSame(range(1, 20), $ids); + } +} diff --git a/tests/Feature/Db2/RawQueryTest.php b/tests/Feature/Db2/RawQueryTest.php new file mode 100644 index 0000000..a6dd59a --- /dev/null +++ b/tests/Feature/Db2/RawQueryTest.php @@ -0,0 +1,29 @@ +db()->selectOne(" + SELECT + CAST('ordinary value' AS VARCHAR(30)) + AS \"data\", + CAST('1' AS VARCHAR(1)) + AS \"__db2_null_flag_0\" + FROM SYSIBM.SYSDUMMY1 + "); + + $this->assertSame('ordinary value', $row->data); + + $this->assertTrue( + property_exists($row, '__db2_null_flag_0') + ); + + $this->assertSame( + '1', + $row->__db2_null_flag_0 + ); + } +} diff --git a/tests/Feature/Db2/TransactionTest.php b/tests/Feature/Db2/TransactionTest.php new file mode 100644 index 0000000..d397382 --- /dev/null +++ b/tests/Feature/Db2/TransactionTest.php @@ -0,0 +1,217 @@ +tableName = 'DB2_TEST.DB2T_' . + strtoupper(bin2hex(random_bytes(6))); + + $this->db()->statement(" + CREATE TABLE {$this->tableName} ( + ID INTEGER NOT NULL PRIMARY KEY, + NAME VARCHAR(100) NOT NULL + ) + "); + } + + protected function tearDown(): void + { + try { + if ($this->tableName !== '') { + $db = $this->db(); + + while ($db->transactionLevel() > 0) { + $db->rollBack(); + } + + $db->statement("DROP TABLE {$this->tableName}"); + } + } finally { + parent::tearDown(); + } + } + + private function insertRow(int $id, string $name): void + { + $this->db()->table($this->tableName)->insert([ + 'ID' => $id, + 'NAME' => $name, + ]); + } + + private function rowCount(): int + { + return $this->db()->table($this->tableName)->count(); + } + + public function test_transaction_commit(): void + { + $this->db()->beginTransaction(); + + $this->insertRow(1, 'Committed'); + + $this->assertSame(1, $this->db()->transactionLevel()); + + $this->db()->commit(); + + $this->assertSame(0, $this->db()->transactionLevel()); + $this->assertSame(1, $this->rowCount()); + } + + public function test_transaction_rollback(): void + { + $this->db()->beginTransaction(); + + $this->insertRow(1, 'Rolled back'); + + $this->db()->rollBack(); + + $this->assertSame(0, $this->db()->transactionLevel()); + $this->assertSame(0, $this->rowCount()); + } + + public function test_transaction_closure_commits(): void + { + $result = $this->db()->transaction(function () { + $this->insertRow(1, 'Closure'); + + return 'success'; + }); + + $this->assertSame('success', $result); + $this->assertSame(1, $this->rowCount()); + $this->assertSame(0, $this->db()->transactionLevel()); + } + + public function test_transaction_closure_rolls_back_on_exception(): void + { + try { + $this->db()->transaction(function () { + $this->insertRow(1, 'Rollback'); + + throw new RuntimeException('Expected failure'); + }); + + $this->fail('Expected exception was not thrown.'); + } catch (RuntimeException $e) { + $this->assertSame('Expected failure', $e->getMessage()); + } + + $this->assertSame(0, $this->rowCount()); + $this->assertSame(0, $this->db()->transactionLevel()); + } + + public function test_nested_transaction_commit(): void + { + $db = $this->db(); + + $db->beginTransaction(); + $this->insertRow(1, 'Outer'); + + $db->beginTransaction(); + $this->insertRow(2, 'Inner'); + + $this->assertSame(2, $db->transactionLevel()); + + $db->commit(); + $this->assertSame(1, $db->transactionLevel()); + + $db->commit(); + + $this->assertSame(0, $db->transactionLevel()); + $this->assertSame(2, $this->rowCount()); + } + + public function test_nested_rollback_preserves_outer_transaction(): void + { + $db = $this->db(); + + $db->beginTransaction(); + $this->insertRow(1, 'Outer'); + + $db->beginTransaction(); + $this->insertRow(2, 'Inner'); + + $db->rollBack(); + + $this->assertSame(1, $db->transactionLevel()); + $this->assertSame(1, $this->rowCount()); + + $db->commit(); + + $this->assertSame(0, $db->transactionLevel()); + $this->assertSame(1, $this->rowCount()); + } + + public function test_nested_exception_preserves_outer_changes(): void + { + $db = $this->db(); + + $db->beginTransaction(); + $this->insertRow(1, 'Outer'); + + try { + $db->transaction(function () { + $this->insertRow(2, 'Inner'); + + throw new RuntimeException('Inner failure'); + }); + } catch (RuntimeException $e) { + $this->assertSame('Inner failure', $e->getMessage()); + } + + $this->assertSame(1, $db->transactionLevel()); + + $db->commit(); + + $this->assertSame(1, $this->rowCount()); + } + + public function test_sql_error_rolls_back_transaction(): void + { + $db = $this->db(); + + try { + $db->transaction(function () { + $this->insertRow(1, 'Valid'); + $this->insertRow(1, 'Duplicate'); + }); + + $this->fail('Expected duplicate-key exception.'); + } catch (QueryException $e) { + $this->assertSame('23505', $e->getCode()); + } + + $this->assertSame(0, $db->transactionLevel()); + $this->assertSame(0, $this->rowCount()); + } + + public function test_transaction_level_is_restored(): void + { + $db = $this->db(); + + $this->assertSame(0, $db->transactionLevel()); + + $db->beginTransaction(); + $this->assertSame(1, $db->transactionLevel()); + + $db->beginTransaction(); + $this->assertSame(2, $db->transactionLevel()); + + $db->rollBack(); + $this->assertSame(1, $db->transactionLevel()); + + $db->rollBack(); + $this->assertSame(0, $db->transactionLevel()); + } +} diff --git a/tests/Feature/Db2/UpsertTest.php b/tests/Feature/Db2/UpsertTest.php new file mode 100644 index 0000000..dac72ea --- /dev/null +++ b/tests/Feature/Db2/UpsertTest.php @@ -0,0 +1,258 @@ +tableName = 'DB2_TEST.DB2T_' . + strtoupper(bin2hex(random_bytes(6))); + + $this->db()->statement(" + CREATE TABLE {$this->tableName} ( + ID INTEGER NOT NULL, + CODE VARCHAR(30) NOT NULL, + NAME VARCHAR(100) NOT NULL, + STATUS VARCHAR(20) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT UQ_CODE UNIQUE (CODE) + ) + "); + + $this->db()->table($this->tableName)->insert([ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Original', + 'STATUS' => 'active', + ]); + } + + protected function tearDown(): void + { + try { + if ($this->tableName !== '') { + $this->db()->statement( + "DROP TABLE {$this->tableName}" + ); + } + } finally { + parent::tearDown(); + } + } + + public function test_upsert_inserts_new_row(): void + { + $this->db()->table($this->tableName)->upsert( + [[ + 'ID' => 2, + 'CODE' => 'A002', + 'NAME' => 'Second', + 'STATUS' => 'active', + ]], + ['ID'], + ['NAME', 'STATUS'] + ); + + $this->assertSame( + 'Second', + $this->db()->table($this->tableName) + ->where('ID', 2)->first()->NAME + ); + } + + public function test_upsert_updates_existing_row(): void + { + $this->db()->table($this->tableName)->upsert( + [[ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Updated', + 'STATUS' => 'inactive', + ]], + ['ID'], + ['NAME', 'STATUS'] + ); + + $row = $this->db()->table($this->tableName) + ->where('ID', 1)->first(); + + $this->assertSame('Updated', $row->NAME); + $this->assertSame('inactive', $row->STATUS); + } + + public function test_upsert_multiple_rows(): void + { + $this->db()->table($this->tableName)->upsert( + [ + [ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Changed', + 'STATUS' => 'active', + ], + [ + 'ID' => 2, + 'CODE' => 'A002', + 'NAME' => 'New', + 'STATUS' => 'active', + ], + ], + ['ID'], + ['NAME'] + ); + + $this->assertSame( + 2, + $this->db()->table($this->tableName)->count() + ); + + $this->assertSame( + 'Changed', + $this->db()->table($this->tableName) + ->where('ID', 1)->first()->NAME + ); + } + + public function test_upsert_preserves_unselected_columns(): void + { + $this->db()->table($this->tableName)->upsert( + [[ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Changed', + 'STATUS' => 'inactive', + ]], + ['ID'], + ['NAME'] + ); + + $row = $this->db()->table($this->tableName) + ->where('ID', 1)->first(); + + $this->assertSame('Changed', $row->NAME); + $this->assertSame('active', $row->STATUS); + } + + public function test_insert_or_ignore_inserts_new_row(): void + { + $this->db()->table($this->tableName)->insertOrIgnore([ + 'ID' => 2, + 'CODE' => 'A002', + 'NAME' => 'Second', + 'STATUS' => 'active', + ]); + + $this->assertSame( + 2, + $this->db()->table($this->tableName)->count() + ); + } + + public function test_insert_or_ignore_skips_duplicate(): void + { + $this->db()->table($this->tableName)->insertOrIgnore([ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Duplicate', + 'STATUS' => 'inactive', + ]); + + $this->assertSame( + 'Original', + $this->db()->table($this->tableName) + ->where('ID', 1)->first()->NAME + ); + } + + public function test_insert_or_ignore_multiple_rows(): void + { + $this->db()->table($this->tableName)->insertOrIgnore([ + [ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Duplicate', + 'STATUS' => 'inactive', + ], + [ + 'ID' => 2, + 'CODE' => 'A002', + 'NAME' => 'New', + 'STATUS' => 'active', + ], + ]); + + $this->assertSame( + 2, + $this->db()->table($this->tableName)->count() + ); + } + + public function test_insert_or_ignore_duplicate_unique_code(): void + { + $this->db()->table($this->tableName)->insertOrIgnore([ + 'ID' => 99, + 'CODE' => 'A001', + 'NAME' => 'Different', + 'STATUS' => 'inactive', + ]); + + $this->assertSame( + 1, + $this->db()->table($this->tableName)->count() + ); + + $this->assertSame( + 'Original', + $this->db()->table($this->tableName) + ->where('ID', 1)->first()->NAME + ); + } + + public function test_insert_or_ignore_does_not_hide_check_violations(): void + { + $this->expectException( + \Illuminate\Database\QueryException::class + ); + + $this->db()->table($this->tableName)->insertOrIgnore([ + 'ID' => 99, + 'CODE' => 'A099', + 'NAME' => 'Invalid', + 'STATUS' => null, + ]); + } + + public function test_update_or_insert(): void + { + $this->db()->table($this->tableName)->updateOrInsert( + ['ID' => 1], + ['NAME' => 'Updated'] + ); + + $this->db()->table($this->tableName)->updateOrInsert( + ['ID' => 2], + [ + 'CODE' => 'A002', + 'NAME' => 'Inserted', + 'STATUS' => 'active', + ] + ); + + $this->assertSame( + 'Updated', + $this->db()->table($this->tableName) + ->where('ID', 1)->first()->NAME + ); + + $this->assertSame( + 'Inserted', + $this->db()->table($this->tableName) + ->where('ID', 2)->first()->NAME + ); + } +} diff --git a/tests/Feature/Db2/UpsertTest.php.bak-20261111-103630 b/tests/Feature/Db2/UpsertTest.php.bak-20261111-103630 new file mode 100644 index 0000000..43ffcb0 --- /dev/null +++ b/tests/Feature/Db2/UpsertTest.php.bak-20261111-103630 @@ -0,0 +1,223 @@ +tableName = 'DB2_TEST.DB2T_' . + strtoupper(bin2hex(random_bytes(6))); + + $this->db()->statement(" + CREATE TABLE {$this->tableName} ( + ID INTEGER NOT NULL, + CODE VARCHAR(30) NOT NULL, + NAME VARCHAR(100) NOT NULL, + STATUS VARCHAR(20) NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT UQ_CODE UNIQUE (CODE) + ) + "); + + $this->db()->table($this->tableName)->insert([ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Original', + 'STATUS' => 'active', + ]); + } + + protected function tearDown(): void + { + try { + if ($this->tableName !== '') { + $this->db()->statement( + "DROP TABLE {$this->tableName}" + ); + } + } finally { + parent::tearDown(); + } + } + + public function test_upsert_inserts_new_row(): void + { + $this->db()->table($this->tableName)->upsert( + [[ + 'ID' => 2, + 'CODE' => 'A002', + 'NAME' => 'Second', + 'STATUS' => 'active', + ]], + ['ID'], + ['NAME', 'STATUS'] + ); + + $this->assertSame( + 'Second', + $this->db()->table($this->tableName) + ->where('ID', 2)->first()->NAME + ); + } + + public function test_upsert_updates_existing_row(): void + { + $this->db()->table($this->tableName)->upsert( + [[ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Updated', + 'STATUS' => 'inactive', + ]], + ['ID'], + ['NAME', 'STATUS'] + ); + + $row = $this->db()->table($this->tableName) + ->where('ID', 1)->first(); + + $this->assertSame('Updated', $row->NAME); + $this->assertSame('inactive', $row->STATUS); + } + + public function test_upsert_multiple_rows(): void + { + $this->db()->table($this->tableName)->upsert( + [ + [ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Changed', + 'STATUS' => 'active', + ], + [ + 'ID' => 2, + 'CODE' => 'A002', + 'NAME' => 'New', + 'STATUS' => 'active', + ], + ], + ['ID'], + ['NAME'] + ); + + $this->assertSame( + 2, + $this->db()->table($this->tableName)->count() + ); + + $this->assertSame( + 'Changed', + $this->db()->table($this->tableName) + ->where('ID', 1)->first()->NAME + ); + } + + public function test_upsert_preserves_unselected_columns(): void + { + $this->db()->table($this->tableName)->upsert( + [[ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Changed', + 'STATUS' => 'inactive', + ]], + ['ID'], + ['NAME'] + ); + + $row = $this->db()->table($this->tableName) + ->where('ID', 1)->first(); + + $this->assertSame('Changed', $row->NAME); + $this->assertSame('active', $row->STATUS); + } + + public function test_insert_or_ignore_inserts_new_row(): void + { + $this->db()->table($this->tableName)->insertOrIgnore([ + 'ID' => 2, + 'CODE' => 'A002', + 'NAME' => 'Second', + 'STATUS' => 'active', + ]); + + $this->assertSame( + 2, + $this->db()->table($this->tableName)->count() + ); + } + + public function test_insert_or_ignore_skips_duplicate(): void + { + $this->db()->table($this->tableName)->insertOrIgnore([ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Duplicate', + 'STATUS' => 'inactive', + ]); + + $this->assertSame( + 'Original', + $this->db()->table($this->tableName) + ->where('ID', 1)->first()->NAME + ); + } + + public function test_insert_or_ignore_multiple_rows(): void + { + $this->db()->table($this->tableName)->insertOrIgnore([ + [ + 'ID' => 1, + 'CODE' => 'A001', + 'NAME' => 'Duplicate', + 'STATUS' => 'inactive', + ], + [ + 'ID' => 2, + 'CODE' => 'A002', + 'NAME' => 'New', + 'STATUS' => 'active', + ], + ]); + + $this->assertSame( + 2, + $this->db()->table($this->tableName)->count() + ); + } + + public function test_update_or_insert(): void + { + $this->db()->table($this->tableName)->updateOrInsert( + ['ID' => 1], + ['NAME' => 'Updated'] + ); + + $this->db()->table($this->tableName)->updateOrInsert( + ['ID' => 2], + [ + 'CODE' => 'A002', + 'NAME' => 'Inserted', + 'STATUS' => 'active', + ] + ); + + $this->assertSame( + 'Updated', + $this->db()->table($this->tableName) + ->where('ID', 1)->first()->NAME + ); + + $this->assertSame( + 'Inserted', + $this->db()->table($this->tableName) + ->where('ID', 2)->first()->NAME + ); + } +}