diff --git a/app/Database/Db2/Db2Connection.php b/app/Database/Db2/Db2Connection.php index 41ef160..f754fbb 100644 --- a/app/Database/Db2/Db2Connection.php +++ b/app/Database/Db2/Db2Connection.php @@ -25,28 +25,47 @@ class Db2Connection extends Connection $fetchUsing ); - foreach ($rows as $row) { - if (! is_object($row)) { + foreach ($rows as &$row) { + if (! is_object($row) && ! is_array($row)) { continue; } - foreach ($row as $key => $value) { - if ($value === Db2QueryGrammar::NULL_TIMESTAMP_SENTINEL) { - $row->{$key} = null; + $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; } - if ( - in_array($key, [ - 'two_factor_secret', - 'two_factor_recovery_codes', - ], true) - && $value === Db2QueryGrammar::NULL_STRING_SENTINEL - ) { - $row->{$key} = null; - } + $result[$key] = $value; + $previousColumn = $key; } + + $row = is_object($row) + ? (object) $result + : $result; } + unset($row); return $rows; } diff --git a/app/Database/Db2/Db2QueryGrammar.php b/app/Database/Db2/Db2QueryGrammar.php index 7723df5..0368b3d 100644 --- a/app/Database/Db2/Db2QueryGrammar.php +++ b/app/Database/Db2/Db2QueryGrammar.php @@ -61,119 +61,188 @@ class Db2QueryGrammar extends Grammar { 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 + ! 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); + ->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'); + $columns = array_column( + $this->db2ColumnCache[$table], + 'name' + ); } - $ordinary = []; - $lobs = []; - $changed = false; + $parsed = []; + $aliases = []; + // Validate the complete selection before modifying any SQL. foreach ($columns as $column) { - // Expressions and partial wildcards cannot be safely rearranged. - 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 - )) { + 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']); - $selected = $column; + $nullable = (bool) ($info['nullable'] ?? false); - // Work around PDO_ODBC attempting a 4 GiB allocation -// when fetching NULL Fortify VARCHAR(4096) columns. - if ( - ($info['nullable'] ?? false) - && $type === 'VARCHAR' - && in_array($name, [ - 'two_factor_secret', - 'two_factor_recovery_codes', - ], true) - ) { - $alias = isset($matches[2]) - ? trim($matches[2], '"') - : $name; - - $wrapped = $this->wrap($identifier); - - $selected = new Expression( - 'COALESCE(' - . $wrapped - . ", CAST('__DB2_NULL_STRING__' AS VARCHAR(4096))) AS " - . $this->wrap($alias) - ); - - $changed = true; - } - - if (($info['nullable'] ?? false) && in_array($type, ['TIMESTAMP', 'DATE', 'TIME'], true)) { - // Never return a SQL NULL date/time to the broken PDO_ODBC - // retrieval path. Use a non-NULL character expression instead. - $format = match ($type) { - 'DATE' => 'YYYY-MM-DD', - 'TIME' => 'HH24:MI:SS', - default => 'YYYY-MM-DD HH24:MI:SS.FF6', - }; - $alias = isset($matches[2]) ? trim($matches[2], '"') : $name; - $wrapped = $this->wrap($identifier); - $selected = new Expression( - 'CASE WHEN '.$wrapped.' IS NULL THEN '. - "'".self::NULL_TIMESTAMP_SENTINEL."'". - ' ELSE VARCHAR_FORMAT('.$wrapped.", '".$format."') END AS ". - $this->wrap($alias) - ); - $changed = true; - } + $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 !== [] && $columns !== array_merge( - array_filter($ordinary, 'is_string'), - array_filter($lobs, 'is_string') - )) { + if ($lobs !== [] && $ordinary !== []) { $changed = true; } - if (! $changed && $lobs === []) { + if (! $changed) { return parent::compileSelect($query); } $modified = clone $query; $modified->columns = array_merge($ordinary, $lobs); + return parent::compileSelect($modified); } }