diff --git a/README.md b/README.md index 420aaeee..a2142c54 100644 --- a/README.md +++ b/README.md @@ -40,4 +40,31 @@ composer require topthink/think-orm [![](https://www.topthink.com/uploads/assistant/20230630/4d1a3f0ad2958b49bb8189b7ef824cb0.png)](https://chat.topthink.com/) -ThinkPHP 生态服务由[顶想云](https://www.topthink.com)(TOPThink Cloud)提供,为生态提供专业的开发者服务和价值之选。 \ No newline at end of file +ThinkPHP 生态服务由[顶想云](https://www.topthink.com)(TOPThink Cloud)提供,为生态提供专业的开发者服务和价值之选。 + +## KingbaseES 使用注意事项 + +### Oracle 兼容模式的字段名称 + +在连接 DSN 的 `options` 中设置 `-c enable_upper_colname=off`,避免服务端自动将查询结果列名转为大写。业务输入、Model 主键及查询结果的字段键需要使用一致的大小写约定。 + +业务统一使用 `ID`、`NAME` 等大写字段键时,在连接配置的 `params` 中设置 `PDO::ATTR_CASE => PDO::CASE_UPPER`。原框架按该配置处理元数据字段键,PDO 按该配置处理查询结果列名,无需修改业务代码或自定义 Query 的父类。例如,以下为连接配置片段: + +```php +'dsn' => "kdb:host=127.0.0.1;port=15422;dbname=oracle;options='-c enable_upper_colname=off'", +'params' => [ + PDO::ATTR_CASE => PDO::CASE_UPPER, +], +``` + +主机、端口和数据库名称按实际环境填写;已有 `options` 或其他 PDO 参数时,应合并配置,不要覆盖原有设置。 + +业务使用精确小写或混合大小写字段名时,保留 `PDO::CASE_NATURAL`,不要强制设置 `CASE_UPPER`,以免改变字段名及显式别名。适配层不自动改写业务字段键,也不保证同一连接能够任意混用多套大小写约定。 + +更改大小写策略后,应重建连接并清理相应字段缓存;采用不同策略的连接不要共用同一份字段缓存。 + +### MySQL 兼容模式的多态关联分组 + +对于部分`has()`、`hasWhere()`生成的等值内连接查询,金仓构造器会在原关联外键分组后补充主表主键。适配前先读取物理目录,确认普通表、有效单列整数主键及同类型非空关联列,保留原WHERE、HAVING、软删除及参数绑定规则。 + +该处理仅覆盖已验证的简单小写物理表名、主表字段投影及单个内连接结构。复杂连接、外连接、继承/分区表、其他主键类型和分布式连接继续沿用原流程,不自动猜测改写。`fetchSql()`等只生成SQL的调用也沿用原分组规则,不为此适配额外访问数据库。 diff --git a/src/db/builder/KingbaseMysql.php b/src/db/builder/KingbaseMysql.php new file mode 100644 index 00000000..c8c277d1 --- /dev/null +++ b/src/db/builder/KingbaseMysql.php @@ -0,0 +1,125 @@ +getOptions(); + $groups = is_string($group) ? explode(',', $group) : array_values($group); + $joins = $options['join'] ?? []; + if (!$query->getModel() || !empty($options['fetch_sql']) || count($groups) !== 1 + || !is_string($groups[0]) || count($joins) !== 1) { + return parent::parseGroup($query, $group); + } + + $main = $this->parseGroupTable($options['table'] ?? null, $options['alias'] ?? []); + $join = reset($joins); + if (!$main || !is_array($join) || count($join) !== 3 + || !in_array($join[1], ['', 'INNER'], true) || !is_string($join[2]) + || array_values($options['field'] ?? []) !== [$main[1] . '.*']) { + return parent::parseGroup($query, $group); + } + + $related = $this->parseGroupTable($join[0]); + $identifier = '[A-Za-z_][A-Za-z0-9_]*'; + if (!$related || $main[1] === $related[1] + || !preg_match('/\A\s*(' . $identifier . ')\.(' . $identifier . ')\s*=\s*(' . $identifier . ')\.(' . $identifier . ')\s*\z/', $join[2], $on)) { + return parent::parseGroup($query, $group); + } + if ($on[1] === $related[1] && $on[3] === $main[1]) { + $on = ['', $on[3], $on[4], $on[1], $on[2]]; + } + if ($on[1] !== $main[1] || $on[3] !== $related[1] + || trim($groups[0]) !== $related[1] . '.' . $on[4]) { + return parent::parseGroup($query, $group); + } + + $connection = $query->getConnection(); + if (!$connection instanceof \think\db\connector\KingbaseMysql + || !empty($connection->getConfig('deploy')) + || !$connection->canSupplementGroupByPrimaryKey($main[0], $on[2], $related[0], $on[4])) { + return parent::parseGroup($query, $group); + } + $groups[] = $main[1] . '.' . $on[2]; + + return parent::parseGroup($query, $groups); + } + + /** 仅识别简单小写物理表名和普通别名,不猜测Raw、子查询及复杂引用。 */ + private function parseGroupTable($table, array $aliases = []): ?array + { + $alias = null; + if (is_array($table)) { + if (count($table) !== 1 || !is_string(key($table)) || !is_string(current($table))) { + return null; + } + $alias = current($table); + $table = key($table); + } + $identifier = '[A-Za-z_][A-Za-z0-9_]*'; + $tableName = '[a-z_][a-z0-9_]*'; + if (!is_string($table) || !preg_match('/\A' . $tableName . '(?:\.' . $tableName . ')?\z/', $table)) { + return null; + } + $alias = $alias ?? ($aliases[$table] ?? (str_contains($table, '.') ? substr($table, strrpos($table, '.') + 1) : $table)); + + return is_string($alias) && preg_match('/\A' . $identifier . '\z/', $alias) ? [$table, $alias] : null; + } + + /** + * 生成写入参数占位符,适配整数列的布尔绑定。 + * + * Model 的 bool 配置可能覆盖整数列的绑定类型;此时按实际字段绑定信息 + * 使用 1/0 整数参数,避免 PDO_KDB + * 发送 t/f。真正的 BOOLEAN 列、NULL 和其他绑定类型仍沿用原处理。 + * + * @param Query $query 当前查询对象 + * @param string $key 字段名或 JSON 路径 + * @param mixed $data 待绑定数据 + * @param array $bind 字段绑定类型映射 + * + * @return string SQL 参数占位表达式 + */ + protected function parseDataBind(Query $query, string $key, $data, array $bind = []): string + { + if (null !== $data && !($data instanceof Raw) && !str_contains($key, '->') + && Connection::PARAM_BOOL === ($bind[$key] ?? null)) { + // 读取连接器已有的字段缓存,不使用被 Model 类型配置覆盖的字段映射。 + $table = $query->getTable(); + $fieldBind = is_string($table) || (is_array($table) && 1 === count($table)) + ? $query->getConnection()->getTableInfo($table, 'bind') : []; + if (Connection::PARAM_INT === ($fieldBind[$key] ?? null)) { + $data = $data ? 1 : 0; + $bind[$key] = Connection::PARAM_INT; + } + } + + return parent::parseDataBind($query, $key, $data, $bind); + } +} diff --git a/src/db/builder/KingbaseOracle.php b/src/db/builder/KingbaseOracle.php new file mode 100644 index 00000000..f38db278 --- /dev/null +++ b/src/db/builder/KingbaseOracle.php @@ -0,0 +1,114 @@ +getOptions(); + $bind = $query->getFieldsBindType(); + + if (empty($options['field']) || '*' == $options['field']) { + $allowFields = array_keys($bind); + } else { + $allowFields = $options['field']; + } + + $values = []; + $insertFields = null; + + foreach ($dataSet as $data) { + $data = $this->parseData($query, $data, $allowFields, $bind); + + if (null === $insertFields) { + $insertFields = array_keys($data); + } + $values[] = '( ' . implode(',', array_values($data)) . ' )'; + } + + if (null === $insertFields) { + return ''; + } + + $fields = []; + foreach ($insertFields as $field) { + $fields[] = $this->parseKey($query, $field); + } + + return str_replace( + ['%INSERT%', '%TABLE%', '%EXTRA%', '%FIELD%', '%DATA%', '%COMMENT%'], + [ + !empty($options['replace']) ? 'REPLACE' : 'INSERT', + $this->parseTable($query, $options['table']), + $this->parseExtra($query, $options['extra']), + implode(' , ', $fields), + 'VALUES ' . implode(' , ', $values), + $this->parseComment($query, $options['comment']), + ], + $this->insertAllSql + ); + } + + /** 使用 VALUES 语法构造固定字段批量 INSERT。 */ + public function insertAllByKeys(Query $query, array $keys, array $datas): string + { + $options = $query->getOptions(); + $bind = $query->getFieldsBindType(); + $fields = []; + $values = []; + + foreach ($keys as $field) { + $fields[] = $this->parseKey($query, $field); + } + + foreach ($datas as $data) { + foreach ($data as $key => &$val) { + $field = $keys[$key]; + + if (!$query->isAutoBind()) { + $val = Connection::PARAM_STR == $bind[$field] ? '\'' . $val . '\'' : $val; + } else { + $val = $this->parseDataBind($query, $field, $val, $bind); + } + } + + $values[] = '( ' . implode(',', $data) . ' )'; + } + + return str_replace( + ['%INSERT%', '%TABLE%', '%EXTRA%', '%FIELD%', '%DATA%', '%COMMENT%'], + [ + !empty($options['replace']) ? 'REPLACE' : 'INSERT', + $this->parseTable($query, $options['table']), + $this->parseExtra($query, $options['extra']), + implode(' , ', $fields), + 'VALUES ' . implode(' , ', $values), + $this->parseComment($query, $options['comment']), + ], + $this->insertAllSql + ); + } +} diff --git a/src/db/builder/KingbaseSqlsrv.php b/src/db/builder/KingbaseSqlsrv.php new file mode 100644 index 00000000..bb35025f --- /dev/null +++ b/src/db/builder/KingbaseSqlsrv.php @@ -0,0 +1,19 @@ + + */ + protected array $kingbaseInitializedLinks = []; + + /** + * 根据 ThinkORM 连接配置生成三个兼容模式共用的 PDO_KDB DSN。 + * + * @param array $config 数据库连接配置 + * + * @return string kdb: 协议 DSN + */ + protected function parseDsn(array $config): string + { + $dsn = 'kdb:host=' . $config['hostname'] . ';dbname=' . $config['database']; + + if (!empty($config['hostport'])) { + $dsn .= ';port=' . $config['hostport']; + } + + return $dsn; + } + + /** MySQL 结果转换需要跟随运行时设置;其余模式保留原 PDO 创建流程。 */ + protected function createPdo($dsn, $username, $password, $params) + { + if ('mysql' === $this->getExpectedKingbaseMode()) { + return new \think\db\connector\KingbasePDO($dsn, $username, $password, $params); + } + + return parent::createPdo($dsn, $username, $password, $params); + } + + /** + * 建立 PDO_KDB 连接并初始化 KingbaseES 会话。 + * + * 在父连接器完成物理连接后校验驱动、数据库兼容模式并读取会话默认 Schema;连接失败时补充 + * 主机、端口及数据库名等诊断信息,同时保留 PDO 异常类型和安全错误信息,避免异常链泄露口令。 + * + * @param array $config 本次连接覆盖配置,为空时使用连接器默认配置 + * @param int $linkNum 连接编号,用于读写分离或多连接场景 + * @param array|bool $autoConnection 自动连接配置或是否启用自动连接 + * + * @throws \PDOException 物理连接失败 + * @throws \UnexpectedValueException 驱动或兼容模式不符合预期 + * @throws \InvalidArgumentException 当前会话的 Schema 标识符不合法 + * + * @return PDO 已完成 KingbaseES 会话初始化的 PDO 对象 + */ + public function connect(array $config = [], $linkNum = 0, $autoConnection = false): PDO + { + $mergedConfig = empty($config) ? $this->config : array_merge($this->config, $config); + + try { + $pdo = parent::connect($config, $linkNum, $autoConnection); + $this->initializeKingbaseSession($pdo); + + return $pdo; + } catch (\PDOException $e) { + $message = $this->formatKingbaseConnectionFailure($mergedConfig, $e); + throw \think\db\connector\KingbaseConnectionDiagnostics::exception( + $message, + $e, + (string) ($mergedConfig['password'] ?? '') + ); + } + } + + /** + * 关闭全部数据库连接并清理 KingbaseES 会话派生状态。 + * + * @return $this 当前连接器实例 + */ + public function close() + { + $this->kingbaseInitializedLinks = []; + + return parent::close(); + } + + /** + * 获取当前连接器要求的 KingbaseES 兼容模式。 + * + * @return string 兼容模式标识:mysql、oracle 或 sqlserver + */ + public function getKingbaseMode(): string + { + return $this->getExpectedKingbaseMode(); + } + + /** + * 从本次元数据查询实际使用的连接读取当前 Schema。 + * + * 路由与 getPDOStatement 一致,包含写后读主库和事务固定连接;每次直接 + * 读取都确认会话状态,不复用另一物理连接留下的 Schema。 + * + * @throws \InvalidArgumentException 当前 Schema 标识符不合法 + * + * @return string 当前有效的 Schema 名称 + */ + public function getKingbaseSchema(): string + { + $this->initConnect($this->readMaster); + return $this->validateKingbaseIdentifier( + (string) $this->linkID->query('SELECT current_schema()')->fetchColumn(), + 'current schema' + ); + } + + /** + * 返回具体连接器实现的 KingbaseES 兼容模式。 + * + * @return string 兼容模式标识 + */ + abstract protected function getExpectedKingbaseMode(): string; + + /** + * 将 KingbaseES 特殊字段映射为正确的 PDO 参数绑定类型。 + * + * 数组、范围、INTERVAL 和几何类型使用文本形式传输,避免其类型名中的 int + * 被通用规则误判为整数;仅 MySQL 模式的二进制字段自动使用 + * PDO::PARAM_LOB。Oracle、SQL Server 模式沿用原连接器的二进制字段 + * 类型映射;业务显式指定的 PDO 绑定类型不受影响。 + * + * @param string $type 数据库返回的原始字段类型 + * + * @return string ThinkORM 内部字段类型 + */ + protected function getFieldType(string $type): string + { + $normalizedType = strtolower(trim($type)); + + // point、int4range、interval 等复杂类型名包含 int。必须先按文本类型识别, + // 否则通用规则会使用 PDO::PARAM_INT,将 “{1,2,3}” 或 “[1,10)” 静默转换为 0。 + if (1 === preg_match('/(?:\[\]\s*$|^_)/', $normalizedType) + || 1 === preg_match('/(?:^|\b)(?:int4range|int8range|numrange|tsrange|tstzrange|daterange|range)(?:\b|$)/', $normalizedType) + || 1 === preg_match('/^(?:interval|point|line|lseg|box|path|polygon|circle)(?:\b|\s|\()/i', $normalizedType)) { + return 'string'; + } + + // 金仓将 MySQL 无符号整数报告为 uint2/uint4/uint8,统一按字符串绑定, + // 避免超出 PHP_INT_MAX 的 uint8 值在 PDO_KDB 发送到服务端之前, + // 因 PHP 整数转换而被截断。 + if (1 === preg_match('/^uint\d+$/i', $normalizedType)) { + return 'bigint'; + } + + if (1 === preg_match('/^bit(?:\s+varying)?\s*\((\d+)\)/i', trim($type), $match) + && (int) $match[1] > 1) { + return 'kingbase_bit_string'; + } + + if ('mysql' === $this->getExpectedKingbaseMode() + && 1 === preg_match('/blob|binary|bytea|\braw\b|\bimage\b/i', $type)) { + return 'kingbase_lob'; + } + + return parent::getFieldType($type); + } + + /** + * 根据内部字段类型返回 PDO 参数绑定类型。 + * + * @param string $type ThinkORM 内部字段类型 + * + * @return int PDO 参数类型常量 + */ + public function getFieldBindType(string $type): int + { + return match ($type) { + 'kingbase_lob' => PDO::PARAM_LOB, + 'kingbase_bit_string' => PDO::PARAM_STR, + default => parent::getFieldBindType($type), + }; + } + + /** + * 初始化并校验一个物理 PDO_KDB 连接。 + * + * 每个 PDO 对象仅检查一次;确认驱动名、服务器兼容模式并读取默认 Schema。 + * 不主动设置 search_path,不要求不同物理连接的默认 Schema 相同。 + * + * @param PDO $pdo 待初始化的物理连接 + * + * @throws \UnexpectedValueException 驱动或兼容模式不符合预期 + * @throws \InvalidArgumentException Schema 标识符不合法 + * + * @return void + */ + protected function initializeKingbaseSession(PDO $pdo): void + { + $hash = spl_object_hash($pdo); + if (isset($this->kingbaseInitializedLinks[$hash])) { + return; + } + + $driver = strtolower((string) $pdo->getAttribute(PDO::ATTR_DRIVER_NAME)); + if ('kdb' !== $driver) { + throw new \UnexpectedValueException('KingbaseES connector requires PDO_KDB, got PDO_' . $driver); + } + + $serverMode = strtolower((string) $pdo + ->query("SELECT current_setting('database_mode', true)") + ->fetchColumn()); + $expectedMode = $this->getExpectedKingbaseMode(); + if ($expectedMode !== $serverMode) { + throw new \UnexpectedValueException( + 'KES compatibility mode mismatch: configured ' . $expectedMode . ', server ' . $serverMode + ); + } + + // search_path 由数据库控制,不应用旧版 schema 配置。 + $this->validateKingbaseIdentifier( + (string) $pdo->query('SELECT current_schema()')->fetchColumn(), + 'current schema' + ); + + $this->kingbaseInitializedLinks[$hash] = true; + } + + /** + * 校验不带限定符的 KingbaseES 数据库对象标识符。 + * + * 只允许字母或下划线开头,后续可包含字母、数字、下划线、美元符号和井号, + * 确保会话返回的名称可供后续元数据读取使用。 + * + * @param string $value 待校验的标识符 + * @param string $label 错误信息中使用的对象说明 + * + * @throws \InvalidArgumentException 标识符格式不合法 + * + * @return string 去除首尾空白后的合法标识符 + */ + protected function validateKingbaseIdentifier(string $value, string $label): string + { + $value = trim($value); + if (1 !== preg_match('/^[A-Za-z_][A-Za-z0-9_$#]*$/', $value)) { + throw new \InvalidArgumentException('Invalid KES ' . $label . ': ' . $value); + } + + return $value; + } + + /** + * 生成不泄露凭据的 KingbaseES 连接失败信息。 + * + * @param array $config 当前连接配置 + * @param \PDOException $exception 原始 PDO 连接异常 + * + * @return string 单行且长度受限的诊断信息 + */ + protected function formatKingbaseConnectionFailure(array $config, \PDOException $exception): string + { + $details = []; + foreach (['hostname' => 'host', 'hostport' => 'port', 'database' => 'database'] as $key => $label) { + if (isset($config[$key]) && '' !== (string) $config[$key]) { + $details[] = $label . '=' . $this->sanitizeKingbaseDiagnostic((string) $config[$key]); + } + } + + $message = $exception->getMessage(); + $password = (string) ($config['password'] ?? ''); + if ('' !== $password) { + $message = str_replace($password, '***', $message); + } + + return 'KES connection failed (' . ($details ? implode(', ', $details) : 'parameters unavailable') . '): ' + . $this->sanitizeKingbaseDiagnostic($message); + } + + /** + * 清理并限制连接诊断文本。 + * + * 将换行和制表符替换为空格,并将文本限制在 500 字节内,便于日志和页面安全展示。 + * + * @param string $value 原始诊断文本 + * + * @return string 清理后的单行诊断文本 + */ + protected function sanitizeKingbaseDiagnostic(string $value): string + { + $value = trim(str_replace(["\r", "\n", "\t"], ' ', $value)); + + return strlen($value) > 500 ? substr($value, 0, 497) . '...' : $value; + } +} diff --git a/src/db/concern/KingbaseResult.php b/src/db/concern/KingbaseResult.php new file mode 100644 index 00000000..cd1b2886 --- /dev/null +++ b/src/db/concern/KingbaseResult.php @@ -0,0 +1,449 @@ +getExpectedKingbaseMode() || !$this->linkID) { + return $rows; + } + $fetchType = null === $statement ? $this->fetchType : PDO::FETCH_ASSOC; + if (!in_array($fetchType, [PDO::FETCH_ASSOC, PDO::FETCH_NUM, PDO::FETCH_BOTH], true)) { + return $rows; + } + $streams = []; + foreach ($rows as $index => $row) { + if (!is_array($row)) { + continue; + } + $columns = $columns ?? $this->getKingbaseResultColumns($statement ?? $this->PDOStatement); + foreach ($row as $key => $value) { + $map = PDO::FETCH_NUM === $fetchType ? 'position' : (PDO::FETCH_BOTH === $fetchType ? 'both' : 'named'); + $rule = $columns[$map][$key] ?? ''; + $rows[$index][$key] = $this->normalizeKingbaseValue($value, $rule, $streams); + } + } + + return $rows; + } + + /** 同名别名以最后一列为准,包括后列为未知类型时覆盖先前转换规则。 */ + protected function getKingbaseResultColumns(PDOStatement $statement): array + { + $columns = ['named' => [], 'position' => [], 'both' => []]; + if ('oracle' === $this->getExpectedKingbaseMode() || !$this->linkID) { + return $columns; + } + $case = $this->linkID->getAttribute(PDO::ATTR_CASE); + $unknownNames = false; + for ($i = 0, $count = $statement->columnCount(); $i < $count; ++$i) { + try { + $meta = $statement->getColumnMeta($i); + } catch (\PDOException $exception) { + // 可选的列元信息不可用时,不猜测查询结果的类型。 + $meta = false; + } + $rule = $this->getKingbaseResultRule($meta); + $columns['position'][$i] = $rule; + // FETCH_BOTH按列依次写数字位置和别名,后列可以覆盖先列数字键。 + $columns['both'][$i] = $rule; + if (is_array($meta) && isset($meta['name'])) { + $name = $meta['name']; + $name = PDO::CASE_LOWER === $case ? strtolower($name) + : (PDO::CASE_UPPER === $case ? strtoupper($name) : $name); + $columns['named'][$name] = $rule; + $columns['both'][$name] = $rule; + } else { + // 无名称的后列可能覆盖前列别名,不能继续套用旧别名规则。 + $unknownNames = true; + } + } + if ($unknownNames) { + $columns['named'] = []; + $columns['both'] = []; + } + + return $columns; + } + + protected function getKingbaseResultRule($meta): string + { + if (!is_array($meta)) { + return ''; + } + $type = strtolower((string) ($meta['native_type'] ?? '')); + $mode = $this->getExpectedKingbaseMode(); + if ('mysql' === $mode) { + if ($this->isMysqlBlobColumn($meta)) { + return 'blob'; + } + return match ($type) { + // FLOAT(M,D) 会返回非负的 precision,其固定小数位数规则 + // 不能被普通 FLOAT 的舍入规则替代。 + 'float4' => -1 === (int) ($meta['precision'] ?? -1) + && isset($meta['kdb:table_oid']) && (int) $meta['kdb:table_oid'] > 0 + ? 'mysqlFloat4' : 'mysqlFloat', + 'float8' => 'mysqlFloat', + 'bool' => 'mysqlBool', + 'uint8' => 'mysqlUnsigned', + 'bit' => 'mysqlBit', + default => '', + }; + } + if ('sqlserver' === $mode && in_array($type, + ['tinyint', 'smallint', 'int', 'integer', 'bigint', 'int2', 'int4', 'int8'], true)) { + $params = $this->config['params'] ?? []; + if (defined('PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE') + && !empty($params[constant('PDO::SQLSRV_ATTR_FETCHES_NUMERIC_TYPE')])) { + return ''; + } + return 'sqlsrvInteger'; + } + + return ''; + } + + /** NULL、文本、精确小数及未知值保持原样;不经浮点数中转大整数。 */ + protected function normalizeKingbaseValue($value, string $rule, array &$streams) + { + if (null === $value || '' === $rule) { + return $value; + } + if ('blob' === $rule) { + if (is_resource($value) && 'stream' === get_resource_type($value)) { + $id = (int) $value; + if (!array_key_exists($id, $streams)) { + $streams[$id] = $this->readMysqlBlobStream($value); + } + return $streams[$id]; + } + return $value; + } + if ('sqlsrvInteger' === $rule) { + return is_int($value) ? (string) $value : $value; + } + $stringify = $this->kingbaseStringifyFetches(); + if ('mysqlFloat4' === $rule) { + if (!is_int($value) && !is_float($value) && !(is_string($value) && is_numeric($value))) { + return $value; + } + // PDO_MYSQL/mysqlnd 将单精度值按六位有效数字返回。先还原 float32, + // 再执行舍入,避免 PDO_KDB 返回的简短小数文本影响 + // 恰好位于舍入边界的数值判断。 + $single = unpack('fvalue', pack('f', (float) $value))['value']; + if (!is_finite($single)) { + return $value; + } + $number = (float) sprintf('%.6H', $single); + return $stringify ? (string) $number : $number; + } + if ('mysqlFloat' === $rule) { + return !$stringify && (is_int($value) || is_float($value) || (is_string($value) && is_numeric($value))) + ? (float) $value : $value; + } + if ('mysqlBool' === $rule) { + if (is_bool($value) || in_array($value, ['t', 'f', '1', '0'], true)) { + $integer = true === $value || 't' === $value || '1' === $value ? 1 : 0; + return $stringify ? (string) $integer : $integer; + } + return $value; + } + if ('mysqlBit' === $rule && is_bool($value)) { + return $stringify ? ($value ? '1' : '0') : ($value ? 1 : 0); + } + if ('mysqlBit' === $rule && is_string($value) && preg_match('/^0x([0-9a-f]{1,16})$/iD', $value, $matches)) { + $value = $this->kingbaseHexToDecimal($matches[1]); + } + if (in_array($rule, ['mysqlBit', 'mysqlUnsigned'], true)) { + if (is_int($value)) { + return $stringify ? (string) $value : $value; + } + if (is_string($value) && preg_match('/^[0-9]+$/D', $value)) { + $decimal = ltrim($value, '0'); + $decimal = '' === $decimal ? '0' : $decimal; + $maximum = (string) PHP_INT_MAX; + if (!$stringify && (strlen($decimal) < strlen($maximum) + || (strlen($decimal) === strlen($maximum) && strcmp($decimal, $maximum) <= 0))) { + return (int) $decimal; + } + return $decimal; + } + } + + return $value; + } + + /** 尊重显式的 PDO 字符串化配置,不强行将其浮点数改回 float。 */ + protected function kingbaseStringifyFetches(): bool + { + if ($this->linkID instanceof \think\db\connector\KingbasePDO) { + return $this->linkID->getKingbaseStringifyFetches(); + } + if ($this->linkID) { + try { + $value = $this->linkID->getAttribute(PDO::ATTR_STRINGIFY_FETCHES); + if (false !== $value || in_array($this->linkID->errorCode(), [null, '00000'], true)) { + return (bool) (int) $value; + } + } catch (\PDOException $exception) { + // 自定义 PDO 不支持读取时,才回退到连接配置。 + } + } + $params = $this->config['params'] ?? []; + return (bool) (int) ($params[PDO::ATTR_STRINGIFY_FETCHES] ?? false); + } + + /** 逐位整数运算,将最多64位BIT的十六进制文本无损转为十进制字符串。 */ + protected function kingbaseHexToDecimal(string $hex): string + { + $decimal = '0'; + foreach (str_split($hex) as $digit) { + $carry = (int) hexdec($digit); + $next = ''; + for ($i = strlen($decimal) - 1; $i >= 0; --$i) { + $number = ((int) $decimal[$i]) * 16 + $carry; + $next = ($number % 10) . $next; + $carry = intdiv($number, 10); + } + while ($carry > 0) { + $next = ($carry % 10) . $next; + $carry = intdiv($carry, 10); + } + $decimal = ltrim($next, '0'); + if ('' === $decimal) { + $decimal = '0'; + } + } + return $decimal; + } + + /** + * 在模型组装和查询缓存之前,对齐已确认的原生驱动返回类型。 + * 存储过程的分组和切换仍由父类完成,每组通过 getResult(false) 转换。 + */ + protected function getResult(bool $procedure = false): array + { + $result = parent::getResult($procedure); + + return $procedure ? $result : $this->normalizeKingbaseRows($result); + } + + /** + * 游标逐行转换,不提前加载后续记录;模型取得的也是转换后的字段值。 + */ + public function getCursor(BaseQuery $query, string $sql, $model = null) + { + if ('oracle' === $this->getExpectedKingbaseMode()) { + yield from parent::getCursor($query, $sql, $model); + return; + } + $this->queryPDOStatement($query, $sql); + $columns = null; + + while ($result = $this->PDOStatement->fetch($this->fetchType)) { + $result = $this->normalizeKingbaseRows([$result], null, $columns)[0]; + if ($model) { + yield $model->newInstance($result); + } else { + yield $result; + } + } + } + + /** + * 保留父类取值及缓存流程;先区分无行,再按结果列类型转换。 + */ + public function value(BaseQuery $query, string $field, $default = null, bool $one = true) + { + if ('oracle' === $this->getExpectedKingbaseMode()) { + return parent::value($query, $field, $default, $one); + } + $options = $query->parseOptions(); + + if (isset($options['field'])) { + $query->removeOption('field'); + } + + if (isset($options['group'])) { + $query->group(''); + } + + $query->setOption('field', (array) $field); + + if (!empty($options['cache'])) { + $cacheItem = $this->parseCache($query, $options['cache'], 'value'); + if (empty($options['force_cache'])) { + $key = $cacheItem->getKey(); + + if ($this->cache->has($key)) { + $data = $this->cache->get($key); + if (null !== $data) { + return $data; + } + } + } + } + + $sql = $this->builder->select($query, $one); + + if (isset($options['field'])) { + $query->setOption('field', $options['field']); + } else { + $query->removeOption('field'); + } + + if (isset($options['group'])) { + $query->setOption('group', $options['group']); + } + + $pdo = $this->getPDOStatement($sql, $query->getBind(), $options['master']); + + // fetchColumn() 的 false 同时表示无行及布尔值 false,必须先区分。 + $row = $pdo->fetch(PDO::FETCH_NUM); + if (false === $row) { + $result = $default; + } else { + $values = array_values($row); + $columns = $this->getKingbaseResultColumns($pdo); + $streams = []; + $result = $this->normalizeKingbaseValue($values[0], $columns['position'][0] ?? '', $streams); + } + $requireCache = $query->getOption('cache_always') || !empty($result); + + if (isset($cacheItem) && $requireCache) { + $cacheItem->set($result); + $this->cacheData($cacheItem); + } + + return $result; + } + + /** + * 保留父类列提取流程;在数组索引组装及缓存之前对齐结果类型。 + */ + public function column(BaseQuery $query, string | array $column, string $key = ''): array + { + if ('oracle' === $this->getExpectedKingbaseMode()) { + return parent::column($query, $column, $key); + } + $options = $query->parseOptions(); + + if (isset($options['field'])) { + $query->removeOption('field'); + } + + if (empty($key) || trim($key) === '') { + $key = null; + } + + if (is_string($column)) { + $column = trim($column); + if ('*' !== $column) { + $column = array_map('trim', explode(',', $column)); + } + } elseif (in_array('*', $column)) { + $column = '*'; + } + + $field = $column; + if ('*' !== $column && $key && !in_array($key, $column)) { + $field[] = $key; + } + + $query->setOption('field', (array) $field); + + if (!empty($options['cache'])) { + $cacheItem = $this->parseCache($query, $options['cache'], 'column'); + if (empty($options['force_cache'])) { + $name = $cacheItem->getKey(); + + if ($this->cache->has($name)) { + $data = $this->cache->get($name); + if (null !== $data) { + return $data; + } + } + } + } + + $sql = $this->builder->select($query); + + if (isset($options['field'])) { + $query->setOption('field', $options['field']); + } else { + $query->removeOption('field'); + } + + $pdo = $this->getPDOStatement($sql, $query->getBind(), $options['master']); + $resultSet = $pdo->fetchAll(PDO::FETCH_ASSOC); + $resultSet = $this->normalizeKingbaseRows($resultSet, $pdo); + + if (is_string($key) && str_contains($key, '.')) { + [$alias, $key] = explode('.', $key); + } + + if (empty($resultSet)) { + $result = []; + } elseif ('*' !== $column && count($column) === 1) { + $column = array_shift($column); + if (str_contains($column, ' ')) { + $column = substr(strrchr(trim($column), ' '), 1); + } + + if (str_contains($column, '.')) { + [$alias, $column] = explode('.', $column); + } + + if (str_contains($column, '->')) { + $column = $this->builder->parseKey($query, $column); + } + + $result = array_column($resultSet, $column, $key); + } elseif ($key) { + $result = array_column($resultSet, null, $key); + } else { + $result = $resultSet; + } + + $requireCache = $query->getOption('cache_always') || !empty($result); + + if (isset($cacheItem) && $requireCache) { + $cacheItem->set($result); + $this->cacheData($cacheItem); + } + + return $result; + } + + /** 仅识别 PDO_KDB 报告的 BLOB/bytea 列,不将其他资源强制转为字符串。 */ + protected function isMysqlBlobColumn($meta): bool + { + return is_array($meta) && in_array(strtolower((string) ($meta['native_type'] ?? '')), + ['bytea', 'tinyblob', 'blob', 'mediumblob', 'longblob'], true); + } + + protected function readMysqlBlobStream($stream): string + { + $value = stream_get_contents($stream); + if (false === $value) { + throw new \RuntimeException('Unable to read KingbaseES MySQL BLOB result stream'); + } + + return $value; + } + +} + diff --git a/src/db/connector/Kingbase.php b/src/db/connector/Kingbase.php new file mode 100644 index 00000000..e493b309 --- /dev/null +++ b/src/db/connector/Kingbase.php @@ -0,0 +1,229 @@ +mode = KingbaseModeDetector::detect($config); + $config['kingbase_mode'] = $this->mode; + $config['type'] = KingbaseModeDetector::connectorType($this->mode); + $class = $this->resolveConnectorClass($this->mode); + $this->connector = new $class($config); + } + + /** + * 返回自动探测后使用的模式专用连接器。 + * + */ + public function getResolvedConnector(): ConnectionInterface + { + return $this->connector; + } + + /** + * 返回服务端实际兼容模式。 + */ + public function getKingbaseMode(): string + { + return $this->mode; + } + + /** + * 将规范化模式映射为模式专用连接器类。 + * + * @return class-string + */ + private function resolveConnectorClass(string $mode): string + { + return match ($mode) { + 'mysql' => KingbaseMysql::class, + 'oracle' => KingbaseOracle::class, + 'sqlserver' => KingbaseSqlsrv::class, + default => throw new \InvalidArgumentException('Unsupported KES database_mode: ' . $mode), + }; + } + + /** {@inheritdoc} 将查询类名获取请求转交模式专用连接器。 */ + public function getQueryClass(): string + { + return $this->connector->getQueryClass(); + } + + /** {@inheritdoc} 将连接建立请求转交模式专用连接器。 */ + public function connect(array $config = [], $linkNum = 0, $autoConnection = false) + { + return $this->connector->connect($config, $linkNum, $autoConnection); + } + + /** {@inheritdoc} 将数据库管理器设置转交模式专用连接器。 */ + public function setDb(DbManager $db) + { + $this->connector->setDb($db); + } + + /** {@inheritdoc} 将缓存对象设置转交模式专用连接器。 */ + public function setCache(CacheInterface $cache) + { + $this->connector->setCache($cache); + } + + /** {@inheritdoc} 将连接配置读取请求转交模式专用连接器。 */ + public function getConfig(string $config = '') + { + return $this->connector->getConfig($config); + } + + /** + * 关闭实际连接器并保持统一入口对象不变。 + * + * @return $this + */ + public function close() + { + $this->connector->close(); + + return $this; + } + + /** {@inheritdoc} 将单条记录查询转交模式专用连接器。 */ + public function find(BaseQuery $query): array + { + return $this->connector->find($query); + } + + /** {@inheritdoc} 将多条记录查询转交模式专用连接器。 */ + public function select(BaseQuery $query): array + { + return $this->connector->select($query); + } + + /** {@inheritdoc} 将单条数据插入转交模式专用连接器。 */ + public function insert(BaseQuery $query, bool $getLastInsID = false) + { + return $this->connector->insert($query, $getLastInsID); + } + + /** {@inheritdoc} 将批量数据插入转交模式专用连接器。 */ + public function insertAll(BaseQuery $query, array $dataSet = []): int + { + return $this->connector->insertAll($query, $dataSet); + } + + /** {@inheritdoc} 将数据更新转交模式专用连接器。 */ + public function update(BaseQuery $query): int + { + return $this->connector->update($query); + } + + /** {@inheritdoc} 将数据删除转交模式专用连接器。 */ + public function delete(BaseQuery $query): int + { + return $this->connector->delete($query); + } + + /** {@inheritdoc} 将单个字段值查询转交模式专用连接器。 */ + public function value(BaseQuery $query, string $field, $default = null) + { + return $this->connector->value($query, $field, $default); + } + + /** {@inheritdoc} 将指定列数据查询转交模式专用连接器。 */ + public function column(BaseQuery $query, string|array $column, string $key = ''): array + { + return $this->connector->column($query, $column, $key); + } + + /** {@inheritdoc} 将闭包事务处理转交模式专用连接器。 */ + public function transaction(callable $callback) + { + return $this->connector->transaction($callback); + } + + /** {@inheritdoc} 将事务开始操作转交模式专用连接器。 */ + public function startTrans() + { + return $this->connector->startTrans(); + } + + /** {@inheritdoc} 将事务提交操作转交模式专用连接器。 */ + public function commit() + { + return $this->connector->commit(); + } + + /** {@inheritdoc} 将事务回滚操作转交模式专用连接器。 */ + public function rollback() + { + return $this->connector->rollback(); + } + + /** {@inheritdoc} 保留原连接器接受的表名及数组别名形式。 */ + public function getTableFields($tableName): array + { + return $this->connector->getTableFields($tableName); + } + + /** {@inheritdoc} 将最近执行的 SQL 读取请求转交模式专用连接器。 */ + public function getLastSql(): string + { + return $this->connector->getLastSql(); + } + + /** {@inheritdoc} 将新增主键值读取请求转交模式专用连接器。 */ + public function getLastInsID(BaseQuery $query, ?string $sequence = null) + { + return $this->connector->getLastInsID($query, $sequence); + } + + /** + * 转发ConnectionInterface之外的ThinkORM连接方法。 + * + * Query、Model和Builder还会调用table、query、execute、newQuery、 + * getBuilder、getFields、getPk、pdo等连接器公开方法。统一入口通过 + * 此方法保持这些扩展接口与实际连接器完全一致。 + * + * @param string $method 方法名 + * @param array $arguments 参数列表 + * + * @return mixed + */ + public function __call(string $method, array $arguments) + { + $result = $this->connector->{$method}(...$arguments); + + return $result === $this->connector ? $this : $result; + } +} diff --git a/src/db/connector/KingbaseConnectionDiagnostics.php b/src/db/connector/KingbaseConnectionDiagnostics.php new file mode 100644 index 00000000..b3fd0413 --- /dev/null +++ b/src/db/connector/KingbaseConnectionDiagnostics.php @@ -0,0 +1,116 @@ + $original->getCode(), + 'trace' => self::safeTrace($failure->getTrace(), $password), + ]); + if (is_array($original->errorInfo)) { + $failure->errorInfo = self::safeErrorInfo($original->errorInfo, $password); + } + + return $failure; + } + + private static function needsSafeCopy(Throwable $exception, string $password): bool + { + if ('' !== $password && str_contains((string) $exception, $password)) { + return true; + } + do { + // 即使异常文本未包含凭据,调用参数或附带对象中仍可能包含凭据。 + foreach ($exception->getTrace() as $frame) { + if (array_key_exists('args', $frame) || array_key_exists('object', $frame)) { + return true; + } + } + if ($exception instanceof PDOException && is_array($exception->errorInfo) + && self::safeErrorInfo($exception->errorInfo, $password) !== $exception->errorInfo) { + return true; + } + $exception = $exception->getPrevious(); + } while ($exception); + + return false; + } + + private static function copyException(Throwable $original, string $password): Throwable + { + $message = self::redact($original->getMessage(), $password); + $copy = $original instanceof PDOException ? new PDOException($message) + : ($original instanceof \Error ? new \Error($message) : new \RuntimeException($message)); + self::setState($copy, [ + 'code' => $original->getCode(), + 'file' => self::redact($original->getFile(), $password), + 'line' => $original->getLine(), + 'trace' => self::safeTrace($original->getTrace(), $password), + 'previous' => $original->getPrevious() + ? self::copyException($original->getPrevious(), $password) : null, + ]); + if ($copy instanceof PDOException && is_array($original->errorInfo)) { + $copy->errorInfo = self::safeErrorInfo($original->errorInfo, $password); + } + + return $copy; + } + + /** 保留源码位置,不保留调用参数或附带对象。 */ + private static function safeTrace(array $trace, string $password): array + { + $safe = []; + foreach ($trace as $frame) { + $item = []; + foreach (['file', 'line', 'class', 'type', 'function'] as $key) { + if (isset($frame[$key]) && (is_string($frame[$key]) || is_int($frame[$key]))) { + $item[$key] = is_string($frame[$key]) + ? self::redact($frame[$key], $password) : $frame[$key]; + } + } + $safe[] = $item; + } + + return $safe; + } + + private static function safeErrorInfo(array $info, string $password): array + { + $safe = []; + foreach ($info as $key => $value) { + $key = is_string($key) ? self::redact($key, $password) : $key; + $safe[$key] = is_array($value) ? self::safeErrorInfo($value, $password) + : (is_string($value) ? self::redact($value, $password) + : (is_scalar($value) || null === $value ? $value : '[redacted]')); + } + + return $safe; + } + + private static function redact(string $value, string $password): string + { + return '' === $password ? $value : str_replace($password, '***', $value); + } + + /** 异常代码可能是 SQLSTATE 字符串,而构造函数仅接收整数代码。 */ + private static function setState(Throwable $exception, array $values): void + { + $base = $exception instanceof \Error ? \Error::class : \Exception::class; + foreach ($values as $name => $value) { + $property = new \ReflectionProperty($base, $name); + $property->setAccessible(true); + $property->setValue($exception, $value); + } + } +} diff --git a/src/db/connector/KingbaseModeDetector.php b/src/db/connector/KingbaseModeDetector.php new file mode 100644 index 00000000..e3853805 --- /dev/null +++ b/src/db/connector/KingbaseModeDetector.php @@ -0,0 +1,213 @@ + PDO::CASE_LOWER, + PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, + PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, + PDO::ATTR_STRINGIFY_FETCHES => false, + PDO::ATTR_EMULATE_PREPARES => false, + ]; + + try { + $pdo = new PDO( + $dsn, + (string) ($probeConfig['username'] ?? ''), + (string) ($probeConfig['password'] ?? ''), + $params + ); + + $driver = strtolower((string) $pdo->getAttribute(PDO::ATTR_DRIVER_NAME)); + if ('kdb' !== $driver) { + throw new \UnexpectedValueException( + 'KingbaseES automatic mode detection requires PDO_KDB, got PDO_' . $driver + ); + } + + $statement = $pdo->query("SELECT current_setting('database_mode', true)"); + // 静默或警告模式下,查询失败返回 false,而不是抛出 PDO 异常。 + if (false === $statement) { + $errorInfo = $pdo->errorInfo(); + $failure = new \PDOException('KES mode query failed [' . ($errorInfo[0] ?? 'HY000') + . ']: ' . ($errorInfo[2] ?? 'PDO::query() returned false')); + $failure->errorInfo = $errorInfo; + throw $failure; + } + $mode = self::normalizeMode((string) $statement->fetchColumn()); + $pdo = null; + } catch (\PDOException $exception) { + $message = self::sanitizeDiagnostic($exception->getMessage(), (string) ($probeConfig['password'] ?? '')); + $details = sprintf( + 'host=%s, port=%s, database=%s', + self::sanitizeDiagnostic((string) ($probeConfig['hostname'] ?? ''), ''), + self::sanitizeDiagnostic((string) ($probeConfig['hostport'] ?? ''), ''), + self::sanitizeDiagnostic((string) ($probeConfig['database'] ?? ''), '') + ); + throw KingbaseConnectionDiagnostics::exception( + 'KES mode detection failed (' . $details . '): ' . $message, + $exception, + (string) ($probeConfig['password'] ?? '') + ); + } + + if ('' === $mode) { + throw new \UnexpectedValueException('Unsupported or empty KES database_mode returned by server'); + } + + $configuredMode = self::configuredMode($config); + if ('' !== $configuredMode && $configuredMode !== $mode) { + throw new \UnexpectedValueException( + 'KES compatibility mode mismatch: configured ' . $configuredMode . ', server ' . $mode + ); + } + + return $mode; + } + + /** + * 将服务端模式映射为现有ThinkORM连接器类型。 + */ + public static function connectorType(string $mode): string + { + return match (self::normalizeMode($mode)) { + 'mysql' => 'kingbaseMysql', + 'oracle' => 'kingbaseOracle', + 'sqlserver' => 'kingbaseSqlsrv', + default => throw new \InvalidArgumentException('Unsupported KES database_mode: ' . $mode), + }; + } + + /** + * 读取可选的模式约束;省略时完全采用自动探测结果。 + */ + private static function configuredMode(array $config): string + { + foreach (['kingbase_mode', 'kdb_mode', 'mode'] as $key) { + if (isset($config[$key]) && '' !== trim((string) $config[$key])) { + $configured = strtolower(trim((string) $config[$key])); + if ('auto' === $configured) { + return ''; + } + $mode = self::normalizeMode($configured); + if ('' === $mode) { + throw new \InvalidArgumentException('Invalid configured KES mode: ' . $config[$key]); + } + + return $mode; + } + } + + return ''; + } + + /** + * 规范化数据库返回值及兼容别名。 + */ + private static function normalizeMode(string $mode): string + { + $mode = strtolower(trim($mode)); + + return match ($mode) { + 'mysql', 'kingbasemysql' => 'mysql', + 'oracle', 'kingbaseoracle' => 'oracle', + 'sqlsrv', 'sqlserver', 'kingbasesqlsrv', + 'kingbasesqlserver' => 'sqlserver', + default => '', + }; + } + + /** + * 自动探测只负责选择方言;读写分离的其他端点由正式连接器逐一二次校验。 + */ + private static function firstEndpoint(array $config): array + { + foreach (['hostname', 'hostport', 'database', 'username', 'password', 'dsn', 'charset'] as $key) { + if (!isset($config[$key])) { + continue; + } + if (is_array($config[$key])) { + $config[$key] = reset($config[$key]); + } elseif (!empty($config['deploy']) && is_string($config[$key]) && str_contains($config[$key], ',')) { + $config[$key] = explode(',', $config[$key], 2)[0]; + } + } + + return $config; + } + + /** + * 生成PDO_KDB DSN;显式DSN仍必须使用kdb协议。 + */ + private static function buildDsn(array $config): string + { + $dsn = trim((string) ($config['dsn'] ?? '')); + if ('' !== $dsn) { + if (!str_starts_with(strtolower($dsn), 'kdb:')) { + throw new \InvalidArgumentException('KingbaseES automatic mode detection requires a kdb: DSN'); + } + + return $dsn; + } + + $hostname = trim((string) ($config['hostname'] ?? '')); + $database = trim((string) ($config['database'] ?? '')); + if ('' === $hostname || '' === $database) { + throw new \InvalidArgumentException('KDB hostname and database are required for automatic mode detection'); + } + + $dsn = 'kdb:host=' . $hostname . ';dbname=' . $database; + if ('' !== trim((string) ($config['hostport'] ?? ''))) { + $dsn .= ';port=' . $config['hostport']; + } + + return $dsn; + } + + /** + * 对探测异常进行脱敏并限制为单行。 + */ + private static function sanitizeDiagnostic(string $value, string $password): string + { + if ('' !== $password) { + $value = str_replace($password, '***', $value); + } + $value = trim(str_replace(["\r", "\n", "\t"], ' ', $value)); + + return strlen($value) > 500 ? substr($value, 0, 497) . '...' : $value; + } +} diff --git a/src/db/connector/KingbaseMysql.php b/src/db/connector/KingbaseMysql.php new file mode 100644 index 00000000..e8ba1629 --- /dev/null +++ b/src/db/connector/KingbaseMysql.php @@ -0,0 +1,324 @@ + 0 AND b.attnum > 0 AND NOT a.attisdropped AND NOT b.attisdropped + AND a.attnotnull AND b.attnotnull AND a.atttypid = b.atttypid + AND a.atttypid IN ('pg_catalog.int2'::pg_catalog.regtype, + 'pg_catalog.int4'::pg_catalog.regtype, + 'pg_catalog.int8'::pg_catalog.regtype) + AND NOT EXISTS ( + SELECT 1 FROM pg_catalog.pg_inherits h + WHERE h.inhparent IN (p.oid, f.oid) OR h.inhrelid IN (p.oid, f.oid) + ) +SQL; + $statement = $this->getPDOStatement($sql, [ + 'main_table' => [$table, PDO::PARAM_STR], 'pk' => [$primaryKey, PDO::PARAM_STR], + 'joined_table' => [$joinedTable, PDO::PARAM_STR], 'fk' => [$foreignKey, PDO::PARAM_STR], + ]); + $result = false !== $statement->fetchColumn(); + $statement->closeCursor(); + + return $result; + } + + /** + * 将绑定值渲染为 KingbaseES MySQL 模式可执行的 SQL 字面量。 + * + * withCount 等流程会把 fetchSql 生成的子查询嵌入实际 SQL。原 Mysql 的 + * addslashes 转义依赖普通字符串的反斜杠规则,此处显式使用 E 字符串, + * 使转义不受 standard_conforming_strings 开关影响。保留原框架的类型 + * 处理及占位符替换规则,不建立连接,避免改变离线生成和 SQL 日志流程。 + * + * @param string $sql 带参数绑定的 SQL 语句 + * @param array $bind 参数绑定列表 + * + * @return string 渲染后的 SQL + */ + public function getRealSql(string $sql, array $bind = []): string + { + foreach ($bind as $key => $val) { + $value = strval(is_array($val) ? $val[0] : $val); + $type = is_array($val) ? $val[1] : self::PARAM_STR; + + if (self::PARAM_FLOAT == $type || self::PARAM_STR == $type) { + $value = "E'" . addslashes($value) . "'"; + } elseif (self::PARAM_INT == $type && '' === $value) { + $value = '0'; + } + + $sql = is_numeric($key) ? + substr_replace($sql, $value, strpos($sql, '?'), 1) : + str_replace( + [':' . $key . ' ', ':' . $key . ',', ':' . $key . ')'], + [$value . ' ', $value . ',', $value . ')'], + $sql . ' ' + ); + } + + return rtrim($sql); + } + + /** + * 保留 cursor(true) 的逐行读取调用,不设置 PDO_MYSQL 专属缓冲属性。 + * + * PDO_KDB 没有经验证的 MYSQL_ATTR_USE_BUFFERED_QUERY 对应能力;此处沿用 + * 现有 getCursor() 及结果转换流程,不依赖 PDO_MYSQL,也不承诺驱动级无缓冲。 + * + * @return \Generator + */ + protected function cursorUnbuffered(BaseQuery $query, string $sql) + { + yield from $this->getCursor($query, $sql, $query->getModel()); + } + + /** + * 读取 MySQL 兼容模式下的数据表字段元数据。 + * + * 从 information_schema 及系统目录中组合字段类型、可空性、默认值、主键、 + * 自增序列和注释,并转换成 ThinkORM 统一字段结构。 + * + * @param string $tableName 表名,可包含 Schema 和别名 + * + * @return array 以字段名为键的 ThinkORM 字段元数据 + */ + public function getFields(string $tableName): array + { + [$tableName] = explode(' ', $tableName); + $tableName = trim($tableName, '`"'); + + if (str_contains($tableName, '.')) { + [$schema, $tableName] = explode('.', $tableName, 2); + $schema = trim($schema, '`"'); + $tableName = trim($tableName, '`"'); + } else { + $schema = $this->getKingbaseSchema(); + } + + $schemaValue = $this->quoteString($schema); + $tableValue = $this->quoteString($tableName); + + $sql = <<getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + $info = []; + + foreach ($result as $val) { + $val = array_change_key_case($val); + $field = $val['field']; + + $info[$field] = [ + 'name' => $field, + 'type' => $val['full_type'] ?: $val['type'], + 'notnull' => 'NO' === strtoupper((string) $val['is_nullable']), + 'default' => $this->normalizeDefaultValue($val['default']), + 'primary' => (bool) $val['primary'], + 'autoinc' => '' !== (string) $val['attidentity'] || !empty($val['serial_sequence']), + 'comment' => $val['comment'], + ]; + } + + return $this->fieldCase($info); + } + + /** + * 将目录中的纯常量默认值转换为原 Mysql getFields() 的公开值。 + * + * 只解析完整字符串、数字和 NULL;函数、运算、未知或可能改变值的类型转换 + * 一律保留表达式原文。此方法不执行默认 SQL,也不经过 PHP int/float,避免 + * 大整数及小数精度丢失。普通 SQL 字符串保留反斜杠,仅 E 字符串解码转义。 + * + * @param mixed $value information_schema.columns.column_default + * @return mixed 常量值或未改动的默认表达式 + */ + protected function normalizeDefaultValue($value) + { + if (null === $value) { + return null; + } + if (is_int($value) || is_float($value) || is_bool($value)) { + return is_bool($value) ? ($value ? '1' : '0') : (string) $value; + } + if (!is_string($value)) { + return $value; + } + + $sql = trim($value); + $typeSchema = '(?:(?:(?i:pg_catalog)|"pg_catalog")\s*\.\s*)?'; + $textType = $typeSchema . '(?:(?i:text|varchar|character\s+varying)|"text"|"varchar")'; + $integerType = $typeSchema . '(?i:int2|int4|int8|smallint|integer|bigint|uint2|uint4|uint8)'; + $textCast = '(?:\s*::\s*' . $textType . ')?'; + + if (preg_match("~\\A'((?:''|[^'])*)'" . $textCast . '\\z~s', $sql, $match)) { + return str_replace("''", "'", $match[1]); + } + $escapePattern = <<<'REGEX' +~\A[Ee]'((?:''|\\.|[^'\\])*)' +REGEX; + if (preg_match($escapePattern . $textCast . '\z~s', $sql, $match)) { + $decoded = $this->decodeEscapeDefault(str_replace("''", "'", $match[1])); + return null === $decoded ? $value : $decoded; + } + if (preg_match('~\A(?i:NULL)(?:\s*::\s*(?:' . $textType . '|' . $integerType . '))?\z~', $sql)) { + return null; + } + if (preg_match('~\A([+-]?\d+)(?:\s*::\s*' . $integerType . ')?\z~', $sql, $match) + || preg_match("~\\A'([+-]?\\d+)'\\s*::\\s*" . $integerType . '\z~', $sql, $match)) { + $digits = ltrim($match[1], '+-0'); + return '' === $digits ? '0' : (str_starts_with($match[1], '-') ? '-' : '') . $digits; + } + if (preg_match('~\A[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?\z~', $sql)) { + return $sql; + } + + return $value; + } + + /** 解码目录明确标为 E 字符串的转义;不认识的形式保留原表达式。 */ + private function decodeEscapeDefault(string $body): ?string + { + $value = ''; + $simple = ['b' => "\x08", 'f' => "\x0c", 'n' => "\n", 'r' => "\r", 't' => "\t", "'" => "'", '"' => '"', '\\' => '\\']; + for ($i = 0, $length = strlen($body); $i < $length; ++$i) { + if ('\\' !== $body[$i]) { + $value .= $body[$i]; + continue; + } + if (++$i >= $length) { + return null; + } + $escape = $body[$i]; + if (isset($simple[$escape])) { + $value .= $simple[$escape]; + } elseif (preg_match('/\A[0-7]{1,3}/', substr($body, $i), $match)) { + $byte = octdec($match[0]); + if ($byte > 255) { + return null; + } + $value .= chr($byte); + $i += strlen($match[0]) - 1; + } elseif ('x' === $escape && preg_match('/\A[0-9a-fA-F]{1,2}/', substr($body, $i + 1), $match)) { + $value .= chr(hexdec($match[0])); + $i += strlen($match[0]); + } else { + return null; + } + } + return $value; + } + + /** + * 返回本连接器要求的 KingbaseES 兼容模式。 + * + * @return string 固定返回 mysql + */ + protected function getExpectedKingbaseMode(): string + { + return 'mysql'; + } + + /** + * 使用当前 PDO_KDB 连接转义元数据查询中的字符串字面量。 + * + * @param string $value 待转义字符串 + * + * @return string 包含引号的安全 SQL 字面量 + */ + protected function quoteString(string $value): string + { + $this->initConnect($this->readMaster); + + return $this->linkID->quote($value); + } +} diff --git a/src/db/connector/KingbaseOracle.php b/src/db/connector/KingbaseOracle.php new file mode 100644 index 00000000..b070b20b --- /dev/null +++ b/src/db/connector/KingbaseOracle.php @@ -0,0 +1,190 @@ +parseOracleTable($tableName); + $schema = $schema ?? $this->getKingbaseSchema(); + $schemaValue = $this->quoteString($schema); + $tableValue = $this->quoteString($tableName); + + $sql = <<getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + $info = []; + + foreach ($result as $val) { + $val = array_change_key_case($val); + $field = $val['field']; + + $info[$field] = [ + 'name' => $field, + 'type' => $val['type'], + 'notnull' => 'NO' === strtoupper((string) $val['is_nullable']), + 'default' => $val['default'], + 'primary' => (bool) $val['primary'], + 'autoinc' => (bool) $val['primary'], + ]; + } + + return $this->fieldCase($info); + } + + /** + * 沿用原 Oracle 序列读取流程,仅对齐 PDO_OCI 的字符串返回类型。 + * + * 序列选项、查询语句及异常处理均交给父连接器;不额外推断或改写序列名。 + * + * @param BaseQuery $query 当前查询对象,保留 ThinkORM 接口一致性 + * @param string|null $sequence 显式指定的序列名,可包含 Owner + * + * @return string|false|null 序列当前值,空结果沿用父连接器返回值 + */ + public function getLastInsID(BaseQuery $query, ?string $sequence = null) + { + $value = parent::getLastInsID($query, $sequence); + + return false === $value || null === $value ? $value : (string) $value; + } + + /** + * 拆分并规范化 Oracle 风格的 Schema 限定表名。 + * + * @param string $tableName 表名,可使用 schema.table 形式 + * + * @return array{0:string|null,1:string} 实际 Schema 与表名;未限定时首项为 null + */ + protected function parseOracleTable(string $tableName): array + { + $tableName = trim($tableName, '`'); + + if (str_contains($tableName, '.')) { + [$owner, $tableName] = explode('.', $tableName, 2); + + return [ + $this->normalizeOracleName($owner), + $this->normalizeOracleName($tableName), + ]; + } + + return [null, $this->normalizeOracleName($tableName)]; + } + + /** + * 规范化 Oracle 对象名的大小写。 + * + * 双引号包围的名称保留原大小写并移除外层引号,未加引号的名称转换为大写。 + * + * @param string $name 原始对象名 + * + * @return string 规范化后的对象名 + */ + protected function normalizeOracleName(string $name): string + { + $name = trim($name); + + if (str_starts_with($name, '"') && str_ends_with($name, '"')) { + return substr($name, 1, -1); + } + + return strtoupper(trim($name, '"')); + } + + /** + * 使用当前 PDO_KDB 连接转义元数据查询中的字符串字面量。 + * + * @param string $value 待转义字符串 + * + * @return string 包含引号的安全 SQL 字面量 + */ + protected function quoteString(string $value): string + { + $this->initConnect($this->readMaster); + + return $this->linkID->quote($value); + } + + /** + * 返回本连接器要求的 KingbaseES 兼容模式。 + * + * @return string 固定返回 oracle + */ + protected function getExpectedKingbaseMode(): string + { + return 'oracle'; + } +} diff --git a/src/db/connector/KingbasePDO.php b/src/db/connector/KingbasePDO.php new file mode 100644 index 00000000..f2d2cb22 --- /dev/null +++ b/src/db/connector/KingbasePDO.php @@ -0,0 +1,62 @@ +kingbasePersistentKey = hash('sha256', $key . ($poolName ? ':' . $persistent : '')); + } + if (array_key_exists(PDO::ATTR_STRINGIFY_FETCHES, $options ?? [])) { + $this->rememberKingbaseStringify((bool) (int) $options[PDO::ATTR_STRINGIFY_FETCHES]); + } + } + + /** 仅在原生调用成功后记录;失败或抛异常时保留原状态。 */ + public function setAttribute(int $attribute, mixed $value): bool + { + $result = parent::setAttribute($attribute, $value); + if ($result && PDO::ATTR_STRINGIFY_FETCHES === $attribute) { + // PDO 按整数选项处理该属性,例如字符串 "false" 等效于 0。 + $this->rememberKingbaseStringify((bool) (int) $value); + } + return $result; + } + + /** 返回本物理连接最后一次成功设置的字符串化状态。 */ + public function getKingbaseStringifyFetches(): bool + { + if (null !== $this->kingbasePersistentKey) { + return self::$kingbaseStringifyPools[$this->kingbasePersistentKey] ?? false; + } + return $this->kingbaseStringifyFetches; + } + + private function rememberKingbaseStringify(bool $value): void + { + $this->kingbaseStringifyFetches = $value; + if (null !== $this->kingbasePersistentKey) { + self::$kingbaseStringifyPools[$this->kingbasePersistentKey] = $value; + } + } +} diff --git a/src/db/connector/KingbaseSqlsrv.php b/src/db/connector/KingbaseSqlsrv.php new file mode 100644 index 00000000..48620a0e --- /dev/null +++ b/src/db/connector/KingbaseSqlsrv.php @@ -0,0 +1,33 @@ +