From 0237846e2ee0dfb0c076a29f847f537fd33e702d Mon Sep 17 00:00:00 2001 From: Leec0nAn <1148768305@qq.com> Date: Wed, 21 Oct 2026 20:34:58 +0800 Subject: [PATCH 1/6] feat: add KingbaseES support --- src/db/builder/KingbaseMysql.php | 100 +++ src/db/builder/KingbaseOracle.php | 182 +++++ src/db/builder/KingbaseSqlsrv.php | 217 ++++++ src/db/connector/Kingbase.php | 230 ++++++ src/db/connector/KingbaseModeDetector.php | 204 ++++++ src/db/connector/KingbaseMysql.php | 217 ++++++ src/db/connector/KingbaseOracle.php | 406 +++++++++++ src/db/connector/KingbaseSqlsrv.php | 448 ++++++++++++ .../connector/concern/KingbaseConnection.php | 654 ++++++++++++++++++ src/model/type/KingbaseDateTime.php | 39 ++ 10 files changed, 2697 insertions(+) create mode 100644 src/db/builder/KingbaseMysql.php create mode 100644 src/db/builder/KingbaseOracle.php create mode 100644 src/db/builder/KingbaseSqlsrv.php create mode 100644 src/db/connector/Kingbase.php create mode 100644 src/db/connector/KingbaseModeDetector.php create mode 100644 src/db/connector/KingbaseMysql.php create mode 100644 src/db/connector/KingbaseOracle.php create mode 100644 src/db/connector/KingbaseSqlsrv.php create mode 100644 src/db/connector/concern/KingbaseConnection.php create mode 100644 src/model/type/KingbaseDateTime.php diff --git a/src/db/builder/KingbaseMysql.php b/src/db/builder/KingbaseMysql.php new file mode 100644 index 00000000..18fbf684 --- /dev/null +++ b/src/db/builder/KingbaseMysql.php @@ -0,0 +1,100 @@ +')) { + return 'CAST(' . $placeholder . ' AS TEXT)'; + } + + return $placeholder; + } + + /** + * 将兼容函数使用的字符串占位符显式转换为 TEXT。 + * + * Raw 表达式保持原样解析,冒号开头的绑定占位符增加 CAST,其余值直接转为字符串。 + * + * @param Query $query 当前查询对象 + * @param mixed $value 原始值、占位符或 Raw 表达式 + * + * @return string 可拼入 SQL 的文本表达式 + */ + protected function parseTextValue(Query $query, $value): string + { + if ($value instanceof Raw) { + return $this->parseRaw($query, $value); + } + + if (is_string($value) && str_starts_with($value, ':')) { + return 'CAST(' . $value . ' AS TEXT)'; + } + + return (string) $value; + } + + /** + * 构造 MySQL 兼容模式的 REGEXP 条件。 + * + * @param Query $query 当前查询对象 + * @param string $key 已解析的字段表达式 + * @param string $exp 正则运算符 + * @param mixed $value 匹配值或绑定占位符 + * @param string $field 原始字段名,保留父方法接口一致性 + * + * @return string REGEXP 条件 SQL + */ + protected function parseRegexp(Query $query, string $key, string $exp, $value, string $field): string + { + return $key . ' ' . $exp . ' ' . $this->parseTextValue($query, $value); + } + + /** + * 构造 MySQL 兼容模式的 FIND_IN_SET 条件。 + * + * @param Query $query 当前查询对象 + * @param string $key 已解析的字段表达式 + * @param string $exp 查询运算符,保留父方法接口一致性 + * @param mixed $value 待查找值或绑定占位符 + * @param string $field 原始字段名,保留父方法接口一致性 + * + * @return string FIND_IN_SET 函数 SQL + */ + protected function parseFindInSet(Query $query, string $key, string $exp, $value, string $field): string + { + return 'FIND_IN_SET(' . $this->parseTextValue($query, $value) . ', ' . $key . ')'; + } +} diff --git a/src/db/builder/KingbaseOracle.php b/src/db/builder/KingbaseOracle.php new file mode 100644 index 00000000..8688929e --- /dev/null +++ b/src/db/builder/KingbaseOracle.php @@ -0,0 +1,182 @@ +selectSql; + $selectMode = $this->kingbaseSelect; + $this->selectSql = $this->plainSelectSql; + $this->kingbaseSelect = true; + try { + return parent::select($query, $one); + } finally { + $this->selectSql = $selectSql; + $this->kingbaseSelect = $selectMode; + } + } + + /** + * SELECT 使用 LIMIT/OFFSET,写语句继续沿用父方言的处理。 + * + * @param Query $query 当前查询对象 + * @param string $limit 数量或“偏移量,数量” + * @return string 分页子句 + * @throws \InvalidArgumentException 分页参数不是非负整数 + */ + protected function parseLimit(Query $query, string $limit): string + { + if (!$this->kingbaseSelect) { + return parent::parseLimit($query, $limit); + } + if ('' === $limit) { + return ''; + } + if (!preg_match('/^\d+(?:,\d+)?$/D', $limit)) { + throw new \InvalidArgumentException('Invalid KES pagination: ' . $limit); + } + $parts = explode(',', $limit); + return count($parts) === 2 + ? ' LIMIT ' . $parts[1] . ' OFFSET ' . $parts[0] + : ' LIMIT ' . $parts[0]; + } + + /** + * 构造 Oracle 兼容模式 INSERT,并将 REPLACE 请求降级为普通 INSERT。 + * + * Oracle 兼容模式不支持 REPLACE。ThinkORM 写入多对多中间表时可能内部启用 + * replace 选项,因此生成 SQL 期间临时关闭该选项,随后恢复;重复数据仍由 + * 中间表的主键或唯一约束阻止。 + * + * @param Query $query 当前查询对象 + * + * @return string 完整 INSERT SQL + */ + public function insert(Query $query): string + { + $replace = (bool) $query->getOption('replace'); + if (!$replace) { + return parent::insert($query); + } + + $query->setOption('replace', false); + try { + return parent::insert($query); + } finally { + $query->setOption('replace', true); + } + } + + /** + * 生成 Oracle 兼容模式随机排序表达式。 + * + * KingbaseES Oracle 兼容模式未暴露 DBMS_RANDOM 包,因此使用 random()。 + * + * @param Query $query 当前查询对象,保留父方法接口一致性 + * + * @return string random() 表达式 + */ + protected function parseRand(Query $query): string + { + return 'random()'; + } + + /** + * 解析字段和表标识符,并适配 Oracle 未引用对象名的大写规则。 + * + * 支持整数、Raw 表达式、JSON 路径、表别名及严格模式校验;普通字段和表名 + * 转换为大写后使用双引号引用。 + * + * @param Query $query 当前查询对象 + * @param string|int|Raw $key 字段名、数字或 Raw 表达式 + * @param bool $strict 是否启用标识符严格校验 + * + * @throws Exception 严格模式下标识符包含不支持的内容 + * + * @return string 可安全拼入 SQL 的标识符或表达式 + */ + public function parseKey(Query $query, string|int|Raw $key, bool $strict = false): string + { + if (is_int($key)) { + return (string) $key; + } + + if ($key instanceof Raw) { + return $this->parseRaw($query, $key); + } + + $key = trim($key); + + if (str_contains($key, '->') && !str_contains($key, '(')) { + [$field, $name] = explode('->', $key, 2); + + return $this->parseKey($query, $field, true) . '."' . strtoupper($name) . '"'; + } + + if (str_contains($key, '.') && !preg_match('/[,\'\"\(\)\[\s]/', $key)) { + [$table, $key] = explode('.', $key, 2); + + $alias = $query->getOption('alias'); + + if ('__TABLE__' == $table) { + $table = $query->getOption('table'); + $table = is_array($table) ? array_shift($table) : $table; + } + + if (isset($alias[$table])) { + $table = $alias[$table]; + } + } + + if ($strict && !preg_match('/^[\w\.\*]+$/', $key)) { + throw new Exception('not support data:' . $key); + } + + if ('*' != $key && !preg_match('/[,\'\"\*\(\)\[.\s]/', $key)) { + $key = '"' . strtoupper($key) . '"'; + } + + if (isset($table)) { + $key = '"' . strtoupper($table) . '".' . $key; + } + + return $key; + } +} diff --git a/src/db/builder/KingbaseSqlsrv.php b/src/db/builder/KingbaseSqlsrv.php new file mode 100644 index 00000000..c51b9ef5 --- /dev/null +++ b/src/db/builder/KingbaseSqlsrv.php @@ -0,0 +1,217 @@ +selectSql; + $selectMode = $this->kingbaseSelect; + $this->selectSql = $this->plainSelectSql; + $this->kingbaseSelect = true; + try { + return parent::select($query, $one); + } finally { + $this->selectSql = $selectSql; + $this->kingbaseSelect = $selectMode; + } + } + + /** + * SELECT 使用 LIMIT/OFFSET,写语句继续沿用父方言的处理。 + * + * @param Query $query 当前查询对象 + * @param string $limit 数量或“偏移量,数量” + * @return string 分页子句 + * @throws \InvalidArgumentException 分页参数不是非负整数 + */ + protected function parseLimit(Query $query, string $limit): string + { + if (!$this->kingbaseSelect) { + return parent::parseLimit($query, $limit); + } + if ('' === $limit) { + return ''; + } + if (!preg_match('/^\d+(?:,\d+)?$/D', $limit)) { + throw new \InvalidArgumentException('Invalid KES pagination: ' . $limit); + } + $parts = explode(',', $limit); + return count($parts) === 2 + ? ' LIMIT ' . $parts[1] . ' OFFSET ' . $parts[0] + : ' LIMIT ' . $parts[0]; + } + + /** + * 原生分页不需要默认随机排序,显式排序仍使用父方言。 + * + * @param Query $query 当前查询对象 + * @param array $order 排序配置 + * @return string 排序子句 + */ + protected function parseOrder(Query $query, array $order): string + { + return $this->kingbaseSelect && empty($order) ? '' : parent::parseOrder($query, $order); + } + + /** + * 构造 INSERT SELECT,避免父实现永久修改共享查询模板。 + * + * @param Query $query 源查询对象 + * @param array $fields 目标字段列表 + * @param string $table 目标表名 + * @return string INSERT SELECT SQL,支持源查询排序与分页 + */ + public function selectInsert(Query $query, array $fields, string $table): string + { + $fields = array_map(fn ($field) => $this->parseKey($query, $field, true), $fields); + return 'INSERT INTO ' . $this->parseTable($query, $table) + . ' (' . implode(',', $fields) . ') ' . $this->select($query); + } + + /** + * 使用 VALUES 语法构造多行 INSERT。 + * + * 避免父 SQL Server 方言的 UNION SELECT 批量写法,使 KingbaseES 能依据目标列 + * 正确推断每个占位符的数据类型。 + * + * @param Query $query 当前查询对象 + * @param array $dataSet 多行待插入数据 + * + * @return string 完整批量 INSERT SQL + * @throws \InvalidArgumentException 各行字段集合不一致或为空 + */ + public function insertAll(Query $query, array $dataSet): string + { + $options = $query->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); + } + if (!$insertFields || count($data) !== count($insertFields) + || array_diff($insertFields, array_keys($data))) { + throw new \InvalidArgumentException('KES batch insert requires the same non-empty fields in every row'); + } + $row = []; + foreach ($insertFields as $field) { + $row[] = $data[$field]; + } + $values[] = '( ' . implode(',', $row) . ' )'; + } + + if (null === $insertFields) { + return ''; + } + $fields = []; + foreach ($insertFields as $field) { + $fields[] = $this->parseKey($query, $field); + } + + return str_replace( + ['%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'], + [ + $this->parseTable($query, $options['table']), + implode(' , ', $fields), + 'VALUES ' . implode(' , ', $values), + $this->parseComment($query, $options['comment']), + ], + $this->insertAllSql + ); + } + + /** + * 按固定字段集合使用 VALUES 语法构造多行 INSERT。 + * + * 根据查询是否启用自动绑定生成字面量或参数占位符,并确保所有行复用同一字段顺序。 + * + * @param Query $query 当前查询对象 + * @param array $keys 固定字段名列表 + * @param array $datas 按字段顺序组织的多行数据 + * + * @return string 完整批量 INSERT SQL + */ + 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( + ['%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'], + [ + $this->parseTable($query, $options['table']), + implode(' , ', $fields), + 'VALUES ' . implode(' , ', $values), + $this->parseComment($query, $options['comment']), + ], + $this->insertAllSql + ); + } +} diff --git a/src/db/connector/Kingbase.php b/src/db/connector/Kingbase.php new file mode 100644 index 00000000..6bf537c3 --- /dev/null +++ b/src/db/connector/Kingbase.php @@ -0,0 +1,230 @@ +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) + { + return $this->connector->connect($config, $linkNum); + } + + /** {@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(string $tableName): array + { + return $this->connector->getTableFields($tableName); + } + + /** {@inheritdoc} */ + 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/KingbaseModeDetector.php b/src/db/connector/KingbaseModeDetector.php new file mode 100644 index 00000000..c4b23bb7 --- /dev/null +++ b/src/db/connector/KingbaseModeDetector.php @@ -0,0 +1,204 @@ + 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 + ); + } + + $mode = self::normalizeMode((string) $pdo + ->query("SELECT current_setting('database_mode', true)") + ->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'] ?? ''), '') + ); + $code = is_numeric($exception->getCode()) ? (int) $exception->getCode() : 0; + + throw new \PDOException('KES mode detection failed (' . $details . '): ' . $message, $code, $exception); + } + + 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'] as $key) { + if (!isset($config[$key])) { + continue; + } + if (is_array($config[$key])) { + $config[$key] = reset($config[$key]); + } elseif (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..6acfbeb7 --- /dev/null +++ b/src/db/connector/KingbaseMysql.php @@ -0,0 +1,217 @@ +getSchemaName(); + } + + $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' => $val['default'], + 'primary' => (bool) $val['primary'], + 'autoinc' => '' !== (string) $val['attidentity'] || !empty($val['serial_sequence']), + 'sequence' => $val['serial_sequence'] ?: null, + 'comment' => $val['comment'], + ]; + } + + return $this->fieldCase($info); + } + + /** + * 获取指定 Schema 下的基础表列表。 + * + * @param string $dbName Schema 名,为空时使用当前连接的 Schema + * + * @return array 表名列表 + */ + public function getTables(string $dbName = ''): array + { + $schema = $dbName ?: $this->getSchemaName(); + $schemaValue = $this->quoteString($schema); + $sql = <<getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + + return array_column($result, 'table_name'); + } + + /** + * 获取最近一次插入产生的自增主键。 + * + * PDO_KDB 当前未实现可靠的 lastInsertId(),因此在同一物理连接上直接 + * 调用 LAST_INSERT_ID() 取得 MySQL 兼容模式生成值。 + * + * @param string|null $sequence 可选序列名,保留父连接器接口兼容性 + * + * @return mixed 自增主键值,无法取得时返回空字符串 + */ + public function getAutoID(?string $sequence = null) + { + return $this->resolveKingbaseGeneratedKey(function () { + $pdo = $this->linkID->query('SELECT LAST_INSERT_ID() AS id'); + $result = $pdo->fetch(PDO::FETCH_ASSOC); + + return isset($result['id']) ? (string) $result['id'] : ''; + }); + } + + /** + * 获取已配置并经服务器确认的 Schema 名称。 + * + * @return string 当前 Schema 名称 + */ + protected function getSchemaName(): string + { + return $this->getKingbaseSchema(); + } + + /** + * 返回本连接器要求的 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(true); + + 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..67874465 --- /dev/null +++ b/src/db/connector/KingbaseOracle.php @@ -0,0 +1,406 @@ + 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, + ]; + + /** + * 根据 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; + } + + /** + * 读取 Oracle 兼容模式下的数据表字段元数据。 + * + * 未指定 Owner 时查询 USER_* 视图,指定 Owner 时查询 ALL_* 视图,并将字段、 + * 主键、可空性、默认值和注释转换成 ThinkORM 统一字段结构。自动生成标记单独 + * 从 Identity 和默认序列读取,不再将普通主键视为自增。 + * + * @param string $tableName 表名,可包含 Owner 和别名 + * + * @return array 以小写字段名为键的 ThinkORM 字段元数据 + */ + public function getFields(string $tableName): array + { + [$tableName] = explode(' ', $tableName); + [$owner, $tableName] = $this->parseOracleTable($tableName); + + if (null === $owner) { + $tableValue = $this->quoteString($tableName); + $sql = <<quoteString($owner); + $tableValue = $this->quoteString($tableName); + $sql = <<getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + $info = []; + $generatedFields = $this->getGeneratedFields($owner ?? $this->getKingbaseSchema(), $tableName); + + foreach ($result as $val) { + $val = array_change_key_case($val); + $field = strtolower($val['field']); + + $info[$field] = [ + 'name' => $field, + 'type' => $val['type'], + 'notnull' => 'N' === strtoupper((string) $val['nullable']), + 'default' => $val['default'], + 'primary' => (bool) $val['primary'], + 'autoinc' => array_key_exists($field, $generatedFields), + 'sequence' => $generatedFields[$field] ?? null, + 'comment' => $val['comment'], + ]; + } + + return $this->fieldCase($info); + } + + /** + * 读取实际由数据库自动生成值的列,区分 Identity、默认序列和普通主键。 + * + * 业务显式写入 seq.NEXTVAL 或设置 sequence() 不改变表定义,因此不在此标记 + * autoinc;显式序列的 CURRVAL 回读仍由 getLastInsID() 负责。 + * + * @param string $owner Schema 名称 + * @param string $tableName Oracle 表名 + * @return array 以小写字段名为键、序列名为值的自动生成列集合 + */ + protected function getGeneratedFields(string $owner, string $tableName): array + { + $ownerValue = $this->quoteString($owner); + $tableValue = $this->quoteString($tableName); + $sql = 'SELECT column_name, is_identity, column_default FROM information_schema.columns' + . ' WHERE lower(table_schema) = lower(' . $ownerValue . ')' + . ' AND lower(table_name) = lower(' . $tableValue . ')'; + $rows = $this->getPDOStatement($sql)->fetchAll(PDO::FETCH_ASSOC); + $fields = []; + foreach ($rows as $row) { + $row = array_change_key_case($row); + $default = (string) ($row['column_default'] ?? ''); + $sequence = $this->extractSequenceFromDefault($default); + if ('YES' === strtoupper((string) $row['is_identity']) || null !== $sequence) { + $fields[strtolower($row['column_name'])] = $sequence; + } + } + return $fields; + } + + /** + * 获取当前用户或指定 Owner 下的业务表列表。 + * + * 查询时过滤 KingbaseES Oracle 兼容模式中的内部辅助表,避免其被 ORM 当作 + * 应用数据表使用。 + * + * @param string $dbName Owner 名,为空时查询当前用户表 + * + * @return array 表名列表 + */ + public function getTables(string $dbName = ''): array + { + if ('' === $dbName) { + $sql = <<quoteString($this->normalizeOracleName($dbName)); + $sql = <<getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + + return array_map('current', $result); + } + + /** + * 通过 Oracle 兼容序列获取最近一次插入主键。 + * + * 序列名为空时 Oracle 模式无法推断主键,返回框架约定的空字符串;否则在当前物理连接上 + * 查询序列 CURRVAL,确保取得本会话刚使用的值。 + * + * @param BaseQuery $query 当前查询对象,保留 ThinkORM 接口一致性 + * @param string|null $sequence 序列名,可包含 Owner + * + * @return mixed 序列当前值;未提供序列名时返回空字符串 + */ + public function getLastInsID(BaseQuery $query, ?string $sequence = null) + { + $sequence = $this->getKingbaseInsertSequence(); + if (null === $sequence || '' === $sequence) { + return ''; + } + + return $this->resolveKingbaseGeneratedKey(function () use ($sequence) { + $sequence = $this->parseSequenceName($sequence); + $pdo = $this->linkID->query("SELECT {$sequence}.CURRVAL AS id FROM dual"); + + return $pdo->fetchColumn(); + }); + } + + /** + * 从 Oracle NEXTVAL 或 PostgreSQL 风格 nextval() 默认值中提取真实序列名。 + */ + protected function extractSequenceFromDefault(?string $default): ?string + { + if (null === $default || '' === trim($default)) { + return null; + } + + if (preg_match( + '/^\s*((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_$#]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_$#]*))?)\s*\.\s*NEXTVAL\b/i', + $default, + $match + )) { + return str_replace('"', '', $match[1]); + } + + if (preg_match('/^\s*nextval\s*\(\s*\'((?:\'\'|[^\'])+)\'\s*(?:::[^)]+)?\s*\)/i', $default, $match)) { + $sequence = str_replace("''", "'", $match[1]); + + return str_replace('"', '', $sequence); + } + + if (preg_match('/^\s*nextval\s*\(\s*"([^"]+)"\s*\)/i', $default, $match)) { + $sequence = $match[1]; + + return str_replace('"', '', $sequence); + } + + return null; + } + + /** + * 拆分并规范化 Oracle 风格的 Owner 限定表名。 + * + * @param string $tableName 表名,可使用 owner.table 形式 + * + * @return array{0:string|null,1:string} Owner 与表名;无 Owner 时首项为 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(true); + + return $this->linkID->quote($value); + } + + /** + * 返回本连接器要求的 KingbaseES 兼容模式。 + * + * @return string 固定返回 oracle + */ + protected function getExpectedKingbaseMode(): string + { + return 'oracle'; + } + + /** + * 解析并引用 Oracle 风格序列名。 + * + * 对 Owner 和序列名称分别规范化并使用双引号引用,以支持限定名称及需要保留 + * 大小写的序列对象。 + * + * @param string $sequence 序列名,可使用 owner.sequence 形式 + * + * @return string 可安全拼入 SQL 的序列标识符 + */ + protected function parseSequenceName(string $sequence): string + { + $parts = explode('.', $sequence); + + foreach ($parts as &$part) { + $part = $this->normalizeOracleName($part); + $part = '"' . str_replace('"', '""', $part) . '"'; + } + + return implode('.', $parts); + } +} diff --git a/src/db/connector/KingbaseSqlsrv.php b/src/db/connector/KingbaseSqlsrv.php new file mode 100644 index 00000000..085f5bdf --- /dev/null +++ b/src/db/connector/KingbaseSqlsrv.php @@ -0,0 +1,448 @@ +getKingbaseFieldType($type); + } + + /** + * 根据 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; + } + + /** + * 读取 SQL Server 兼容模式下的数据表字段元数据。 + * + * 分别读取基础列、主键列和 IDENTITY 列后合并为 ThinkORM 统一字段结构, + * 避免不同系统视图之间的兼容差异影响字段识别。 + * + * @param string $tableName 表名,可包含 Schema 和别名 + * + * @return array 以小写字段名为键的 ThinkORM 字段元数据 + */ + public function getFields(string $tableName): array + { + [$tableName] = explode(' ', $tableName); + [$schema, $tableName] = $this->parseSqlsrvTable($tableName); + + $result = $this->getColumnRows($schema, $tableName); + $comments = $this->getColumnComments($schema, $tableName); + $info = []; + + foreach ($result as $val) { + $val = array_change_key_case($val); + $field = strtolower($val['field']); + + $info[$field] = [ + 'name' => $field, + 'type' => $val['type'], + 'notnull' => 'NO' === strtoupper((string) $val['is_nullable']), + 'default' => $val['default'], + 'primary' => false, + 'autoinc' => false, + 'sequence' => null, + 'comment' => $comments[$field] ?? null, + ]; + } + + foreach ($this->getPrimaryFields($schema, $tableName) as $field) { + $field = strtolower($field); + if (isset($info[$field])) { + $info[$field]['primary'] = true; + } + } + + foreach ($this->getIdentityFields($schema, $tableName) as $field) { + $field = strtolower($field); + if (isset($info[$field])) { + $info[$field]['autoinc'] = true; + } + } + + return $this->fieldCase($info); + } + + /** + * 获取指定 Schema 下的业务基础表列表。 + * + * 查询时过滤 KingbaseES SQL Server 兼容模式中的内部辅助表。 + * + * @param string $dbName Schema 名,为空时使用当前连接的 Schema + * + * @return array 表名列表 + */ + public function getTables(string $dbName = ''): array + { + $schema = $dbName ?: $this->getSchemaName(); + $schemaValue = $this->quoteString($schema); + $sql = <<getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + + return array_column($result, 'table_name'); + } + + /** + * 获取最近一次插入产生的 IDENTITY 主键。 + * + * PDO_KDB 的 lastInsertId() 不能作为 SQL Server 兼容模式的可靠结果,因此只在 + * 当前 INSERT 已确认使用 Identity 列时,于同一物理连接上依次查询 + * SCOPE_IDENTITY() 和 @@IDENTITY,防止返回先前 INSERT 遗留的会话值。 + * + * @param string|null $sequence 可选序列名,保留父连接器接口兼容性 + * + * @return mixed IDENTITY 值,无法取得时返回空字符串 + */ + public function getAutoID(?string $sequence = null) + { + return $this->resolveKingbaseGeneratedKey(function () { + foreach (['SELECT SCOPE_IDENTITY() AS id', 'SELECT @@IDENTITY AS id'] as $sql) { + try { + $pdo = $this->linkID->query($sql); + $result = $pdo->fetch(PDO::FETCH_ASSOC); + $id = is_array($result) ? ($result['id'] ?? current($result)) : ''; + + if ('' !== $id && false !== $id && null !== $id) { + return (string) $id; + } + } catch (\Throwable $e) { + // Try the documented fallback on the same physical connection. + } + } + + return ''; + }); + } + + /** + * 使用 SQL Server 兼容语法开启事务。 + * + * 最外层执行 BEGIN TRANSACTION;内层建立保存点,便于局部失败后回滚。 + * + * @return void + */ + public function startTrans(): void + { + $this->initConnect(true); + + if (0 == $this->transTimes) { + $this->linkID->exec('BEGIN TRANSACTION'); + } else { + $this->linkID->exec($this->parseSavepoint('trans' . ($this->transTimes + 1))); + } + + $this->transTimes++; + $this->reConnectTimes = 0; + } + + /** + * 使用 SQL Server 兼容语法提交事务。 + * + * 事务计数回到零时才执行物理 COMMIT,以保持 ThinkORM 嵌套事务行为。 + * + * @return void + */ + public function commit(): void + { + if (0 == $this->transTimes) { + return; + } + $this->initConnect(true); + if (1 == $this->transTimes) { + $this->linkID->exec('COMMIT'); + } + $this->transTimes--; + } + + /** + * 使用 SQL Server 兼容语法回滚事务。 + * + * 内层回滚到对应保存点,最外层执行物理 ROLLBACK;SQL 成功后才改变计数。 + * + * @return void + */ + public function rollback(): void + { + if (0 == $this->transTimes) { + return; + } + $this->initConnect(true); + if (1 == $this->transTimes) { + $this->linkID->exec('ROLLBACK'); + } else { + $this->linkID->exec($this->parseSavepointRollBack('trans' . $this->transTimes)); + } + $this->transTimes--; + } + + /** + * 拆分 SQL Server 风格的 Schema 限定表名。 + * + * @param string $tableName 表名,可使用 schema.table 及方括号/引号形式 + * + * @return array{0:string,1:string} Schema 与表名 + */ + protected function parseSqlsrvTable(string $tableName): array + { + $tableName = trim($tableName, '`[]"'); + + if (str_contains($tableName, '.')) { + [$schema, $tableName] = explode('.', $tableName, 2); + + return [ + trim($schema, '`[]"'), + trim($tableName, '`[]"'), + ]; + } + + return [$this->getSchemaName(), $tableName]; + } + + /** + * 获取已配置并经服务器确认的 Schema 名称。 + * + * @return string 当前 Schema 名称 + */ + protected function getSchemaName(): string + { + return $this->getKingbaseSchema(); + } + + /** + * 返回本连接器要求的 KingbaseES 兼容模式。 + * + * @return string 固定返回 sqlserver + */ + protected function getExpectedKingbaseMode(): string + { + return 'sqlserver'; + } + + /** + * 从 information_schema 获取指定表的基础列信息。 + * + * @param string $schema Schema 名称 + * @param string $tableName 表名 + * + * @return array 数据库返回的字段记录 + */ + protected function getColumnRows(string $schema, string $tableName): array + { + $schemaValue = $this->quoteString($schema); + $tableValue = $this->quoteString($tableName); + + $sql = <<getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + + return $result; + } + + /** + * 从 KingbaseES 系统目录读取 SQL Server 兼容模式的字段注释。 + * + * 某些服务端版本未暴露该系统目录时返回空集合,基础字段元数据仍可使用;支持 + * 目录的版本则返回 COMMENT ON COLUMN 写入的真实非空注释。 + * + * @return array 以小写字段名为键的注释集合 + */ + protected function getColumnComments(string $schema, string $tableName): array + { + $schemaValue = $this->quoteString($schema); + $tableValue = $this->quoteString($tableName); + $sql = << 0 + AND NOT a.attisdropped +SQL; + + try { + $rows = $this->getPDOStatement($sql)->fetchAll(PDO::FETCH_ASSOC); + } catch (\Throwable $exception) { + return []; + } + + $comments = []; + foreach ($rows as $row) { + $row = array_change_key_case($row); + $comments[strtolower((string) $row['field'])] = $row['comment'] ?? null; + } + + return $comments; + } + + /** + * 获取指定表按约束顺序排列的主键字段名。 + * + * @param string $schema Schema 名称 + * @param string $tableName 表名 + * + * @return array 主键字段名列表 + */ + protected function getPrimaryFields(string $schema, string $tableName): array + { + $schemaValue = $this->quoteString($schema); + $tableValue = $this->quoteString($tableName); + $sql = <<getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + + return array_map('current', $result); + } + + /** + * 获取指定表的 IDENTITY 自增字段名。 + * + * @param string $schema Schema 名称 + * @param string $tableName 表名 + * + * @return array IDENTITY 字段名列表 + */ + protected function getIdentityFields(string $schema, string $tableName): array + { + $objectName = $schema . '.' . $tableName; + $objectValue = $this->quoteString($objectName); + $sql = <<getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + + return array_map('current', $result); + } + + /** + * 使用当前 PDO_KDB 连接转义元数据查询中的字符串字面量。 + * + * @param string $value 待转义字符串 + * + * @return string 包含引号的安全 SQL 字面量 + */ + protected function quoteString(string $value): string + { + $this->initConnect(true); + + return $this->linkID->quote($value); + } + + /** + * 禁用父 SQL Server 连接器的会话时区设置 SQL。 + * + * KingbaseES SQL Server 兼容模式未提供父实现依赖的完整时区设置语义,因此返回 + * 空 SQL,日期时间表达式由数据库当前会话处理。 + * + * @param string $timezone ThinkORM 配置的时区 + * + * @return string 固定返回空字符串 + */ + protected function getSetTimezoneSql(string $timezone): string + { + return ''; + } +} diff --git a/src/db/connector/concern/KingbaseConnection.php b/src/db/connector/concern/KingbaseConnection.php new file mode 100644 index 00000000..b0e4fb54 --- /dev/null +++ b/src/db/connector/concern/KingbaseConnection.php @@ -0,0 +1,654 @@ + + */ + protected array $kingbaseInitializedLinks = []; + + /** + * Schema discovered from the current PDO_KDB session. + */ + protected string $kingbaseResolvedSchema = ''; + + /** @var array 本连接器读取过的结构缓存键 */ + protected array $kingbaseSchemaCacheKeys = []; + + /** 当前 INSERT 是否真实具备数据库生成主键的语义。 */ + protected bool $kingbaseGeneratedKeyExpected = false; + + /** 当前 INSERT 已读取到的生成主键,供 Model 后续再次读取。 */ + protected mixed $kingbaseGeneratedKey = null; + + /** 当前 INSERT 的生成主键是否已成功读取。 */ + protected bool $kingbaseGeneratedKeyCached = false; + + /** 当前 Oracle INSERT 实际使用或由字段默认值解析出的序列。 */ + protected ?string $kingbaseInsertSequence = null; + + /** + * 建立 PDO_KDB 连接并初始化 KingbaseES 会话。 + * + * 在父连接器完成物理连接后校验驱动、数据库兼容模式和 Schema;连接失败时补充 + * 主机、端口及数据库名等诊断信息,同时对口令脱敏并保留原始 PDOException。 + * + * @param array $config 本次连接覆盖配置,为空时使用连接器默认配置 + * @param int $linkNum 连接编号,用于读写分离或多连接场景 + * @param array|bool $autoConnection 自动连接配置或是否启用自动连接 + * + * @throws \PDOException 物理连接失败 + * @throws \UnexpectedValueException 驱动、兼容模式或 Schema 与配置不一致 + * @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, $mergedConfig); + + return $pdo; + } catch (\PDOException $e) { + $message = $this->formatKingbaseConnectionFailure($mergedConfig, $e); + $code = is_numeric($e->getCode()) ? (int) $e->getCode() : 0; + + throw new \PDOException($message, $code, $e); + } + } + + /** + * 关闭全部数据库连接并清理 KingbaseES 会话派生状态。 + * + * @return $this 当前连接器实例 + */ + public function close() + { + $this->kingbaseInitializedLinks = []; + $this->kingbaseResolvedSchema = ''; + $this->kingbaseSchemaCacheKeys = []; + $this->resetKingbaseGeneratedKeyContext(); + + return parent::close(); + } + + /** + * 执行原生 SQL,并在 DDL 成功后使本连接器已读取的结构缓存失效。 + * + * 原生 INSERT 无法从 Query 元数据确认主键生成语义,因此先清除上一次 ORM + * INSERT 的生成键上下文,避免随后 getLastInsID() 返回历史值。 + * + * @param string $sql SQL 语句 + * @param array $bind 参数绑定 + * + * @return int 影响行数 + */ + public function execute(string $sql, array $bind = []): int + { + if (1 === preg_match('/^\s*(?:INSERT|REPLACE|MERGE)\b/i', $sql)) { + $this->resetKingbaseGeneratedKeyContext(); + } + + $result = parent::execute($sql, $bind); + + if ($this->isKingbaseDdl($sql)) { + $this->invalidateKingbaseSchemaCache($sql); + } + + return $result; + } + + /** + * 记录结构缓存键,使 DDL 后可以同时清理内存缓存和 PSR-16 字段缓存。 + * + * @param string $tableName 表名 + * @param bool $force 是否强制从数据库读取 + * + * @return array 表结构信息 + */ + public function getSchemaInfo(string $tableName, bool $force = false): array + { + $this->kingbaseSchemaCacheKeys[$this->kingbaseSchemaCacheKey($tableName)] = true; + + return parent::getSchemaInfo($tableName, $force); + } + + /** + * 执行单行 INSERT,并建立仅属于本次 INSERT 的生成主键上下文。 + * + * 父连接器会在 INSERT 成功后读取生成主键,Model 随后还可能再次调用 + * getLastInsID()。这里缓存本次真实生成的值,同时在显式普通主键场景返回空值, + * 避免 LAST_INSERT_ID()/CURRVAL/@@IDENTITY 的历史会话值被误认为本次主键。 + * + * @param BaseQuery $query 查询对象 + * @param bool $getLastInsID 是否返回生成主键 + * + * @return mixed 插入结果或本次生成主键 + */ + public function insert(BaseQuery $query, bool $getLastInsID = false) + { + $this->prepareKingbaseGeneratedKeyContext($query); + + try { + $result = parent::insert($query, $getLastInsID); + } catch (\Throwable $exception) { + $this->resetKingbaseGeneratedKeyContext(); + throw $exception; + } + + if ($getLastInsID) { + return $this->kingbaseGeneratedKeyCached ? $this->kingbaseGeneratedKey : ''; + } + + return $result; + } + + /** + * 批量插入不会产生可安全归属到单行的生成主键,执行前清理历史上下文。 + * + * @param BaseQuery $query 查询对象 + * @param array $dataSet 数据集 + */ + public function insertAll(BaseQuery $query, array $dataSet = []): int + { + $this->resetKingbaseGeneratedKeyContext(); + + return parent::insertAll($query, $dataSet); + } + + /** + * 固定字段批量插入不会返回单行生成主键,执行前清理历史上下文。 + * + * @param BaseQuery $query 查询对象 + * @param array $keys 字段集合 + * @param array $values 数据集合 + */ + public function insertAllByKeys(BaseQuery $query, array $keys, array $values): int + { + $this->resetKingbaseGeneratedKeyContext(); + + return parent::insertAllByKeys($query, $keys, $values); + } + + /** + * 获取当前连接器要求的 KingbaseES 兼容模式。 + * + * @return string 兼容模式标识:mysql、oracle 或 sqlserver + */ + public function getKingbaseMode(): string + { + return $this->getExpectedKingbaseMode(); + } + + /** + * 获取配置或由当前会话解析得到的 Schema。 + * + * 尚未建立连接时会主动初始化连接;仍无法确定 Schema 时抛出异常,避免后续 + * 元数据查询误落入其他模式。 + * + * @throws \UnexpectedValueException 无法解析当前 Schema + * + * @return string 当前有效的 Schema 名称 + */ + public function getKingbaseSchema(): string + { + if ('' === $this->kingbaseResolvedSchema) { + $this->initConnect(true); + } + + if ('' === $this->kingbaseResolvedSchema) { + throw new \UnexpectedValueException('Unable to resolve the current KES schema'); + } + + return $this->kingbaseResolvedSchema; + } + + /** + * 返回具体连接器实现的 KingbaseES 兼容模式。 + * + * @return string 兼容模式标识 + */ + abstract protected function getExpectedKingbaseMode(): string; + + /** + * 将 KingbaseES 特殊字段映射为正确的 PDO 参数绑定类型。 + * + * 数组、范围、INTERVAL 和几何类型使用文本形式传输,避免其类型名中的 int + * 被通用规则误判为整数;blob、binary、bytea、raw 和 image 类型标记为 + * kingbase_lob,以便包含 NUL 字节的数据通过 PDO::PARAM_LOB 安全写入。 + * 其他类型沿用父连接器映射。 + * + * @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'; + } + + // KES reports MySQL unsigned integers as uint2/uint4/uint8. Always + // bind them as strings so uint8 values above PHP_INT_MAX are not + // truncated before PDO_KDB sends them to the server. + 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 (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), + }; + } + + /** + * 只在当前 INSERT 已确认会生成数据库主键时执行回读,并缓存有效结果。 + * + * @param callable $resolver 实际生成主键查询 + * @param mixed $empty 不应读取或无法取得时的返回值 + * + * @return mixed 当前 INSERT 的生成主键或空值 + */ + protected function resolveKingbaseGeneratedKey(callable $resolver, mixed $empty = ''): mixed + { + if (!$this->kingbaseGeneratedKeyExpected) { + return $empty; + } + + if ($this->kingbaseGeneratedKeyCached) { + return $this->kingbaseGeneratedKey; + } + + $value = $resolver(); + if (null === $value || false === $value || '' === $value) { + return $empty; + } + + $this->kingbaseGeneratedKey = $value; + $this->kingbaseGeneratedKeyCached = true; + + return $value; + } + + /** + * 返回当前 Oracle INSERT 经验证实际使用的序列。 + */ + protected function getKingbaseInsertSequence(): ?string + { + return $this->kingbaseInsertSequence; + } + + /** + * 初始化并校验一个物理 PDO_KDB 连接。 + * + * 每个 PDO 对象仅初始化一次;依次确认驱动名、服务器兼容模式,设置 search_path, + * 并验证同一连接器创建的不同物理连接使用相同 Schema。 + * + * @param PDO $pdo 待初始化的物理连接 + * @param array $config 合并后的数据库连接配置 + * + * @throws \UnexpectedValueException 驱动、兼容模式或实际 Schema 不符合预期 + * @throws \InvalidArgumentException Schema 标识符不合法 + * + * @return void + */ + protected function initializeKingbaseSession(PDO $pdo, array $config): 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 + ); + } + + $configuredSchema = trim((string) ($config['schema'] ?? '')); + if ('' !== $configuredSchema) { + $configuredSchema = $this->validateKingbaseIdentifier($configuredSchema, 'schema'); + $quotedSchema = '"' . str_replace('"', '""', $configuredSchema) . '"'; + $searchPath = 'public' === strtolower($configuredSchema) + ? $quotedSchema + : $quotedSchema . ', public'; + + $pdo->exec('SET search_path TO ' . $searchPath); + } + + $currentSchema = $this->validateKingbaseIdentifier( + (string) $pdo->query('SELECT current_schema()')->fetchColumn(), + 'current schema' + ); + + if ('' !== $configuredSchema && 0 !== strcasecmp($configuredSchema, $currentSchema)) { + throw new \UnexpectedValueException( + 'KES schema initialization failed: expected ' . $configuredSchema . ', got ' . $currentSchema + ); + } + + if ('' !== $this->kingbaseResolvedSchema + && 0 !== strcasecmp($this->kingbaseResolvedSchema, $currentSchema)) { + throw new \UnexpectedValueException( + 'KES schema mismatch between connections: expected ' + . $this->kingbaseResolvedSchema . ', got ' . $currentSchema + ); + } + + $this->kingbaseResolvedSchema = $currentSchema; + $this->kingbaseInitializedLinks[$hash] = true; + } + + /** + * 为当前 INSERT 解析自增、Identity 或 Oracle Sequence 生成语义。 + */ + protected function prepareKingbaseGeneratedKeyContext(BaseQuery $query): void + { + $this->resetKingbaseGeneratedKeyContext(); + + $options = $query->getOptions(); + $data = is_array($options['data'] ?? null) ? $options['data'] : []; + $sequence = trim((string) ($options['sequence'] ?? '')); + $mode = $this->getExpectedKingbaseMode(); + + if ('oracle' === $mode && '' !== $sequence && $this->dataUsesKingbaseSequence($data, $sequence)) { + $this->kingbaseGeneratedKeyExpected = true; + $this->kingbaseInsertSequence = $sequence; + return; + } + + $autoInc = $query->getAutoInc(); + if (!is_string($autoInc) || '' === $autoInc) { + return; + } + + [$fieldExists, $fieldValue] = $this->findKingbaseDataField($data, $autoInc); + if ($fieldExists && !$this->isKingbaseGeneratedFieldValue($fieldValue)) { + return; + } + + if ('oracle' !== $mode) { + $this->kingbaseGeneratedKeyExpected = true; + return; + } + + $fields = $this->getFields((string) $query->getTable()); + $metadataSequence = trim((string) ($fields[$autoInc]['sequence'] ?? '')); + if ('' === $metadataSequence) { + return; + } + + if ('' !== $sequence + && $this->normalizeKingbaseSequence($sequence) !== $this->normalizeKingbaseSequence($metadataSequence)) { + return; + } + + $this->kingbaseGeneratedKeyExpected = true; + $this->kingbaseInsertSequence = $metadataSequence; + } + + /** + * 清除生成主键上下文;任何新 INSERT 都必须重新证明生成语义。 + */ + protected function resetKingbaseGeneratedKeyContext(): void + { + $this->kingbaseGeneratedKeyExpected = false; + $this->kingbaseGeneratedKey = null; + $this->kingbaseGeneratedKeyCached = false; + $this->kingbaseInsertSequence = null; + } + + /** + * 在大小写不敏感的字段数组中读取指定字段。 + * + * @return array{0:bool,1:mixed} + */ + private function findKingbaseDataField(array $data, string $field): array + { + foreach ($data as $key => $value) { + if (0 === strcasecmp((string) $key, $field)) { + return [true, $value]; + } + } + + return [false, null]; + } + + /** + * NULL 或 DEFAULT 表达式仍可触发自增/Identity 默认值。 + */ + private function isKingbaseGeneratedFieldValue(mixed $value): bool + { + if (null === $value) { + return true; + } + + return $value instanceof Raw && 'DEFAULT' === strtoupper(trim($value->getValue())); + } + + /** + * 判断 INSERT 数据中是否确实使用指定 Oracle 序列的 NEXTVAL。 + */ + private function dataUsesKingbaseSequence(array $data, string $sequence): bool + { + $expected = $this->normalizeKingbaseSequence($sequence) . '.NEXTVAL'; + + foreach ($data as $value) { + if (!$value instanceof Raw) { + continue; + } + $expression = strtoupper((string) preg_replace('/[\s`"\[\]]+/', '', $value->getValue())); + if (str_contains($expression, $expected)) { + return true; + } + } + + return false; + } + + /** + * 规范化序列限定名,供显式配置与元数据结果比较。 + */ + private function normalizeKingbaseSequence(string $sequence): string + { + return strtoupper((string) preg_replace('/[\s`"\[\]]+/', '', trim($sequence))); + } + + /** + * 判断 SQL 是否可能改变表结构或字段注释。 + */ + private function isKingbaseDdl(string $sql): bool + { + return 1 === preg_match('/^\s*(?:CREATE|ALTER|DROP|TRUNCATE|COMMENT|RENAME)\b/i', $sql); + } + + /** + * 清理本连接器内存字段信息及已知的 PSR-16 结构缓存项。 + */ + private function invalidateKingbaseSchemaCache(string $sql): void + { + $keys = $this->kingbaseSchemaCacheKeys; + $table = $this->extractKingbaseDdlTable($sql); + if (null !== $table) { + $keys[$this->kingbaseSchemaCacheKey($table)] = true; + } + + $this->info = []; + if (!empty($this->cache)) { + foreach (array_keys($keys) as $key) { + $this->cache->delete($key); + } + } + $this->kingbaseSchemaCacheKeys = []; + } + + /** + * 按父连接器规则计算字段缓存键。 + */ + private function kingbaseSchemaCacheKey(string $tableName): string + { + [$tableName] = explode(' ', trim($tableName), 2); + $tableName = str_replace(['`', '"', '[', ']'], '', $tableName); + $schema = str_contains($tableName, '.') + ? $tableName + : $this->getConfig('database') . '.' . $tableName; + + return $this->getSchemaCacheKey($schema); + } + + /** + * 从常见 DDL 中提取受影响的表名,用于删除跨连接字段缓存。 + */ + private function extractKingbaseDdlTable(string $sql): ?string + { + $patterns = [ + '/^\s*(?:CREATE|ALTER|DROP|TRUNCATE)\s+(?:TABLE|VIEW)\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?([^\s(;]+)/i', + '/^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+[^\s]+\s+ON\s+([^\s(]+)/i', + '/^\s*COMMENT\s+ON\s+COLUMN\s+([^\s]+)\s+IS\b/i', + ]; + + foreach ($patterns as $pattern) { + if (1 !== preg_match($pattern, $sql, $match)) { + continue; + } + $name = str_replace(['`', '"', '[', ']'], '', $match[1]); + if (str_starts_with(strtoupper(ltrim($sql)), 'COMMENT ON COLUMN')) { + $parts = explode('.', $name); + if (count($parts) > 1) { + array_pop($parts); + $name = implode('.', $parts); + } + } + + return '' === $name ? null : $name; + } + + return null; + } + + /** + * 校验不带限定符的 KingbaseES 数据库对象标识符。 + * + * 只允许字母或下划线开头,后续可包含字母、数字、下划线、美元符号和井号, + * 防止配置值直接拼入 SET search_path 等 SQL 时产生歧义或注入风险。 + * + * @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/model/type/KingbaseDateTime.php b/src/model/type/KingbaseDateTime.php new file mode 100644 index 00000000..05357d78 --- /dev/null +++ b/src/model/type/KingbaseDateTime.php @@ -0,0 +1,39 @@ + Date: Sun, 25 Oct 2026 23:24:41 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E9=80=82=E9=85=8D=E8=BE=B9=E7=95=8C?= =?UTF-8?q?=E5=AF=B9=E9=BD=90=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/builder/KingbaseMysql.php | 16 -- src/db/builder/KingbaseOracle.php | 205 +++++++----------- src/db/builder/KingbaseSqlsrv.php | 100 +-------- src/db/connector/KingbaseSqlsrv.php | 10 +- .../connector/concern/KingbaseConnection.php | 104 +-------- 5 files changed, 89 insertions(+), 346 deletions(-) diff --git a/src/db/builder/KingbaseMysql.php b/src/db/builder/KingbaseMysql.php index 18fbf684..63d7592e 100644 --- a/src/db/builder/KingbaseMysql.php +++ b/src/db/builder/KingbaseMysql.php @@ -66,22 +66,6 @@ protected function parseTextValue(Query $query, $value): string return (string) $value; } - /** - * 构造 MySQL 兼容模式的 REGEXP 条件。 - * - * @param Query $query 当前查询对象 - * @param string $key 已解析的字段表达式 - * @param string $exp 正则运算符 - * @param mixed $value 匹配值或绑定占位符 - * @param string $field 原始字段名,保留父方法接口一致性 - * - * @return string REGEXP 条件 SQL - */ - protected function parseRegexp(Query $query, string $key, string $exp, $value, string $field): string - { - return $key . ' ' . $exp . ' ' . $this->parseTextValue($query, $value); - } - /** * 构造 MySQL 兼容模式的 FIND_IN_SET 条件。 * diff --git a/src/db/builder/KingbaseOracle.php b/src/db/builder/KingbaseOracle.php index 8688929e..1667ceaa 100644 --- a/src/db/builder/KingbaseOracle.php +++ b/src/db/builder/KingbaseOracle.php @@ -12,8 +12,7 @@ namespace think\db\builder; use think\db\BaseQuery as Query; -use think\db\exception\DbException as Exception; -use think\db\Raw; +use think\db\Connection; /** * KingbaseES Oracle 兼容模式 SQL 构造器。 @@ -21,87 +20,96 @@ class KingbaseOracle extends Oracle { /** - * A scalar subquery must not expose Oracle's synthetic ROWNUM column. - */ - protected string $plainSelectSql = 'SELECT%DISTINCT%%EXTRA% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%UNION%%ORDER%%LIMIT% %LOCK%%COMMENT%'; - - /** 当前是否正在构造使用 KingbaseES 原生分页的 SELECT。 */ - protected bool $kingbaseSelect = false; - - /** - * 使用 KingbaseES 原生分页构造 SELECT,保留行锁及单列子查询语义。 + * 使用 VALUES 语法构造多行 INSERT。 * - * 不添加 NUMROW 辅助列,避免关联聚合或 INSERT SELECT 列数变化;所有 SELECT - * 均保留 LOCK、UNION 和 ORDER。finally 恢复状态,支持重入和构造异常后的复用。 - * - * @param Query $query 当前查询对象 - * @param bool $one 是否仅查询一条记录 - * - * @return string 完整 SELECT SQL + * PDO_KDB 无法在父 Oracle Builder 的 UNION ALL SELECT 批量写法中稳定推断 + * BLOB 等目标列的占位符类型,因此仅改写 SQL 结构;字段和值仍按原框架的 + * 数组迭代顺序处理。 */ - public function select(Query $query, bool $one = false): string + public function insertAll(Query $query, array $dataSet): string { - $selectSql = $this->selectSql; - $selectMode = $this->kingbaseSelect; - $this->selectSql = $this->plainSelectSql; - $this->kingbaseSelect = true; - try { - return parent::select($query, $one); - } finally { - $this->selectSql = $selectSql; - $this->kingbaseSelect = $selectMode; + $options = $query->getOptions(); + $bind = $query->getFieldsBindType(); + + if (empty($options['field']) || '*' == $options['field']) { + $allowFields = array_keys($bind); + } else { + $allowFields = $options['field']; } - } - /** - * SELECT 使用 LIMIT/OFFSET,写语句继续沿用父方言的处理。 - * - * @param Query $query 当前查询对象 - * @param string $limit 数量或“偏移量,数量” - * @return string 分页子句 - * @throws \InvalidArgumentException 分页参数不是非负整数 - */ - protected function parseLimit(Query $query, string $limit): string - { - if (!$this->kingbaseSelect) { - return parent::parseLimit($query, $limit); + $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 ('' === $limit) { + + if (null === $insertFields) { return ''; } - if (!preg_match('/^\d+(?:,\d+)?$/D', $limit)) { - throw new \InvalidArgumentException('Invalid KES pagination: ' . $limit); + + $fields = []; + foreach ($insertFields as $field) { + $fields[] = $this->parseKey($query, $field); } - $parts = explode(',', $limit); - return count($parts) === 2 - ? ' LIMIT ' . $parts[1] . ' OFFSET ' . $parts[0] - : ' LIMIT ' . $parts[0]; + + 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 + ); } - /** - * 构造 Oracle 兼容模式 INSERT,并将 REPLACE 请求降级为普通 INSERT。 - * - * Oracle 兼容模式不支持 REPLACE。ThinkORM 写入多对多中间表时可能内部启用 - * replace 选项,因此生成 SQL 期间临时关闭该选项,随后恢复;重复数据仍由 - * 中间表的主键或唯一约束阻止。 - * - * @param Query $query 当前查询对象 - * - * @return string 完整 INSERT SQL - */ - public function insert(Query $query): string + /** 使用 VALUES 语法构造固定字段批量 INSERT。 */ + public function insertAllByKeys(Query $query, array $keys, array $datas): string { - $replace = (bool) $query->getOption('replace'); - if (!$replace) { - return parent::insert($query); + $options = $query->getOptions(); + $bind = $query->getFieldsBindType(); + $fields = []; + $values = []; + + foreach ($keys as $field) { + $fields[] = $this->parseKey($query, $field); } - $query->setOption('replace', false); - try { - return parent::insert($query); - } finally { - $query->setOption('replace', true); + 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 + ); } /** @@ -118,65 +126,4 @@ protected function parseRand(Query $query): string return 'random()'; } - /** - * 解析字段和表标识符,并适配 Oracle 未引用对象名的大写规则。 - * - * 支持整数、Raw 表达式、JSON 路径、表别名及严格模式校验;普通字段和表名 - * 转换为大写后使用双引号引用。 - * - * @param Query $query 当前查询对象 - * @param string|int|Raw $key 字段名、数字或 Raw 表达式 - * @param bool $strict 是否启用标识符严格校验 - * - * @throws Exception 严格模式下标识符包含不支持的内容 - * - * @return string 可安全拼入 SQL 的标识符或表达式 - */ - public function parseKey(Query $query, string|int|Raw $key, bool $strict = false): string - { - if (is_int($key)) { - return (string) $key; - } - - if ($key instanceof Raw) { - return $this->parseRaw($query, $key); - } - - $key = trim($key); - - if (str_contains($key, '->') && !str_contains($key, '(')) { - [$field, $name] = explode('->', $key, 2); - - return $this->parseKey($query, $field, true) . '."' . strtoupper($name) . '"'; - } - - if (str_contains($key, '.') && !preg_match('/[,\'\"\(\)\[\s]/', $key)) { - [$table, $key] = explode('.', $key, 2); - - $alias = $query->getOption('alias'); - - if ('__TABLE__' == $table) { - $table = $query->getOption('table'); - $table = is_array($table) ? array_shift($table) : $table; - } - - if (isset($alias[$table])) { - $table = $alias[$table]; - } - } - - if ($strict && !preg_match('/^[\w\.\*]+$/', $key)) { - throw new Exception('not support data:' . $key); - } - - if ('*' != $key && !preg_match('/[,\'\"\*\(\)\[.\s]/', $key)) { - $key = '"' . strtoupper($key) . '"'; - } - - if (isset($table)) { - $key = '"' . strtoupper($table) . '".' . $key; - } - - return $key; - } } diff --git a/src/db/builder/KingbaseSqlsrv.php b/src/db/builder/KingbaseSqlsrv.php index c51b9ef5..48adedc4 100644 --- a/src/db/builder/KingbaseSqlsrv.php +++ b/src/db/builder/KingbaseSqlsrv.php @@ -19,91 +19,6 @@ */ class KingbaseSqlsrv extends Sqlsrv { - /** - * A scalar subquery must not expose SQL Server pagination's ROW_NUMBER. - */ - protected string $plainSelectSql = 'SELECT%DISTINCT%%EXTRA% %FIELD% FROM %TABLE%%FORCE%%JOIN%%WHERE%%GROUP%%HAVING%%UNION%%ORDER%%LIMIT% %LOCK%%COMMENT%'; - - /** 当前是否正在构造使用 KingbaseES 原生分页的 SELECT。 */ - protected bool $kingbaseSelect = false; - - /** - * 使用 KingbaseES 原生分页构造 SELECT,保留行锁及单列子查询语义。 - * - * 不添加 ROW_NUMBER 辅助列,避免关联聚合或 INSERT SELECT 列数变化;所有 SELECT - * 均保留 LOCK、UNION 和 ORDER。finally 恢复状态,支持重入和构造异常后的复用。 - * - * @param Query $query 当前查询对象 - * @param bool $one 是否仅查询一条记录 - * - * @return string 完整 SELECT SQL - */ - public function select(Query $query, bool $one = false): string - { - $selectSql = $this->selectSql; - $selectMode = $this->kingbaseSelect; - $this->selectSql = $this->plainSelectSql; - $this->kingbaseSelect = true; - try { - return parent::select($query, $one); - } finally { - $this->selectSql = $selectSql; - $this->kingbaseSelect = $selectMode; - } - } - - /** - * SELECT 使用 LIMIT/OFFSET,写语句继续沿用父方言的处理。 - * - * @param Query $query 当前查询对象 - * @param string $limit 数量或“偏移量,数量” - * @return string 分页子句 - * @throws \InvalidArgumentException 分页参数不是非负整数 - */ - protected function parseLimit(Query $query, string $limit): string - { - if (!$this->kingbaseSelect) { - return parent::parseLimit($query, $limit); - } - if ('' === $limit) { - return ''; - } - if (!preg_match('/^\d+(?:,\d+)?$/D', $limit)) { - throw new \InvalidArgumentException('Invalid KES pagination: ' . $limit); - } - $parts = explode(',', $limit); - return count($parts) === 2 - ? ' LIMIT ' . $parts[1] . ' OFFSET ' . $parts[0] - : ' LIMIT ' . $parts[0]; - } - - /** - * 原生分页不需要默认随机排序,显式排序仍使用父方言。 - * - * @param Query $query 当前查询对象 - * @param array $order 排序配置 - * @return string 排序子句 - */ - protected function parseOrder(Query $query, array $order): string - { - return $this->kingbaseSelect && empty($order) ? '' : parent::parseOrder($query, $order); - } - - /** - * 构造 INSERT SELECT,避免父实现永久修改共享查询模板。 - * - * @param Query $query 源查询对象 - * @param array $fields 目标字段列表 - * @param string $table 目标表名 - * @return string INSERT SELECT SQL,支持源查询排序与分页 - */ - public function selectInsert(Query $query, array $fields, string $table): string - { - $fields = array_map(fn ($field) => $this->parseKey($query, $field, true), $fields); - return 'INSERT INTO ' . $this->parseTable($query, $table) - . ' (' . implode(',', $fields) . ') ' . $this->select($query); - } - /** * 使用 VALUES 语法构造多行 INSERT。 * @@ -113,8 +28,10 @@ public function selectInsert(Query $query, array $fields, string $table): string * @param Query $query 当前查询对象 * @param array $dataSet 多行待插入数据 * + * 仅改写父 SQL Server Builder 的 SQL 结构;各行字段和值仍按照原框架的 + * 数组迭代顺序处理,不在适配层重新排序或增加字段集合校验。 + * * @return string 完整批量 INSERT SQL - * @throws \InvalidArgumentException 各行字段集合不一致或为空 */ public function insertAll(Query $query, array $dataSet): string { @@ -136,15 +53,7 @@ public function insertAll(Query $query, array $dataSet): string if (null === $insertFields) { $insertFields = array_keys($data); } - if (!$insertFields || count($data) !== count($insertFields) - || array_diff($insertFields, array_keys($data))) { - throw new \InvalidArgumentException('KES batch insert requires the same non-empty fields in every row'); - } - $row = []; - foreach ($insertFields as $field) { - $row[] = $data[$field]; - } - $values[] = '( ' . implode(',', $row) . ' )'; + $values[] = '( ' . implode(',', array_values($data)) . ' )'; } if (null === $insertFields) { @@ -214,4 +123,5 @@ public function insertAllByKeys(Query $query, array $keys, array $datas): string $this->insertAllSql ); } + } diff --git a/src/db/connector/KingbaseSqlsrv.php b/src/db/connector/KingbaseSqlsrv.php index 085f5bdf..4b81167e 100644 --- a/src/db/connector/KingbaseSqlsrv.php +++ b/src/db/connector/KingbaseSqlsrv.php @@ -181,7 +181,8 @@ public function getAutoID(?string $sequence = null) /** * 使用 SQL Server 兼容语法开启事务。 * - * 最外层执行 BEGIN TRANSACTION;内层建立保存点,便于局部失败后回滚。 + * 最外层执行 BEGIN TRANSACTION;内层仅增加事务计数,保持原 Sqlsrv + * Connector 不使用保存点的逻辑嵌套语义。 * * @return void */ @@ -191,8 +192,6 @@ public function startTrans(): void if (0 == $this->transTimes) { $this->linkID->exec('BEGIN TRANSACTION'); - } else { - $this->linkID->exec($this->parseSavepoint('trans' . ($this->transTimes + 1))); } $this->transTimes++; @@ -221,7 +220,8 @@ public function commit(): void /** * 使用 SQL Server 兼容语法回滚事务。 * - * 内层回滚到对应保存点,最外层执行物理 ROLLBACK;SQL 成功后才改变计数。 + * 最外层执行物理 ROLLBACK;内层仅减少事务计数,不执行局部回滚, + * 保持原 Sqlsrv Connector 的事务行为。 * * @return void */ @@ -233,8 +233,6 @@ public function rollback(): void $this->initConnect(true); if (1 == $this->transTimes) { $this->linkID->exec('ROLLBACK'); - } else { - $this->linkID->exec($this->parseSavepointRollBack('trans' . $this->transTimes)); } $this->transTimes--; } diff --git a/src/db/connector/concern/KingbaseConnection.php b/src/db/connector/concern/KingbaseConnection.php index b0e4fb54..f163a376 100644 --- a/src/db/connector/concern/KingbaseConnection.php +++ b/src/db/connector/concern/KingbaseConnection.php @@ -32,9 +32,6 @@ trait KingbaseConnection */ protected string $kingbaseResolvedSchema = ''; - /** @var array 本连接器读取过的结构缓存键 */ - protected array $kingbaseSchemaCacheKeys = []; - /** 当前 INSERT 是否真实具备数据库生成主键的语义。 */ protected bool $kingbaseGeneratedKeyExpected = false; @@ -89,17 +86,17 @@ public function close() { $this->kingbaseInitializedLinks = []; $this->kingbaseResolvedSchema = ''; - $this->kingbaseSchemaCacheKeys = []; $this->resetKingbaseGeneratedKeyContext(); return parent::close(); } /** - * 执行原生 SQL,并在 DDL 成功后使本连接器已读取的结构缓存失效。 + * 执行原生 SQL,并在原生写入前清理 ORM 生成主键上下文。 * * 原生 INSERT 无法从 Query 元数据确认主键生成语义,因此先清除上一次 ORM - * INSERT 的生成键上下文,避免随后 getLastInsID() 返回历史值。 + * INSERT 的生成键上下文,避免随后 getLastInsID() 返回历史值。DDL 后的字段 + * 缓存行为继续沿用原 PDOConnection,不在适配层增加自动失效处理。 * * @param string $sql SQL 语句 * @param array $bind 参数绑定 @@ -112,28 +109,7 @@ public function execute(string $sql, array $bind = []): int $this->resetKingbaseGeneratedKeyContext(); } - $result = parent::execute($sql, $bind); - - if ($this->isKingbaseDdl($sql)) { - $this->invalidateKingbaseSchemaCache($sql); - } - - return $result; - } - - /** - * 记录结构缓存键,使 DDL 后可以同时清理内存缓存和 PSR-16 字段缓存。 - * - * @param string $tableName 表名 - * @param bool $force 是否强制从数据库读取 - * - * @return array 表结构信息 - */ - public function getSchemaInfo(string $tableName, bool $force = false): array - { - $this->kingbaseSchemaCacheKeys[$this->kingbaseSchemaCacheKey($tableName)] = true; - - return parent::getSchemaInfo($tableName, $force); + return parent::execute($sql, $bind); } /** @@ -514,78 +490,6 @@ private function normalizeKingbaseSequence(string $sequence): string return strtoupper((string) preg_replace('/[\s`"\[\]]+/', '', trim($sequence))); } - /** - * 判断 SQL 是否可能改变表结构或字段注释。 - */ - private function isKingbaseDdl(string $sql): bool - { - return 1 === preg_match('/^\s*(?:CREATE|ALTER|DROP|TRUNCATE|COMMENT|RENAME)\b/i', $sql); - } - - /** - * 清理本连接器内存字段信息及已知的 PSR-16 结构缓存项。 - */ - private function invalidateKingbaseSchemaCache(string $sql): void - { - $keys = $this->kingbaseSchemaCacheKeys; - $table = $this->extractKingbaseDdlTable($sql); - if (null !== $table) { - $keys[$this->kingbaseSchemaCacheKey($table)] = true; - } - - $this->info = []; - if (!empty($this->cache)) { - foreach (array_keys($keys) as $key) { - $this->cache->delete($key); - } - } - $this->kingbaseSchemaCacheKeys = []; - } - - /** - * 按父连接器规则计算字段缓存键。 - */ - private function kingbaseSchemaCacheKey(string $tableName): string - { - [$tableName] = explode(' ', trim($tableName), 2); - $tableName = str_replace(['`', '"', '[', ']'], '', $tableName); - $schema = str_contains($tableName, '.') - ? $tableName - : $this->getConfig('database') . '.' . $tableName; - - return $this->getSchemaCacheKey($schema); - } - - /** - * 从常见 DDL 中提取受影响的表名,用于删除跨连接字段缓存。 - */ - private function extractKingbaseDdlTable(string $sql): ?string - { - $patterns = [ - '/^\s*(?:CREATE|ALTER|DROP|TRUNCATE)\s+(?:TABLE|VIEW)\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?([^\s(;]+)/i', - '/^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+[^\s]+\s+ON\s+([^\s(]+)/i', - '/^\s*COMMENT\s+ON\s+COLUMN\s+([^\s]+)\s+IS\b/i', - ]; - - foreach ($patterns as $pattern) { - if (1 !== preg_match($pattern, $sql, $match)) { - continue; - } - $name = str_replace(['`', '"', '[', ']'], '', $match[1]); - if (str_starts_with(strtoupper(ltrim($sql)), 'COMMENT ON COLUMN')) { - $parts = explode('.', $name); - if (count($parts) > 1) { - array_pop($parts); - $name = implode('.', $parts); - } - } - - return '' === $name ? null : $name; - } - - return null; - } - /** * 校验不带限定符的 KingbaseES 数据库对象标识符。 * From a16013315ee1cdba8b0879ce061e55ed06dafdd6 Mon Sep 17 00:00:00 2001 From: Leec0nAn <1148768305@qq.com> Date: Mon, 26 Oct 2026 00:33:32 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E8=B0=83=E6=95=B4KingbaseConnection?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/{connector => }/concern/KingbaseConnection.php | 2 +- src/db/connector/KingbaseMysql.php | 2 +- src/db/connector/KingbaseOracle.php | 2 +- src/db/connector/KingbaseSqlsrv.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) rename src/db/{connector => }/concern/KingbaseConnection.php (99%) diff --git a/src/db/connector/concern/KingbaseConnection.php b/src/db/concern/KingbaseConnection.php similarity index 99% rename from src/db/connector/concern/KingbaseConnection.php rename to src/db/concern/KingbaseConnection.php index f163a376..ab13ed55 100644 --- a/src/db/connector/concern/KingbaseConnection.php +++ b/src/db/concern/KingbaseConnection.php @@ -9,7 +9,7 @@ // +---------------------------------------------------------------------- declare(strict_types=1); -namespace think\db\connector\concern; +namespace think\db\concern; use PDO; use think\db\BaseQuery; diff --git a/src/db/connector/KingbaseMysql.php b/src/db/connector/KingbaseMysql.php index 6acfbeb7..41e91874 100644 --- a/src/db/connector/KingbaseMysql.php +++ b/src/db/connector/KingbaseMysql.php @@ -12,7 +12,7 @@ namespace think\db\connector; use PDO; -use think\db\connector\concern\KingbaseConnection; +use think\db\concern\KingbaseConnection; /** * KingbaseES MySQL 兼容模式数据库连接器。 diff --git a/src/db/connector/KingbaseOracle.php b/src/db/connector/KingbaseOracle.php index 67874465..5a67289a 100644 --- a/src/db/connector/KingbaseOracle.php +++ b/src/db/connector/KingbaseOracle.php @@ -13,7 +13,7 @@ use PDO; use think\db\BaseQuery; -use think\db\connector\concern\KingbaseConnection; +use think\db\concern\KingbaseConnection; /** * KingbaseES Oracle 兼容模式数据库连接器。 diff --git a/src/db/connector/KingbaseSqlsrv.php b/src/db/connector/KingbaseSqlsrv.php index 4b81167e..00217601 100644 --- a/src/db/connector/KingbaseSqlsrv.php +++ b/src/db/connector/KingbaseSqlsrv.php @@ -12,7 +12,7 @@ namespace think\db\connector; use PDO; -use think\db\connector\concern\KingbaseConnection; +use think\db\concern\KingbaseConnection; use think\model\type\KingbaseDateTime; /** From 67aeaf232c570ae179d2719491bfa265c880c104 Mon Sep 17 00:00:00 2001 From: Leec0nAn <1148768305@qq.com> Date: Mon, 26 Oct 2026 08:52:06 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/builder/KingbaseOracle.php | 10 ++--- src/db/builder/KingbaseSqlsrv.php | 8 ++-- src/db/concern/KingbaseConnection.php | 34 ++++++++-------- src/db/connector/Kingbase.php | 16 ++++---- src/db/connector/KingbaseModeDetector.php | 28 ++++++------- src/db/connector/KingbaseMysql.php | 36 ++++++++--------- src/db/connector/KingbaseOracle.php | 40 +++++++++---------- src/db/connector/KingbaseSqlsrv.php | 48 +++++++++++------------ 8 files changed, 110 insertions(+), 110 deletions(-) diff --git a/src/db/builder/KingbaseOracle.php b/src/db/builder/KingbaseOracle.php index 1667ceaa..07091821 100644 --- a/src/db/builder/KingbaseOracle.php +++ b/src/db/builder/KingbaseOracle.php @@ -29,7 +29,7 @@ class KingbaseOracle extends Oracle public function insertAll(Query $query, array $dataSet): string { $options = $query->getOptions(); - $bind = $query->getFieldsBindType(); + $bind = $query->getFieldsBindType(); if (empty($options['field']) || '*' == $options['field']) { $allowFields = array_keys($bind); @@ -37,7 +37,7 @@ public function insertAll(Query $query, array $dataSet): string $allowFields = $options['field']; } - $values = []; + $values = []; $insertFields = null; foreach ($dataSet as $data) { @@ -76,9 +76,9 @@ public function insertAll(Query $query, array $dataSet): string public function insertAllByKeys(Query $query, array $keys, array $datas): string { $options = $query->getOptions(); - $bind = $query->getFieldsBindType(); - $fields = []; - $values = []; + $bind = $query->getFieldsBindType(); + $fields = []; + $values = []; foreach ($keys as $field) { $fields[] = $this->parseKey($query, $field); diff --git a/src/db/builder/KingbaseSqlsrv.php b/src/db/builder/KingbaseSqlsrv.php index 48adedc4..57441671 100644 --- a/src/db/builder/KingbaseSqlsrv.php +++ b/src/db/builder/KingbaseSqlsrv.php @@ -36,7 +36,7 @@ class KingbaseSqlsrv extends Sqlsrv public function insertAll(Query $query, array $dataSet): string { $options = $query->getOptions(); - $bind = $query->getFieldsBindType(); + $bind = $query->getFieldsBindType(); if (empty($options['field']) || '*' == $options['field']) { $allowFields = array_keys($bind); @@ -90,9 +90,9 @@ public function insertAll(Query $query, array $dataSet): string public function insertAllByKeys(Query $query, array $keys, array $datas): string { $options = $query->getOptions(); - $bind = $query->getFieldsBindType(); - $fields = []; - $values = []; + $bind = $query->getFieldsBindType(); + $fields = []; + $values = []; foreach ($keys as $field) { $fields[] = $this->parseKey($query, $field); diff --git a/src/db/concern/KingbaseConnection.php b/src/db/concern/KingbaseConnection.php index ab13ed55..4566b0c7 100644 --- a/src/db/concern/KingbaseConnection.php +++ b/src/db/concern/KingbaseConnection.php @@ -71,7 +71,7 @@ public function connect(array $config = [], $linkNum = 0, $autoConnection = fals return $pdo; } catch (\PDOException $e) { $message = $this->formatKingbaseConnectionFailure($mergedConfig, $e); - $code = is_numeric($e->getCode()) ? (int) $e->getCode() : 0; + $code = is_numeric($e->getCode()) ? (int) $e->getCode() : 0; throw new \PDOException($message, $code, $e); } @@ -85,7 +85,7 @@ public function connect(array $config = [], $linkNum = 0, $autoConnection = fals public function close() { $this->kingbaseInitializedLinks = []; - $this->kingbaseResolvedSchema = ''; + $this->kingbaseResolvedSchema = ''; $this->resetKingbaseGeneratedKeyContext(); return parent::close(); @@ -262,9 +262,9 @@ protected function getFieldType(string $type): string public function getFieldBindType(string $type): int { return match ($type) { - 'kingbase_lob' => PDO::PARAM_LOB, + 'kingbase_lob' => PDO::PARAM_LOB, 'kingbase_bit_string' => PDO::PARAM_STR, - default => parent::getFieldBindType($type), + default => parent::getFieldBindType($type), }; } @@ -291,7 +291,7 @@ protected function resolveKingbaseGeneratedKey(callable $resolver, mixed $empty return $empty; } - $this->kingbaseGeneratedKey = $value; + $this->kingbaseGeneratedKey = $value; $this->kingbaseGeneratedKeyCached = true; return $value; @@ -344,8 +344,8 @@ protected function initializeKingbaseSession(PDO $pdo, array $config): void $configuredSchema = trim((string) ($config['schema'] ?? '')); if ('' !== $configuredSchema) { $configuredSchema = $this->validateKingbaseIdentifier($configuredSchema, 'schema'); - $quotedSchema = '"' . str_replace('"', '""', $configuredSchema) . '"'; - $searchPath = 'public' === strtolower($configuredSchema) + $quotedSchema = '"' . str_replace('"', '""', $configuredSchema) . '"'; + $searchPath = 'public' === strtolower($configuredSchema) ? $quotedSchema : $quotedSchema . ', public'; @@ -371,7 +371,7 @@ protected function initializeKingbaseSession(PDO $pdo, array $config): void ); } - $this->kingbaseResolvedSchema = $currentSchema; + $this->kingbaseResolvedSchema = $currentSchema; $this->kingbaseInitializedLinks[$hash] = true; } @@ -382,14 +382,14 @@ protected function prepareKingbaseGeneratedKeyContext(BaseQuery $query): void { $this->resetKingbaseGeneratedKeyContext(); - $options = $query->getOptions(); - $data = is_array($options['data'] ?? null) ? $options['data'] : []; + $options = $query->getOptions(); + $data = is_array($options['data'] ?? null) ? $options['data'] : []; $sequence = trim((string) ($options['sequence'] ?? '')); - $mode = $this->getExpectedKingbaseMode(); + $mode = $this->getExpectedKingbaseMode(); if ('oracle' === $mode && '' !== $sequence && $this->dataUsesKingbaseSequence($data, $sequence)) { $this->kingbaseGeneratedKeyExpected = true; - $this->kingbaseInsertSequence = $sequence; + $this->kingbaseInsertSequence = $sequence; return; } @@ -420,7 +420,7 @@ protected function prepareKingbaseGeneratedKeyContext(BaseQuery $query): void } $this->kingbaseGeneratedKeyExpected = true; - $this->kingbaseInsertSequence = $metadataSequence; + $this->kingbaseInsertSequence = $metadataSequence; } /** @@ -429,9 +429,9 @@ protected function prepareKingbaseGeneratedKeyContext(BaseQuery $query): void protected function resetKingbaseGeneratedKeyContext(): void { $this->kingbaseGeneratedKeyExpected = false; - $this->kingbaseGeneratedKey = null; - $this->kingbaseGeneratedKeyCached = false; - $this->kingbaseInsertSequence = null; + $this->kingbaseGeneratedKey = null; + $this->kingbaseGeneratedKeyCached = false; + $this->kingbaseInsertSequence = null; } /** @@ -530,7 +530,7 @@ protected function formatKingbaseConnectionFailure(array $config, \PDOException } } - $message = $exception->getMessage(); + $message = $exception->getMessage(); $password = (string) ($config['password'] ?? ''); if ('' !== $password) { $message = str_replace($password, '***', $message); diff --git a/src/db/connector/Kingbase.php b/src/db/connector/Kingbase.php index 6bf537c3..4251e662 100644 --- a/src/db/connector/Kingbase.php +++ b/src/db/connector/Kingbase.php @@ -37,11 +37,11 @@ class Kingbase implements ConnectionInterface */ public function __construct(array $config = []) { - $this->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); + $this->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); } /** @@ -70,10 +70,10 @@ public function getKingbaseMode(): string private function resolveConnectorClass(string $mode): string { return match ($mode) { - 'mysql' => KingbaseMysql::class, - 'oracle' => KingbaseOracle::class, + 'mysql' => KingbaseMysql::class, + 'oracle' => KingbaseOracle::class, 'sqlserver' => KingbaseSqlsrv::class, - default => throw new \InvalidArgumentException('Unsupported KES database_mode: ' . $mode), + default => throw new \InvalidArgumentException('Unsupported KES database_mode: ' . $mode), }; } diff --git a/src/db/connector/KingbaseModeDetector.php b/src/db/connector/KingbaseModeDetector.php index c4b23bb7..562d9ce9 100644 --- a/src/db/connector/KingbaseModeDetector.php +++ b/src/db/connector/KingbaseModeDetector.php @@ -34,14 +34,14 @@ final class KingbaseModeDetector public static function detect(array $config): string { $probeConfig = self::firstEndpoint($config); - $dsn = self::buildDsn($probeConfig); - $params = is_array($probeConfig['params'] ?? null) ? $probeConfig['params'] : []; - $params = $params + [ - PDO::ATTR_CASE => PDO::CASE_LOWER, - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, - PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, + $dsn = self::buildDsn($probeConfig); + $params = is_array($probeConfig['params'] ?? null) ? $probeConfig['params'] : []; + $params = $params + [ + PDO::ATTR_CASE => 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, + PDO::ATTR_EMULATE_PREPARES => false, ]; try { @@ -96,10 +96,10 @@ public static function detect(array $config): string public static function connectorType(string $mode): string { return match (self::normalizeMode($mode)) { - 'mysql' => 'kingbaseMysql', - 'oracle' => 'kingbaseOracle', + 'mysql' => 'kingbaseMysql', + 'oracle' => 'kingbaseOracle', 'sqlserver' => 'kingbaseSqlsrv', - default => throw new \InvalidArgumentException('Unsupported KES database_mode: ' . $mode), + default => throw new \InvalidArgumentException('Unsupported KES database_mode: ' . $mode), }; } @@ -134,11 +134,11 @@ private static function normalizeMode(string $mode): string $mode = strtolower(trim($mode)); return match ($mode) { - 'mysql', 'kingbasemysql' => 'mysql', - 'oracle', 'kingbaseoracle' => 'oracle', + 'mysql', 'kingbasemysql' => 'mysql', + 'oracle', 'kingbaseoracle' => 'oracle', 'sqlsrv', 'sqlserver', 'kingbasesqlsrv', - 'kingbasesqlserver' => 'sqlserver', - default => '', + 'kingbasesqlserver' => 'sqlserver', + default => '', }; } diff --git a/src/db/connector/KingbaseMysql.php b/src/db/connector/KingbaseMysql.php index 41e91874..19df0556 100644 --- a/src/db/connector/KingbaseMysql.php +++ b/src/db/connector/KingbaseMysql.php @@ -52,18 +52,18 @@ protected function parseDsn(array $config): string public function getFields(string $tableName): array { [$tableName] = explode(' ', $tableName); - $tableName = trim($tableName, '`"'); + $tableName = trim($tableName, '`"'); if (str_contains($tableName, '.')) { [$schema, $tableName] = explode('.', $tableName, 2); - $schema = trim($schema, '`"'); - $tableName = trim($tableName, '`"'); + $schema = trim($schema, '`"'); + $tableName = trim($tableName, '`"'); } else { $schema = $this->getSchemaName(); } $schemaValue = $this->quoteString($schema); - $tableValue = $this->quoteString($tableName); + $tableValue = $this->quoteString($tableName); $sql = <<getPDOStatement($sql); + $pdo = $this->getPDOStatement($sql); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); - $info = []; + $info = []; foreach ($result as $val) { - $val = array_change_key_case($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' => $val['default'], - 'primary' => (bool) $val['primary'], - 'autoinc' => '' !== (string) $val['attidentity'] || !empty($val['serial_sequence']), + 'name' => $field, + 'type' => $val['full_type'] ?: $val['type'], + 'notnull' => 'NO' === strtoupper((string) $val['is_nullable']), + 'default' => $val['default'], + 'primary' => (bool) $val['primary'], + 'autoinc' => '' !== (string) $val['attidentity'] || !empty($val['serial_sequence']), 'sequence' => $val['serial_sequence'] ?: null, - 'comment' => $val['comment'], + 'comment' => $val['comment'], ]; } @@ -145,9 +145,9 @@ public function getFields(string $tableName): array */ public function getTables(string $dbName = ''): array { - $schema = $dbName ?: $this->getSchemaName(); + $schema = $dbName ?: $this->getSchemaName(); $schemaValue = $this->quoteString($schema); - $sql = <<getPDOStatement($sql); + $pdo = $this->getPDOStatement($sql); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); return array_column($result, 'table_name'); @@ -174,7 +174,7 @@ public function getTables(string $dbName = ''): array public function getAutoID(?string $sequence = null) { return $this->resolveKingbaseGeneratedKey(function () { - $pdo = $this->linkID->query('SELECT LAST_INSERT_ID() AS id'); + $pdo = $this->linkID->query('SELECT LAST_INSERT_ID() AS id'); $result = $pdo->fetch(PDO::FETCH_ASSOC); return isset($result['id']) ? (string) $result['id'] : ''; diff --git a/src/db/connector/KingbaseOracle.php b/src/db/connector/KingbaseOracle.php index 5a67289a..83e590fa 100644 --- a/src/db/connector/KingbaseOracle.php +++ b/src/db/connector/KingbaseOracle.php @@ -32,11 +32,11 @@ class KingbaseOracle extends Oracle * @var array */ protected $params = [ - PDO::ATTR_CASE => PDO::CASE_LOWER, - PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, - PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL, + PDO::ATTR_CASE => 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, + PDO::ATTR_EMULATE_PREPARES => false, ]; /** @@ -75,7 +75,7 @@ public function getFields(string $tableName): array if (null === $owner) { $tableValue = $this->quoteString($tableName); - $sql = <<quoteString($owner); $tableValue = $this->quoteString($tableName); - $sql = <<getPDOStatement($sql); - $result = $pdo->fetchAll(PDO::FETCH_ASSOC); - $info = []; + $pdo = $this->getPDOStatement($sql); + $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + $info = []; $generatedFields = $this->getGeneratedFields($owner ?? $this->getKingbaseSchema(), $tableName); foreach ($result as $val) { - $val = array_change_key_case($val); + $val = array_change_key_case($val); $field = strtolower($val['field']); $info[$field] = [ - 'name' => $field, - 'type' => $val['type'], - 'notnull' => 'N' === strtoupper((string) $val['nullable']), - 'default' => $val['default'], - 'primary' => (bool) $val['primary'], - 'autoinc' => array_key_exists($field, $generatedFields), + 'name' => $field, + 'type' => $val['type'], + 'notnull' => 'N' === strtoupper((string) $val['nullable']), + 'default' => $val['default'], + 'primary' => (bool) $val['primary'], + 'autoinc' => array_key_exists($field, $generatedFields), 'sequence' => $generatedFields[$field] ?? null, - 'comment' => $val['comment'], + 'comment' => $val['comment'], ]; } @@ -233,7 +233,7 @@ public function getTables(string $dbName = ''): array SQL; } else { $ownerValue = $this->quoteString($this->normalizeOracleName($dbName)); - $sql = <<getPDOStatement($sql); + $pdo = $this->getPDOStatement($sql); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); return array_map('current', $result); @@ -277,7 +277,7 @@ public function getLastInsID(BaseQuery $query, ?string $sequence = null) return $this->resolveKingbaseGeneratedKey(function () use ($sequence) { $sequence = $this->parseSequenceName($sequence); - $pdo = $this->linkID->query("SELECT {$sequence}.CURRVAL AS id FROM dual"); + $pdo = $this->linkID->query("SELECT {$sequence}.CURRVAL AS id FROM dual"); return $pdo->fetchColumn(); }); diff --git a/src/db/connector/KingbaseSqlsrv.php b/src/db/connector/KingbaseSqlsrv.php index 00217601..bbffebb4 100644 --- a/src/db/connector/KingbaseSqlsrv.php +++ b/src/db/connector/KingbaseSqlsrv.php @@ -72,23 +72,23 @@ public function getFields(string $tableName): array [$tableName] = explode(' ', $tableName); [$schema, $tableName] = $this->parseSqlsrvTable($tableName); - $result = $this->getColumnRows($schema, $tableName); + $result = $this->getColumnRows($schema, $tableName); $comments = $this->getColumnComments($schema, $tableName); - $info = []; + $info = []; foreach ($result as $val) { - $val = array_change_key_case($val); + $val = array_change_key_case($val); $field = strtolower($val['field']); $info[$field] = [ - 'name' => $field, - 'type' => $val['type'], - 'notnull' => 'NO' === strtoupper((string) $val['is_nullable']), - 'default' => $val['default'], - 'primary' => false, - 'autoinc' => false, + 'name' => $field, + 'type' => $val['type'], + 'notnull' => 'NO' === strtoupper((string) $val['is_nullable']), + 'default' => $val['default'], + 'primary' => false, + 'autoinc' => false, 'sequence' => null, - 'comment' => $comments[$field] ?? null, + 'comment' => $comments[$field] ?? null, ]; } @@ -120,9 +120,9 @@ public function getFields(string $tableName): array */ public function getTables(string $dbName = ''): array { - $schema = $dbName ?: $this->getSchemaName(); + $schema = $dbName ?: $this->getSchemaName(); $schemaValue = $this->quoteString($schema); - $sql = <<getPDOStatement($sql); + $pdo = $this->getPDOStatement($sql); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); return array_column($result, 'table_name'); @@ -162,9 +162,9 @@ public function getAutoID(?string $sequence = null) return $this->resolveKingbaseGeneratedKey(function () { foreach (['SELECT SCOPE_IDENTITY() AS id', 'SELECT @@IDENTITY AS id'] as $sql) { try { - $pdo = $this->linkID->query($sql); + $pdo = $this->linkID->query($sql); $result = $pdo->fetch(PDO::FETCH_ASSOC); - $id = is_array($result) ? ($result['id'] ?? current($result)) : ''; + $id = is_array($result) ? ($result['id'] ?? current($result)) : ''; if ('' !== $id && false !== $id && null !== $id) { return (string) $id; @@ -291,7 +291,7 @@ protected function getExpectedKingbaseMode(): string protected function getColumnRows(string $schema, string $tableName): array { $schemaValue = $this->quoteString($schema); - $tableValue = $this->quoteString($tableName); + $tableValue = $this->quoteString($tableName); $sql = <<getPDOStatement($sql); + $pdo = $this->getPDOStatement($sql); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); return $result; @@ -325,7 +325,7 @@ protected function getColumnRows(string $schema, string $tableName): array protected function getColumnComments(string $schema, string $tableName): array { $schemaValue = $this->quoteString($schema); - $tableValue = $this->quoteString($tableName); + $tableValue = $this->quoteString($tableName); $sql = <<quoteString($schema); - $tableValue = $this->quoteString($tableName); - $sql = <<quoteString($tableName); + $sql = <<getPDOStatement($sql); + $pdo = $this->getPDOStatement($sql); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); return array_map('current', $result); @@ -400,16 +400,16 @@ protected function getPrimaryFields(string $schema, string $tableName): array */ protected function getIdentityFields(string $schema, string $tableName): array { - $objectName = $schema . '.' . $tableName; + $objectName = $schema . '.' . $tableName; $objectValue = $this->quoteString($objectName); - $sql = <<getPDOStatement($sql); + $pdo = $this->getPDOStatement($sql); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); return array_map('current', $result); From 1d0dc87c74fc2355f3a942d71b23b41498fa5f65 Mon Sep 17 00:00:00 2001 From: Leec0nAn <1148768305@qq.com> Date: Tue, 17 Nov 2026 21:24:47 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E9=9C=80=E6=B1=82=E6=96=87=E6=A1=A3v0.4?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/db/builder/KingbaseMysql.php | 63 +-- src/db/builder/KingbaseOracle.php | 50 +- src/db/builder/KingbaseSqlsrv.php | 110 +---- src/db/concern/KingbaseConnection.php | 366 +++----------- src/db/concern/KingbaseResult.php | 449 ++++++++++++++++++ src/db/connector/Kingbase.php | 47 +- .../KingbaseConnectionDiagnostics.php | 116 +++++ src/db/connector/KingbaseModeDetector.php | 25 +- src/db/connector/KingbaseMysql.php | 173 ++++--- src/db/connector/KingbaseOracle.php | 315 ++---------- src/db/connector/KingbasePDO.php | 62 +++ src/db/connector/KingbaseSqlsrv.php | 417 +--------------- src/model/type/KingbaseDateTime.php | 39 -- 13 files changed, 948 insertions(+), 1284 deletions(-) create mode 100644 src/db/concern/KingbaseResult.php create mode 100644 src/db/connector/KingbaseConnectionDiagnostics.php create mode 100644 src/db/connector/KingbasePDO.php delete mode 100644 src/model/type/KingbaseDateTime.php diff --git a/src/db/builder/KingbaseMysql.php b/src/db/builder/KingbaseMysql.php index 63d7592e..f9ba8c3f 100644 --- a/src/db/builder/KingbaseMysql.php +++ b/src/db/builder/KingbaseMysql.php @@ -12,6 +12,7 @@ namespace think\db\builder; use think\db\BaseQuery as Query; +use think\db\Connection; use think\db\Raw; /** @@ -20,10 +21,11 @@ class KingbaseMysql extends Mysql { /** - * 生成数据字段的参数占位符,并适配 JSON 路径更新。 + * 生成写入参数占位符,适配整数列的布尔绑定。 * - * KingbaseES MySQL 兼容函数有时无法推断 JSON 路径更新值对应的 PDO 占位符 - * 类型,因此将该占位符显式转换为 TEXT;普通字段沿用父构造器行为。 + * Model 的 bool 配置可能覆盖整数列的绑定类型;此时按实际字段绑定信息 + * 使用 1/0 整数参数,避免 PDO_KDB + * 发送 t/f。真正的 BOOLEAN 列、NULL 和其他绑定类型仍沿用原处理。 * * @param Query $query 当前查询对象 * @param string $key 字段名或 JSON 路径 @@ -34,51 +36,18 @@ class KingbaseMysql extends Mysql */ protected function parseDataBind(Query $query, string $key, $data, array $bind = []): string { - $placeholder = parent::parseDataBind($query, $key, $data, $bind); - - if (str_contains($key, '->')) { - return 'CAST(' . $placeholder . ' AS TEXT)'; - } - - return $placeholder; - } - - /** - * 将兼容函数使用的字符串占位符显式转换为 TEXT。 - * - * Raw 表达式保持原样解析,冒号开头的绑定占位符增加 CAST,其余值直接转为字符串。 - * - * @param Query $query 当前查询对象 - * @param mixed $value 原始值、占位符或 Raw 表达式 - * - * @return string 可拼入 SQL 的文本表达式 - */ - protected function parseTextValue(Query $query, $value): string - { - if ($value instanceof Raw) { - return $this->parseRaw($query, $value); + 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; + } } - if (is_string($value) && str_starts_with($value, ':')) { - return 'CAST(' . $value . ' AS TEXT)'; - } - - return (string) $value; - } - - /** - * 构造 MySQL 兼容模式的 FIND_IN_SET 条件。 - * - * @param Query $query 当前查询对象 - * @param string $key 已解析的字段表达式 - * @param string $exp 查询运算符,保留父方法接口一致性 - * @param mixed $value 待查找值或绑定占位符 - * @param string $field 原始字段名,保留父方法接口一致性 - * - * @return string FIND_IN_SET 函数 SQL - */ - protected function parseFindInSet(Query $query, string $key, string $exp, $value, string $field): string - { - return 'FIND_IN_SET(' . $this->parseTextValue($query, $value) . ', ' . $key . ')'; + return parent::parseDataBind($query, $key, $data, $bind); } } diff --git a/src/db/builder/KingbaseOracle.php b/src/db/builder/KingbaseOracle.php index 07091821..f2bd141c 100644 --- a/src/db/builder/KingbaseOracle.php +++ b/src/db/builder/KingbaseOracle.php @@ -19,6 +19,41 @@ */ class KingbaseOracle extends Oracle { + /** + * 单表 Model 查询显式保留字段名,避免 enable_upper_colname 改变模型主键。 + * + * 元数据中的字段名是目录值,不受 PDO 的列名大小写策略控制。为模型字段增加 + * 同名双引号别名,使返回数据仍使用元数据名称;普通 Query、关联查询、表达式 + * 和用户显式设置的别名继续使用原 Builder 行为,不统一转换结果键。 + */ + protected function parseField(Query $query, array $fields): string + { + $table = $query->getTable(); + if (!$query->getModel() || $query->getOption('join') || !is_string($table) + || false !== strpbrk($table, ',()')) { + return parent::parseField($query, $fields); + } + + $names = $query->getTableFields(); + if (!$names) { + return parent::parseField($query, $fields); + } + if (!$fields || ['*'] === $fields) { + $fields = $names; + } + + $parts = []; + foreach ($fields as $key => $field) { + if (is_int($key) && is_string($field) && in_array($field, $names, true)) { + $parts[] = $this->parseKey($query, $field) . ' AS "' . str_replace('"', '""', $field) . '"'; + } else { + $parts[] = parent::parseField($query, [$key => $field]); + } + } + + return implode(',', $parts); + } + /** * 使用 VALUES 语法构造多行 INSERT。 * @@ -111,19 +146,4 @@ public function insertAllByKeys(Query $query, array $keys, array $datas): string $this->insertAllSql ); } - - /** - * 生成 Oracle 兼容模式随机排序表达式。 - * - * KingbaseES Oracle 兼容模式未暴露 DBMS_RANDOM 包,因此使用 random()。 - * - * @param Query $query 当前查询对象,保留父方法接口一致性 - * - * @return string random() 表达式 - */ - protected function parseRand(Query $query): string - { - return 'random()'; - } - } diff --git a/src/db/builder/KingbaseSqlsrv.php b/src/db/builder/KingbaseSqlsrv.php index 57441671..bb35025f 100644 --- a/src/db/builder/KingbaseSqlsrv.php +++ b/src/db/builder/KingbaseSqlsrv.php @@ -11,117 +11,9 @@ namespace think\db\builder; -use think\db\BaseQuery as Query; -use think\db\Connection; - /** - * KingbaseES SQL Server 兼容模式 SQL 构造器。 + * KingbaseES SQL Server 兼容模式 SQL 构造器,直接沿用原 Sqlsrv 生成规则。 */ class KingbaseSqlsrv extends Sqlsrv { - /** - * 使用 VALUES 语法构造多行 INSERT。 - * - * 避免父 SQL Server 方言的 UNION SELECT 批量写法,使 KingbaseES 能依据目标列 - * 正确推断每个占位符的数据类型。 - * - * @param Query $query 当前查询对象 - * @param array $dataSet 多行待插入数据 - * - * 仅改写父 SQL Server Builder 的 SQL 结构;各行字段和值仍按照原框架的 - * 数组迭代顺序处理,不在适配层重新排序或增加字段集合校验。 - * - * @return string 完整批量 INSERT SQL - */ - public function insertAll(Query $query, array $dataSet): string - { - $options = $query->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( - ['%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'], - [ - $this->parseTable($query, $options['table']), - implode(' , ', $fields), - 'VALUES ' . implode(' , ', $values), - $this->parseComment($query, $options['comment']), - ], - $this->insertAllSql - ); - } - - /** - * 按固定字段集合使用 VALUES 语法构造多行 INSERT。 - * - * 根据查询是否启用自动绑定生成字面量或参数占位符,并确保所有行复用同一字段顺序。 - * - * @param Query $query 当前查询对象 - * @param array $keys 固定字段名列表 - * @param array $datas 按字段顺序组织的多行数据 - * - * @return string 完整批量 INSERT SQL - */ - 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( - ['%TABLE%', '%FIELD%', '%DATA%', '%COMMENT%'], - [ - $this->parseTable($query, $options['table']), - implode(' , ', $fields), - 'VALUES ' . implode(' , ', $values), - $this->parseComment($query, $options['comment']), - ], - $this->insertAllSql - ); - } - } diff --git a/src/db/concern/KingbaseConnection.php b/src/db/concern/KingbaseConnection.php index 4566b0c7..9df64c1d 100644 --- a/src/db/concern/KingbaseConnection.php +++ b/src/db/concern/KingbaseConnection.php @@ -12,51 +12,62 @@ namespace think\db\concern; use PDO; -use think\db\BaseQuery; -use think\db\Raw; /** * KingbaseES 三种兼容模式连接器共用的 PDO_KDB 初始化逻辑。 */ trait KingbaseConnection { + use KingbaseResult; + /** - * Initialized PDO object hashes. + * 已完成初始化的 PDO 对象,按对象哈希去重。 * * @var array */ protected array $kingbaseInitializedLinks = []; /** - * Schema discovered from the current PDO_KDB session. + * 根据 ThinkORM 连接配置生成三个兼容模式共用的 PDO_KDB DSN。 + * + * @param array $config 数据库连接配置 + * + * @return string kdb: 协议 DSN */ - protected string $kingbaseResolvedSchema = ''; + protected function parseDsn(array $config): string + { + $dsn = 'kdb:host=' . $config['hostname'] . ';dbname=' . $config['database']; - /** 当前 INSERT 是否真实具备数据库生成主键的语义。 */ - protected bool $kingbaseGeneratedKeyExpected = false; + if (!empty($config['hostport'])) { + $dsn .= ';port=' . $config['hostport']; + } - /** 当前 INSERT 已读取到的生成主键,供 Model 后续再次读取。 */ - protected mixed $kingbaseGeneratedKey = null; + return $dsn; + } - /** 当前 INSERT 的生成主键是否已成功读取。 */ - protected bool $kingbaseGeneratedKeyCached = false; + /** MySQL 结果转换需要跟随运行时设置;其余模式保留原 PDO 创建流程。 */ + protected function createPdo($dsn, $username, $password, $params) + { + if ('mysql' === $this->getExpectedKingbaseMode()) { + return new \think\db\connector\KingbasePDO($dsn, $username, $password, $params); + } - /** 当前 Oracle INSERT 实际使用或由字段默认值解析出的序列。 */ - protected ?string $kingbaseInsertSequence = null; + return parent::createPdo($dsn, $username, $password, $params); + } /** * 建立 PDO_KDB 连接并初始化 KingbaseES 会话。 * - * 在父连接器完成物理连接后校验驱动、数据库兼容模式和 Schema;连接失败时补充 - * 主机、端口及数据库名等诊断信息,同时对口令脱敏并保留原始 PDOException。 + * 在父连接器完成物理连接后校验驱动、数据库兼容模式并读取会话默认 Schema;连接失败时补充 + * 主机、端口及数据库名等诊断信息,同时保留 PDO 异常类型和安全错误信息,避免异常链泄露口令。 * * @param array $config 本次连接覆盖配置,为空时使用连接器默认配置 * @param int $linkNum 连接编号,用于读写分离或多连接场景 * @param array|bool $autoConnection 自动连接配置或是否启用自动连接 * * @throws \PDOException 物理连接失败 - * @throws \UnexpectedValueException 驱动、兼容模式或 Schema 与配置不一致 - * @throws \InvalidArgumentException Schema 标识符不合法 + * @throws \UnexpectedValueException 驱动或兼容模式不符合预期 + * @throws \InvalidArgumentException 当前会话的 Schema 标识符不合法 * * @return PDO 已完成 KingbaseES 会话初始化的 PDO 对象 */ @@ -66,14 +77,16 @@ public function connect(array $config = [], $linkNum = 0, $autoConnection = fals try { $pdo = parent::connect($config, $linkNum, $autoConnection); - $this->initializeKingbaseSession($pdo, $mergedConfig); + $this->initializeKingbaseSession($pdo); return $pdo; } catch (\PDOException $e) { $message = $this->formatKingbaseConnectionFailure($mergedConfig, $e); - $code = is_numeric($e->getCode()) ? (int) $e->getCode() : 0; - - throw new \PDOException($message, $code, $e); + throw \think\db\connector\KingbaseConnectionDiagnostics::exception( + $message, + $e, + (string) ($mergedConfig['password'] ?? '') + ); } } @@ -85,90 +98,10 @@ public function connect(array $config = [], $linkNum = 0, $autoConnection = fals public function close() { $this->kingbaseInitializedLinks = []; - $this->kingbaseResolvedSchema = ''; - $this->resetKingbaseGeneratedKeyContext(); return parent::close(); } - /** - * 执行原生 SQL,并在原生写入前清理 ORM 生成主键上下文。 - * - * 原生 INSERT 无法从 Query 元数据确认主键生成语义,因此先清除上一次 ORM - * INSERT 的生成键上下文,避免随后 getLastInsID() 返回历史值。DDL 后的字段 - * 缓存行为继续沿用原 PDOConnection,不在适配层增加自动失效处理。 - * - * @param string $sql SQL 语句 - * @param array $bind 参数绑定 - * - * @return int 影响行数 - */ - public function execute(string $sql, array $bind = []): int - { - if (1 === preg_match('/^\s*(?:INSERT|REPLACE|MERGE)\b/i', $sql)) { - $this->resetKingbaseGeneratedKeyContext(); - } - - return parent::execute($sql, $bind); - } - - /** - * 执行单行 INSERT,并建立仅属于本次 INSERT 的生成主键上下文。 - * - * 父连接器会在 INSERT 成功后读取生成主键,Model 随后还可能再次调用 - * getLastInsID()。这里缓存本次真实生成的值,同时在显式普通主键场景返回空值, - * 避免 LAST_INSERT_ID()/CURRVAL/@@IDENTITY 的历史会话值被误认为本次主键。 - * - * @param BaseQuery $query 查询对象 - * @param bool $getLastInsID 是否返回生成主键 - * - * @return mixed 插入结果或本次生成主键 - */ - public function insert(BaseQuery $query, bool $getLastInsID = false) - { - $this->prepareKingbaseGeneratedKeyContext($query); - - try { - $result = parent::insert($query, $getLastInsID); - } catch (\Throwable $exception) { - $this->resetKingbaseGeneratedKeyContext(); - throw $exception; - } - - if ($getLastInsID) { - return $this->kingbaseGeneratedKeyCached ? $this->kingbaseGeneratedKey : ''; - } - - return $result; - } - - /** - * 批量插入不会产生可安全归属到单行的生成主键,执行前清理历史上下文。 - * - * @param BaseQuery $query 查询对象 - * @param array $dataSet 数据集 - */ - public function insertAll(BaseQuery $query, array $dataSet = []): int - { - $this->resetKingbaseGeneratedKeyContext(); - - return parent::insertAll($query, $dataSet); - } - - /** - * 固定字段批量插入不会返回单行生成主键,执行前清理历史上下文。 - * - * @param BaseQuery $query 查询对象 - * @param array $keys 字段集合 - * @param array $values 数据集合 - */ - public function insertAllByKeys(BaseQuery $query, array $keys, array $values): int - { - $this->resetKingbaseGeneratedKeyContext(); - - return parent::insertAllByKeys($query, $keys, $values); - } - /** * 获取当前连接器要求的 KingbaseES 兼容模式。 * @@ -180,26 +113,22 @@ public function getKingbaseMode(): string } /** - * 获取配置或由当前会话解析得到的 Schema。 + * 从本次元数据查询实际使用的连接读取当前 Schema。 * - * 尚未建立连接时会主动初始化连接;仍无法确定 Schema 时抛出异常,避免后续 - * 元数据查询误落入其他模式。 + * 路由与 getPDOStatement 一致,包含写后读主库和事务固定连接;每次直接 + * 读取都确认会话状态,不复用另一物理连接留下的 Schema。 * - * @throws \UnexpectedValueException 无法解析当前 Schema + * @throws \InvalidArgumentException 当前 Schema 标识符不合法 * * @return string 当前有效的 Schema 名称 */ public function getKingbaseSchema(): string { - if ('' === $this->kingbaseResolvedSchema) { - $this->initConnect(true); - } - - if ('' === $this->kingbaseResolvedSchema) { - throw new \UnexpectedValueException('Unable to resolve the current KES schema'); - } - - return $this->kingbaseResolvedSchema; + $this->initConnect($this->readMaster); + return $this->validateKingbaseIdentifier( + (string) $this->linkID->query('SELECT current_schema()')->fetchColumn(), + 'current schema' + ); } /** @@ -213,9 +142,9 @@ abstract protected function getExpectedKingbaseMode(): string; * 将 KingbaseES 特殊字段映射为正确的 PDO 参数绑定类型。 * * 数组、范围、INTERVAL 和几何类型使用文本形式传输,避免其类型名中的 int - * 被通用规则误判为整数;blob、binary、bytea、raw 和 image 类型标记为 - * kingbase_lob,以便包含 NUL 字节的数据通过 PDO::PARAM_LOB 安全写入。 - * 其他类型沿用父连接器映射。 + * 被通用规则误判为整数;仅 MySQL 模式的二进制字段自动使用 + * PDO::PARAM_LOB。Oracle、SQL Server 模式沿用原连接器的二进制字段 + * 类型映射;业务显式指定的 PDO 绑定类型不受影响。 * * @param string $type 数据库返回的原始字段类型 * @@ -233,9 +162,9 @@ protected function getFieldType(string $type): string return 'string'; } - // KES reports MySQL unsigned integers as uint2/uint4/uint8. Always - // bind them as strings so uint8 values above PHP_INT_MAX are not - // truncated before PDO_KDB sends them to the server. + // 金仓将 MySQL 无符号整数报告为 uint2/uint4/uint8,统一按字符串绑定, + // 避免超出 PHP_INT_MAX 的 uint8 值在 PDO_KDB 发送到服务端之前, + // 因 PHP 整数转换而被截断。 if (1 === preg_match('/^uint\d+$/i', $normalizedType)) { return 'bigint'; } @@ -245,7 +174,8 @@ protected function getFieldType(string $type): string return 'kingbase_bit_string'; } - if (1 === preg_match('/blob|binary|bytea|\braw\b|\bimage\b/i', $type)) { + if ('mysql' === $this->getExpectedKingbaseMode() + && 1 === preg_match('/blob|binary|bytea|\braw\b|\bimage\b/i', $type)) { return 'kingbase_lob'; } @@ -268,58 +198,20 @@ public function getFieldBindType(string $type): int }; } - /** - * 只在当前 INSERT 已确认会生成数据库主键时执行回读,并缓存有效结果。 - * - * @param callable $resolver 实际生成主键查询 - * @param mixed $empty 不应读取或无法取得时的返回值 - * - * @return mixed 当前 INSERT 的生成主键或空值 - */ - protected function resolveKingbaseGeneratedKey(callable $resolver, mixed $empty = ''): mixed - { - if (!$this->kingbaseGeneratedKeyExpected) { - return $empty; - } - - if ($this->kingbaseGeneratedKeyCached) { - return $this->kingbaseGeneratedKey; - } - - $value = $resolver(); - if (null === $value || false === $value || '' === $value) { - return $empty; - } - - $this->kingbaseGeneratedKey = $value; - $this->kingbaseGeneratedKeyCached = true; - - return $value; - } - - /** - * 返回当前 Oracle INSERT 经验证实际使用的序列。 - */ - protected function getKingbaseInsertSequence(): ?string - { - return $this->kingbaseInsertSequence; - } - /** * 初始化并校验一个物理 PDO_KDB 连接。 * - * 每个 PDO 对象仅初始化一次;依次确认驱动名、服务器兼容模式,设置 search_path, - * 并验证同一连接器创建的不同物理连接使用相同 Schema。 + * 每个 PDO 对象仅检查一次;确认驱动名、服务器兼容模式并读取默认 Schema。 + * 不主动设置 search_path,不要求不同物理连接的默认 Schema 相同。 * - * @param PDO $pdo 待初始化的物理连接 - * @param array $config 合并后的数据库连接配置 + * @param PDO $pdo 待初始化的物理连接 * - * @throws \UnexpectedValueException 驱动、兼容模式或实际 Schema 不符合预期 + * @throws \UnexpectedValueException 驱动或兼容模式不符合预期 * @throws \InvalidArgumentException Schema 标识符不合法 * * @return void */ - protected function initializeKingbaseSession(PDO $pdo, array $config): void + protected function initializeKingbaseSession(PDO $pdo): void { $hash = spl_object_hash($pdo); if (isset($this->kingbaseInitializedLinks[$hash])) { @@ -341,160 +233,20 @@ protected function initializeKingbaseSession(PDO $pdo, array $config): void ); } - $configuredSchema = trim((string) ($config['schema'] ?? '')); - if ('' !== $configuredSchema) { - $configuredSchema = $this->validateKingbaseIdentifier($configuredSchema, 'schema'); - $quotedSchema = '"' . str_replace('"', '""', $configuredSchema) . '"'; - $searchPath = 'public' === strtolower($configuredSchema) - ? $quotedSchema - : $quotedSchema . ', public'; - - $pdo->exec('SET search_path TO ' . $searchPath); - } - - $currentSchema = $this->validateKingbaseIdentifier( + // search_path 由数据库控制,不应用旧版 schema 配置。 + $this->validateKingbaseIdentifier( (string) $pdo->query('SELECT current_schema()')->fetchColumn(), 'current schema' ); - if ('' !== $configuredSchema && 0 !== strcasecmp($configuredSchema, $currentSchema)) { - throw new \UnexpectedValueException( - 'KES schema initialization failed: expected ' . $configuredSchema . ', got ' . $currentSchema - ); - } - - if ('' !== $this->kingbaseResolvedSchema - && 0 !== strcasecmp($this->kingbaseResolvedSchema, $currentSchema)) { - throw new \UnexpectedValueException( - 'KES schema mismatch between connections: expected ' - . $this->kingbaseResolvedSchema . ', got ' . $currentSchema - ); - } - - $this->kingbaseResolvedSchema = $currentSchema; $this->kingbaseInitializedLinks[$hash] = true; } - /** - * 为当前 INSERT 解析自增、Identity 或 Oracle Sequence 生成语义。 - */ - protected function prepareKingbaseGeneratedKeyContext(BaseQuery $query): void - { - $this->resetKingbaseGeneratedKeyContext(); - - $options = $query->getOptions(); - $data = is_array($options['data'] ?? null) ? $options['data'] : []; - $sequence = trim((string) ($options['sequence'] ?? '')); - $mode = $this->getExpectedKingbaseMode(); - - if ('oracle' === $mode && '' !== $sequence && $this->dataUsesKingbaseSequence($data, $sequence)) { - $this->kingbaseGeneratedKeyExpected = true; - $this->kingbaseInsertSequence = $sequence; - return; - } - - $autoInc = $query->getAutoInc(); - if (!is_string($autoInc) || '' === $autoInc) { - return; - } - - [$fieldExists, $fieldValue] = $this->findKingbaseDataField($data, $autoInc); - if ($fieldExists && !$this->isKingbaseGeneratedFieldValue($fieldValue)) { - return; - } - - if ('oracle' !== $mode) { - $this->kingbaseGeneratedKeyExpected = true; - return; - } - - $fields = $this->getFields((string) $query->getTable()); - $metadataSequence = trim((string) ($fields[$autoInc]['sequence'] ?? '')); - if ('' === $metadataSequence) { - return; - } - - if ('' !== $sequence - && $this->normalizeKingbaseSequence($sequence) !== $this->normalizeKingbaseSequence($metadataSequence)) { - return; - } - - $this->kingbaseGeneratedKeyExpected = true; - $this->kingbaseInsertSequence = $metadataSequence; - } - - /** - * 清除生成主键上下文;任何新 INSERT 都必须重新证明生成语义。 - */ - protected function resetKingbaseGeneratedKeyContext(): void - { - $this->kingbaseGeneratedKeyExpected = false; - $this->kingbaseGeneratedKey = null; - $this->kingbaseGeneratedKeyCached = false; - $this->kingbaseInsertSequence = null; - } - - /** - * 在大小写不敏感的字段数组中读取指定字段。 - * - * @return array{0:bool,1:mixed} - */ - private function findKingbaseDataField(array $data, string $field): array - { - foreach ($data as $key => $value) { - if (0 === strcasecmp((string) $key, $field)) { - return [true, $value]; - } - } - - return [false, null]; - } - - /** - * NULL 或 DEFAULT 表达式仍可触发自增/Identity 默认值。 - */ - private function isKingbaseGeneratedFieldValue(mixed $value): bool - { - if (null === $value) { - return true; - } - - return $value instanceof Raw && 'DEFAULT' === strtoupper(trim($value->getValue())); - } - - /** - * 判断 INSERT 数据中是否确实使用指定 Oracle 序列的 NEXTVAL。 - */ - private function dataUsesKingbaseSequence(array $data, string $sequence): bool - { - $expected = $this->normalizeKingbaseSequence($sequence) . '.NEXTVAL'; - - foreach ($data as $value) { - if (!$value instanceof Raw) { - continue; - } - $expression = strtoupper((string) preg_replace('/[\s`"\[\]]+/', '', $value->getValue())); - if (str_contains($expression, $expected)) { - return true; - } - } - - return false; - } - - /** - * 规范化序列限定名,供显式配置与元数据结果比较。 - */ - private function normalizeKingbaseSequence(string $sequence): string - { - return strtoupper((string) preg_replace('/[\s`"\[\]]+/', '', trim($sequence))); - } - /** * 校验不带限定符的 KingbaseES 数据库对象标识符。 * * 只允许字母或下划线开头,后续可包含字母、数字、下划线、美元符号和井号, - * 防止配置值直接拼入 SET search_path 等 SQL 时产生歧义或注入风险。 + * 确保会话返回的名称可供后续元数据读取使用。 * * @param string $value 待校验的标识符 * @param string $label 错误信息中使用的对象说明 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 index 4251e662..e493b309 100644 --- a/src/db/connector/Kingbase.php +++ b/src/db/connector/Kingbase.php @@ -47,7 +47,6 @@ public function __construct(array $config = []) /** * 返回自动探测后使用的模式专用连接器。 * - * 该方法主要用于诊断和测试;业务查询仍通过统一入口调用。 */ public function getResolvedConnector(): ConnectionInterface { @@ -77,31 +76,31 @@ private function resolveConnectorClass(string $mode): string }; } - /** {@inheritdoc} */ + /** {@inheritdoc} 将查询类名获取请求转交模式专用连接器。 */ public function getQueryClass(): string { return $this->connector->getQueryClass(); } - /** {@inheritdoc} */ - public function connect(array $config = [], $linkNum = 0) + /** {@inheritdoc} 将连接建立请求转交模式专用连接器。 */ + public function connect(array $config = [], $linkNum = 0, $autoConnection = false) { - return $this->connector->connect($config, $linkNum); + return $this->connector->connect($config, $linkNum, $autoConnection); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将数据库管理器设置转交模式专用连接器。 */ public function setDb(DbManager $db) { $this->connector->setDb($db); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将缓存对象设置转交模式专用连接器。 */ public function setCache(CacheInterface $cache) { $this->connector->setCache($cache); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将连接配置读取请求转交模式专用连接器。 */ public function getConfig(string $config = '') { return $this->connector->getConfig($config); @@ -119,91 +118,91 @@ public function close() return $this; } - /** {@inheritdoc} */ + /** {@inheritdoc} 将单条记录查询转交模式专用连接器。 */ public function find(BaseQuery $query): array { return $this->connector->find($query); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将多条记录查询转交模式专用连接器。 */ public function select(BaseQuery $query): array { return $this->connector->select($query); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将单条数据插入转交模式专用连接器。 */ public function insert(BaseQuery $query, bool $getLastInsID = false) { return $this->connector->insert($query, $getLastInsID); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将批量数据插入转交模式专用连接器。 */ public function insertAll(BaseQuery $query, array $dataSet = []): int { return $this->connector->insertAll($query, $dataSet); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将数据更新转交模式专用连接器。 */ public function update(BaseQuery $query): int { return $this->connector->update($query); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将数据删除转交模式专用连接器。 */ public function delete(BaseQuery $query): int { return $this->connector->delete($query); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将单个字段值查询转交模式专用连接器。 */ public function value(BaseQuery $query, string $field, $default = null) { return $this->connector->value($query, $field, $default); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将指定列数据查询转交模式专用连接器。 */ public function column(BaseQuery $query, string|array $column, string $key = ''): array { return $this->connector->column($query, $column, $key); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将闭包事务处理转交模式专用连接器。 */ public function transaction(callable $callback) { return $this->connector->transaction($callback); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将事务开始操作转交模式专用连接器。 */ public function startTrans() { return $this->connector->startTrans(); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将事务提交操作转交模式专用连接器。 */ public function commit() { return $this->connector->commit(); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将事务回滚操作转交模式专用连接器。 */ public function rollback() { return $this->connector->rollback(); } - /** {@inheritdoc} */ - public function getTableFields(string $tableName): array + /** {@inheritdoc} 保留原连接器接受的表名及数组别名形式。 */ + public function getTableFields($tableName): array { return $this->connector->getTableFields($tableName); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将最近执行的 SQL 读取请求转交模式专用连接器。 */ public function getLastSql(): string { return $this->connector->getLastSql(); } - /** {@inheritdoc} */ + /** {@inheritdoc} 将新增主键值读取请求转交模式专用连接器。 */ public function getLastInsID(BaseQuery $query, ?string $sequence = null) { return $this->connector->getLastInsID($query, $sequence); 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 index 562d9ce9..e3853805 100644 --- a/src/db/connector/KingbaseModeDetector.php +++ b/src/db/connector/KingbaseModeDetector.php @@ -59,9 +59,16 @@ public static function detect(array $config): string ); } - $mode = self::normalizeMode((string) $pdo - ->query("SELECT current_setting('database_mode', true)") - ->fetchColumn()); + $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'] ?? '')); @@ -71,9 +78,11 @@ public static function detect(array $config): string self::sanitizeDiagnostic((string) ($probeConfig['hostport'] ?? ''), ''), self::sanitizeDiagnostic((string) ($probeConfig['database'] ?? ''), '') ); - $code = is_numeric($exception->getCode()) ? (int) $exception->getCode() : 0; - - throw new \PDOException('KES mode detection failed (' . $details . '): ' . $message, $code, $exception); + throw KingbaseConnectionDiagnostics::exception( + 'KES mode detection failed (' . $details . '): ' . $message, + $exception, + (string) ($probeConfig['password'] ?? '') + ); } if ('' === $mode) { @@ -147,13 +156,13 @@ private static function normalizeMode(string $mode): string */ private static function firstEndpoint(array $config): array { - foreach (['hostname', 'hostport', 'database', 'username', 'password', 'dsn'] as $key) { + 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 (is_string($config[$key]) && str_contains($config[$key], ',')) { + } elseif (!empty($config['deploy']) && is_string($config[$key]) && str_contains($config[$key], ',')) { $config[$key] = explode(',', $config[$key], 2)[0]; } } diff --git a/src/db/connector/KingbaseMysql.php b/src/db/connector/KingbaseMysql.php index 19df0556..92d6b299 100644 --- a/src/db/connector/KingbaseMysql.php +++ b/src/db/connector/KingbaseMysql.php @@ -12,31 +12,64 @@ namespace think\db\connector; use PDO; +use think\db\BaseQuery; use think\db\concern\KingbaseConnection; /** - * KingbaseES MySQL 兼容模式数据库连接器。 + * KingbaseES MySQL 兼容模式数据库连接器,表名列表继承原 Mysql 查询。 */ class KingbaseMysql extends Mysql { use KingbaseConnection; /** - * 根据 ThinkORM 连接配置生成 PDO_KDB DSN。 + * 将绑定值渲染为 KingbaseES MySQL 模式可执行的 SQL 字面量。 * - * @param array $config 数据库连接配置 + * withCount 等流程会把 fetchSql 生成的子查询嵌入实际 SQL。原 Mysql 的 + * addslashes 转义依赖普通字符串的反斜杠规则,此处显式使用 E 字符串, + * 使转义不受 standard_conforming_strings 开关影响。保留原框架的类型 + * 处理及占位符替换规则,不建立连接,避免改变离线生成和 SQL 日志流程。 * - * @return string kdb: 协议 DSN + * @param string $sql 带参数绑定的 SQL 语句 + * @param array $bind 参数绑定列表 + * + * @return string 渲染后的 SQL */ - protected function parseDsn(array $config): string + public function getRealSql(string $sql, array $bind = []): string { - $dsn = 'kdb:host=' . $config['hostname'] . ';dbname=' . $config['database']; + 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'; + } - if (!empty($config['hostport'])) { - $dsn .= ';port=' . $config['hostport']; + $sql = is_numeric($key) ? + substr_replace($sql, $value, strpos($sql, '?'), 1) : + str_replace( + [':' . $key . ' ', ':' . $key . ',', ':' . $key . ')'], + [$value . ' ', $value . ',', $value . ')'], + $sql . ' ' + ); } - return $dsn; + 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()); } /** @@ -59,7 +92,7 @@ public function getFields(string $tableName): array $schema = trim($schema, '`"'); $tableName = trim($tableName, '`"'); } else { - $schema = $this->getSchemaName(); + $schema = $this->getKingbaseSchema(); } $schemaValue = $this->quoteString($schema); @@ -125,10 +158,9 @@ public function getFields(string $tableName): array 'name' => $field, 'type' => $val['full_type'] ?: $val['type'], 'notnull' => 'NO' === strtoupper((string) $val['is_nullable']), - 'default' => $val['default'], + 'default' => $this->normalizeDefaultValue($val['default']), 'primary' => (bool) $val['primary'], 'autoinc' => '' !== (string) $val['attidentity'] || !empty($val['serial_sequence']), - 'sequence' => $val['serial_sequence'] ?: null, 'comment' => $val['comment'], ]; } @@ -137,58 +169,89 @@ public function getFields(string $tableName): array } /** - * 获取指定 Schema 下的基础表列表。 + * 将目录中的纯常量默认值转换为原 Mysql getFields() 的公开值。 * - * @param string $dbName Schema 名,为空时使用当前连接的 Schema + * 只解析完整字符串、数字和 NULL;函数、运算、未知或可能改变值的类型转换 + * 一律保留表达式原文。此方法不执行默认 SQL,也不经过 PHP int/float,避免 + * 大整数及小数精度丢失。普通 SQL 字符串保留反斜杠,仅 E 字符串解码转义。 * - * @return array 表名列表 + * @param mixed $value information_schema.columns.column_default + * @return mixed 常量值或未改动的默认表达式 */ - public function getTables(string $dbName = ''): array + protected function normalizeDefaultValue($value) { - $schema = $dbName ?: $this->getSchemaName(); - $schemaValue = $this->quoteString($schema); - $sql = <<getPDOStatement($sql); - $result = $pdo->fetchAll(PDO::FETCH_ASSOC); + 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; + } - return array_column($result, 'table_name'); - } + $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 . ')?'; - /** - * 获取最近一次插入产生的自增主键。 - * - * PDO_KDB 当前未实现可靠的 lastInsertId(),因此在同一物理连接上直接 - * 调用 LAST_INSERT_ID() 取得 MySQL 兼容模式生成值。 - * - * @param string|null $sequence 可选序列名,保留父连接器接口兼容性 - * - * @return mixed 自增主键值,无法取得时返回空字符串 - */ - public function getAutoID(?string $sequence = null) - { - return $this->resolveKingbaseGeneratedKey(function () { - $pdo = $this->linkID->query('SELECT LAST_INSERT_ID() AS id'); - $result = $pdo->fetch(PDO::FETCH_ASSOC); + 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 isset($result['id']) ? (string) $result['id'] : ''; - }); + return $value; } - /** - * 获取已配置并经服务器确认的 Schema 名称。 - * - * @return string 当前 Schema 名称 - */ - protected function getSchemaName(): string + /** 解码目录明确标为 E 字符串的转义;不认识的形式保留原表达式。 */ + private function decodeEscapeDefault(string $body): ?string { - return $this->getKingbaseSchema(); + $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; } /** @@ -210,7 +273,7 @@ protected function getExpectedKingbaseMode(): string */ protected function quoteString(string $value): string { - $this->initConnect(true); + $this->initConnect($this->readMaster); return $this->linkID->quote($value); } diff --git a/src/db/connector/KingbaseOracle.php b/src/db/connector/KingbaseOracle.php index 83e590fa..8d0aba22 100644 --- a/src/db/connector/KingbaseOracle.php +++ b/src/db/connector/KingbaseOracle.php @@ -23,150 +23,82 @@ class KingbaseOracle extends Oracle use KingbaseConnection; /** - * Oracle 兼容模式默认 PDO 连接参数。 + * 按实际 Schema 读取 Oracle 兼容模式的字段元数据。 * - * KingbaseES 可通过 enable_upper_colname 将结果集列名转换为大写。ThinkORM - * 应用通常以小写字段名访问数组和模型属性,因此在 PDO 边界统一为小写,避免 - * 数据库参数开关改变 PHP 层字段键。应用显式传入的 params 仍具有更高优先级。 + * KES 的 USER_* 和 ALL_* 视图按对象所有者组织数据;同一所有者可以拥有多个 + * Schema,不能将 OWNER 当作 Schema,也不能仅按表名合并不同 Schema 的列。 + * 字段和主键使用同一物理 Schema/表范围。公开 autoinc 沿用原 Oracle + * 组件的主键标记。 * - * @var array - */ - protected $params = [ - PDO::ATTR_CASE => 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, - ]; - - /** - * 根据 ThinkORM 连接配置生成 PDO_KDB DSN。 + * 字段名保留目录中的原始大小写。目录值与查询结果列名不是同一层面的信息; + * 单表 Model SELECT 由模式 Builder 使用显式同名别名保持两侧一致,避免 + * enable_upper_colname 改变返回键后丢失模型主键。普通 Query 保留服务端行为。 * - * @param array $config 数据库连接配置 + * @param string $tableName 表名,可包含 Schema 和别名 * - * @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; - } - - /** - * 读取 Oracle 兼容模式下的数据表字段元数据。 - * - * 未指定 Owner 时查询 USER_* 视图,指定 Owner 时查询 ALL_* 视图,并将字段、 - * 主键、可空性、默认值和注释转换成 ThinkORM 统一字段结构。自动生成标记单独 - * 从 Identity 和默认序列读取,不再将普通主键视为自增。 - * - * @param string $tableName 表名,可包含 Owner 和别名 - * - * @return array 以小写字段名为键的 ThinkORM 字段元数据 + * @return array 以实际大小写字段名为键的 ThinkORM 字段元数据 */ public function getFields(string $tableName): array { [$tableName] = explode(' ', $tableName); - [$owner, $tableName] = $this->parseOracleTable($tableName); + [$schema, $tableName] = $this->parseOracleTable($tableName); + $schema = $schema ?? $this->getKingbaseSchema(); + $schemaValue = $this->quoteString($schema); + $tableValue = $this->quoteString($tableName); - if (null === $owner) { - $tableValue = $this->quoteString($tableName); - $sql = <<quoteString($owner); - $tableValue = $this->quoteString($tableName); - $sql = <<getPDOStatement($sql); $result = $pdo->fetchAll(PDO::FETCH_ASSOC); $info = []; - $generatedFields = $this->getGeneratedFields($owner ?? $this->getKingbaseSchema(), $tableName); foreach ($result as $val) { $val = array_change_key_case($val); - $field = strtolower($val['field']); + $field = $val['field']; $info[$field] = [ 'name' => $field, 'type' => $val['type'], - 'notnull' => 'N' === strtoupper((string) $val['nullable']), + 'notnull' => 'NO' === strtoupper((string) $val['is_nullable']), 'default' => $val['default'], 'primary' => (bool) $val['primary'], - 'autoinc' => array_key_exists($field, $generatedFields), - 'sequence' => $generatedFields[$field] ?? null, - 'comment' => $val['comment'], + 'autoinc' => (bool) $val['primary'], ]; } @@ -174,153 +106,28 @@ public function getFields(string $tableName): array } /** - * 读取实际由数据库自动生成值的列,区分 Identity、默认序列和普通主键。 - * - * 业务显式写入 seq.NEXTVAL 或设置 sequence() 不改变表定义,因此不在此标记 - * autoinc;显式序列的 CURRVAL 回读仍由 getLastInsID() 负责。 - * - * @param string $owner Schema 名称 - * @param string $tableName Oracle 表名 - * @return array 以小写字段名为键、序列名为值的自动生成列集合 - */ - protected function getGeneratedFields(string $owner, string $tableName): array - { - $ownerValue = $this->quoteString($owner); - $tableValue = $this->quoteString($tableName); - $sql = 'SELECT column_name, is_identity, column_default FROM information_schema.columns' - . ' WHERE lower(table_schema) = lower(' . $ownerValue . ')' - . ' AND lower(table_name) = lower(' . $tableValue . ')'; - $rows = $this->getPDOStatement($sql)->fetchAll(PDO::FETCH_ASSOC); - $fields = []; - foreach ($rows as $row) { - $row = array_change_key_case($row); - $default = (string) ($row['column_default'] ?? ''); - $sequence = $this->extractSequenceFromDefault($default); - if ('YES' === strtoupper((string) $row['is_identity']) || null !== $sequence) { - $fields[strtolower($row['column_name'])] = $sequence; - } - } - return $fields; - } - - /** - * 获取当前用户或指定 Owner 下的业务表列表。 - * - * 查询时过滤 KingbaseES Oracle 兼容模式中的内部辅助表,避免其被 ORM 当作 - * 应用数据表使用。 + * 沿用原 Oracle 序列读取流程,仅对齐 PDO_OCI 的字符串返回类型。 * - * @param string $dbName Owner 名,为空时查询当前用户表 - * - * @return array 表名列表 - */ - public function getTables(string $dbName = ''): array - { - if ('' === $dbName) { - $sql = <<quoteString($this->normalizeOracleName($dbName)); - $sql = <<getPDOStatement($sql); - $result = $pdo->fetchAll(PDO::FETCH_ASSOC); - - return array_map('current', $result); - } - - /** - * 通过 Oracle 兼容序列获取最近一次插入主键。 - * - * 序列名为空时 Oracle 模式无法推断主键,返回框架约定的空字符串;否则在当前物理连接上 - * 查询序列 CURRVAL,确保取得本会话刚使用的值。 + * 序列选项、查询语句及异常处理均交给父连接器;不额外推断或改写序列名。 * * @param BaseQuery $query 当前查询对象,保留 ThinkORM 接口一致性 - * @param string|null $sequence 序列名,可包含 Owner + * @param string|null $sequence 显式指定的序列名,可包含 Owner * - * @return mixed 序列当前值;未提供序列名时返回空字符串 + * @return string|false|null 序列当前值,空结果沿用父连接器返回值 */ public function getLastInsID(BaseQuery $query, ?string $sequence = null) { - $sequence = $this->getKingbaseInsertSequence(); - if (null === $sequence || '' === $sequence) { - return ''; - } - - return $this->resolveKingbaseGeneratedKey(function () use ($sequence) { - $sequence = $this->parseSequenceName($sequence); - $pdo = $this->linkID->query("SELECT {$sequence}.CURRVAL AS id FROM dual"); - - return $pdo->fetchColumn(); - }); - } - - /** - * 从 Oracle NEXTVAL 或 PostgreSQL 风格 nextval() 默认值中提取真实序列名。 - */ - protected function extractSequenceFromDefault(?string $default): ?string - { - if (null === $default || '' === trim($default)) { - return null; - } - - if (preg_match( - '/^\s*((?:"[^"]+"|[A-Za-z_][A-Za-z0-9_$#]*)(?:\.(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_$#]*))?)\s*\.\s*NEXTVAL\b/i', - $default, - $match - )) { - return str_replace('"', '', $match[1]); - } - - if (preg_match('/^\s*nextval\s*\(\s*\'((?:\'\'|[^\'])+)\'\s*(?:::[^)]+)?\s*\)/i', $default, $match)) { - $sequence = str_replace("''", "'", $match[1]); - - return str_replace('"', '', $sequence); - } - - if (preg_match('/^\s*nextval\s*\(\s*"([^"]+)"\s*\)/i', $default, $match)) { - $sequence = $match[1]; + $value = parent::getLastInsID($query, $sequence); - return str_replace('"', '', $sequence); - } - - return null; + return false === $value || null === $value ? $value : (string) $value; } /** - * 拆分并规范化 Oracle 风格的 Owner 限定表名。 + * 拆分并规范化 Oracle 风格的 Schema 限定表名。 * - * @param string $tableName 表名,可使用 owner.table 形式 + * @param string $tableName 表名,可使用 schema.table 形式 * - * @return array{0:string|null,1:string} Owner 与表名;无 Owner 时首项为 null + * @return array{0:string|null,1:string} 实际 Schema 与表名;未限定时首项为 null */ protected function parseOracleTable(string $tableName): array { @@ -367,7 +174,7 @@ protected function normalizeOracleName(string $name): string */ protected function quoteString(string $value): string { - $this->initConnect(true); + $this->initConnect($this->readMaster); return $this->linkID->quote($value); } @@ -381,26 +188,4 @@ protected function getExpectedKingbaseMode(): string { return 'oracle'; } - - /** - * 解析并引用 Oracle 风格序列名。 - * - * 对 Owner 和序列名称分别规范化并使用双引号引用,以支持限定名称及需要保留 - * 大小写的序列对象。 - * - * @param string $sequence 序列名,可使用 owner.sequence 形式 - * - * @return string 可安全拼入 SQL 的序列标识符 - */ - protected function parseSequenceName(string $sequence): string - { - $parts = explode('.', $sequence); - - foreach ($parts as &$part) { - $part = $this->normalizeOracleName($part); - $part = '"' . str_replace('"', '""', $part) . '"'; - } - - return implode('.', $parts); - } } 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 index bbffebb4..48620a0e 100644 --- a/src/db/connector/KingbaseSqlsrv.php +++ b/src/db/connector/KingbaseSqlsrv.php @@ -11,264 +11,15 @@ namespace think\db\connector; -use PDO; use think\db\concern\KingbaseConnection; -use think\model\type\KingbaseDateTime; /** * KingbaseES SQL Server 兼容模式数据库连接器。 + * 表名、字段读取及事务控制继承原 Sqlsrv/PDOConnection。 */ class KingbaseSqlsrv extends Sqlsrv { - use KingbaseConnection { - getFieldType as private getKingbaseFieldType; - } - - /** - * 将SQL Server兼容模式的DATETIME系列映射到KingbaseES日期时间类型。 - * - * PDO_KDB可能返回7位小数秒,ThinkORM原生DateTime只接受最多6位微秒; - * 其他字段类型继续沿用KingbaseES公共绑定和类型映射规则。 - */ - protected function getFieldType(string $type): string - { - if (str_starts_with(strtolower(trim($type)), 'datetime')) { - return KingbaseDateTime::class; - } - - return $this->getKingbaseFieldType($type); - } - - /** - * 根据 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; - } - - /** - * 读取 SQL Server 兼容模式下的数据表字段元数据。 - * - * 分别读取基础列、主键列和 IDENTITY 列后合并为 ThinkORM 统一字段结构, - * 避免不同系统视图之间的兼容差异影响字段识别。 - * - * @param string $tableName 表名,可包含 Schema 和别名 - * - * @return array 以小写字段名为键的 ThinkORM 字段元数据 - */ - public function getFields(string $tableName): array - { - [$tableName] = explode(' ', $tableName); - [$schema, $tableName] = $this->parseSqlsrvTable($tableName); - - $result = $this->getColumnRows($schema, $tableName); - $comments = $this->getColumnComments($schema, $tableName); - $info = []; - - foreach ($result as $val) { - $val = array_change_key_case($val); - $field = strtolower($val['field']); - - $info[$field] = [ - 'name' => $field, - 'type' => $val['type'], - 'notnull' => 'NO' === strtoupper((string) $val['is_nullable']), - 'default' => $val['default'], - 'primary' => false, - 'autoinc' => false, - 'sequence' => null, - 'comment' => $comments[$field] ?? null, - ]; - } - - foreach ($this->getPrimaryFields($schema, $tableName) as $field) { - $field = strtolower($field); - if (isset($info[$field])) { - $info[$field]['primary'] = true; - } - } - - foreach ($this->getIdentityFields($schema, $tableName) as $field) { - $field = strtolower($field); - if (isset($info[$field])) { - $info[$field]['autoinc'] = true; - } - } - - return $this->fieldCase($info); - } - - /** - * 获取指定 Schema 下的业务基础表列表。 - * - * 查询时过滤 KingbaseES SQL Server 兼容模式中的内部辅助表。 - * - * @param string $dbName Schema 名,为空时使用当前连接的 Schema - * - * @return array 表名列表 - */ - public function getTables(string $dbName = ''): array - { - $schema = $dbName ?: $this->getSchemaName(); - $schemaValue = $this->quoteString($schema); - $sql = <<getPDOStatement($sql); - $result = $pdo->fetchAll(PDO::FETCH_ASSOC); - - return array_column($result, 'table_name'); - } - - /** - * 获取最近一次插入产生的 IDENTITY 主键。 - * - * PDO_KDB 的 lastInsertId() 不能作为 SQL Server 兼容模式的可靠结果,因此只在 - * 当前 INSERT 已确认使用 Identity 列时,于同一物理连接上依次查询 - * SCOPE_IDENTITY() 和 @@IDENTITY,防止返回先前 INSERT 遗留的会话值。 - * - * @param string|null $sequence 可选序列名,保留父连接器接口兼容性 - * - * @return mixed IDENTITY 值,无法取得时返回空字符串 - */ - public function getAutoID(?string $sequence = null) - { - return $this->resolveKingbaseGeneratedKey(function () { - foreach (['SELECT SCOPE_IDENTITY() AS id', 'SELECT @@IDENTITY AS id'] as $sql) { - try { - $pdo = $this->linkID->query($sql); - $result = $pdo->fetch(PDO::FETCH_ASSOC); - $id = is_array($result) ? ($result['id'] ?? current($result)) : ''; - - if ('' !== $id && false !== $id && null !== $id) { - return (string) $id; - } - } catch (\Throwable $e) { - // Try the documented fallback on the same physical connection. - } - } - - return ''; - }); - } - - /** - * 使用 SQL Server 兼容语法开启事务。 - * - * 最外层执行 BEGIN TRANSACTION;内层仅增加事务计数,保持原 Sqlsrv - * Connector 不使用保存点的逻辑嵌套语义。 - * - * @return void - */ - public function startTrans(): void - { - $this->initConnect(true); - - if (0 == $this->transTimes) { - $this->linkID->exec('BEGIN TRANSACTION'); - } - - $this->transTimes++; - $this->reConnectTimes = 0; - } - - /** - * 使用 SQL Server 兼容语法提交事务。 - * - * 事务计数回到零时才执行物理 COMMIT,以保持 ThinkORM 嵌套事务行为。 - * - * @return void - */ - public function commit(): void - { - if (0 == $this->transTimes) { - return; - } - $this->initConnect(true); - if (1 == $this->transTimes) { - $this->linkID->exec('COMMIT'); - } - $this->transTimes--; - } - - /** - * 使用 SQL Server 兼容语法回滚事务。 - * - * 最外层执行物理 ROLLBACK;内层仅减少事务计数,不执行局部回滚, - * 保持原 Sqlsrv Connector 的事务行为。 - * - * @return void - */ - public function rollback(): void - { - if (0 == $this->transTimes) { - return; - } - $this->initConnect(true); - if (1 == $this->transTimes) { - $this->linkID->exec('ROLLBACK'); - } - $this->transTimes--; - } - - /** - * 拆分 SQL Server 风格的 Schema 限定表名。 - * - * @param string $tableName 表名,可使用 schema.table 及方括号/引号形式 - * - * @return array{0:string,1:string} Schema 与表名 - */ - protected function parseSqlsrvTable(string $tableName): array - { - $tableName = trim($tableName, '`[]"'); - - if (str_contains($tableName, '.')) { - [$schema, $tableName] = explode('.', $tableName, 2); - - return [ - trim($schema, '`[]"'), - trim($tableName, '`[]"'), - ]; - } - - return [$this->getSchemaName(), $tableName]; - } - - /** - * 获取已配置并经服务器确认的 Schema 名称。 - * - * @return string 当前 Schema 名称 - */ - protected function getSchemaName(): string - { - return $this->getKingbaseSchema(); - } + use KingbaseConnection; /** * 返回本连接器要求的 KingbaseES 兼容模式。 @@ -279,168 +30,4 @@ protected function getExpectedKingbaseMode(): string { return 'sqlserver'; } - - /** - * 从 information_schema 获取指定表的基础列信息。 - * - * @param string $schema Schema 名称 - * @param string $tableName 表名 - * - * @return array 数据库返回的字段记录 - */ - protected function getColumnRows(string $schema, string $tableName): array - { - $schemaValue = $this->quoteString($schema); - $tableValue = $this->quoteString($tableName); - - $sql = <<getPDOStatement($sql); - $result = $pdo->fetchAll(PDO::FETCH_ASSOC); - - return $result; - } - - /** - * 从 KingbaseES 系统目录读取 SQL Server 兼容模式的字段注释。 - * - * 某些服务端版本未暴露该系统目录时返回空集合,基础字段元数据仍可使用;支持 - * 目录的版本则返回 COMMENT ON COLUMN 写入的真实非空注释。 - * - * @return array 以小写字段名为键的注释集合 - */ - protected function getColumnComments(string $schema, string $tableName): array - { - $schemaValue = $this->quoteString($schema); - $tableValue = $this->quoteString($tableName); - $sql = << 0 - AND NOT a.attisdropped -SQL; - - try { - $rows = $this->getPDOStatement($sql)->fetchAll(PDO::FETCH_ASSOC); - } catch (\Throwable $exception) { - return []; - } - - $comments = []; - foreach ($rows as $row) { - $row = array_change_key_case($row); - $comments[strtolower((string) $row['field'])] = $row['comment'] ?? null; - } - - return $comments; - } - - /** - * 获取指定表按约束顺序排列的主键字段名。 - * - * @param string $schema Schema 名称 - * @param string $tableName 表名 - * - * @return array 主键字段名列表 - */ - protected function getPrimaryFields(string $schema, string $tableName): array - { - $schemaValue = $this->quoteString($schema); - $tableValue = $this->quoteString($tableName); - $sql = <<getPDOStatement($sql); - $result = $pdo->fetchAll(PDO::FETCH_ASSOC); - - return array_map('current', $result); - } - - /** - * 获取指定表的 IDENTITY 自增字段名。 - * - * @param string $schema Schema 名称 - * @param string $tableName 表名 - * - * @return array IDENTITY 字段名列表 - */ - protected function getIdentityFields(string $schema, string $tableName): array - { - $objectName = $schema . '.' . $tableName; - $objectValue = $this->quoteString($objectName); - $sql = <<getPDOStatement($sql); - $result = $pdo->fetchAll(PDO::FETCH_ASSOC); - - return array_map('current', $result); - } - - /** - * 使用当前 PDO_KDB 连接转义元数据查询中的字符串字面量。 - * - * @param string $value 待转义字符串 - * - * @return string 包含引号的安全 SQL 字面量 - */ - protected function quoteString(string $value): string - { - $this->initConnect(true); - - return $this->linkID->quote($value); - } - - /** - * 禁用父 SQL Server 连接器的会话时区设置 SQL。 - * - * KingbaseES SQL Server 兼容模式未提供父实现依赖的完整时区设置语义,因此返回 - * 空 SQL,日期时间表达式由数据库当前会话处理。 - * - * @param string $timezone ThinkORM 配置的时区 - * - * @return string 固定返回空字符串 - */ - protected function getSetTimezoneSql(string $timezone): string - { - return ''; - } } diff --git a/src/model/type/KingbaseDateTime.php b/src/model/type/KingbaseDateTime.php deleted file mode 100644 index 05357d78..00000000 --- a/src/model/type/KingbaseDateTime.php +++ /dev/null @@ -1,39 +0,0 @@ - Date: Thu, 19 Nov 2026 15:32:03 +0800 Subject: [PATCH 6/6] =?UTF-8?q?=E5=8A=9F=E8=83=BD=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 29 +++++++++++- src/db/builder/KingbaseMysql.php | 72 +++++++++++++++++++++++++++++ src/db/builder/KingbaseOracle.php | 35 -------------- src/db/connector/KingbaseMysql.php | 44 ++++++++++++++++++ src/db/connector/KingbaseOracle.php | 7 ++- 5 files changed, 147 insertions(+), 40 deletions(-) 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 index f9ba8c3f..c8c277d1 100644 --- a/src/db/builder/KingbaseMysql.php +++ b/src/db/builder/KingbaseMysql.php @@ -20,6 +20,78 @@ */ class KingbaseMysql extends Mysql { + /** + * 为等值内连接的主表投影补充分组主键。 + * + * 多态关联会按关联外键分组并返回主表全部字段。只有结构及物理目录能证明 + * 每个原分组只对应一个真实主键时,才保留原分组并补充该主键;不改查询状态、 + * HAVING、绑定值或软删除条件。离线SQL生成、分布式连接及未验证的复杂结构 + * 沿用原流程,避免使用另一物理连接的目录属性作为证明。 + */ + protected function parseGroup(Query $query, string|array $group): string + { + $options = $query->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; + } + /** * 生成写入参数占位符,适配整数列的布尔绑定。 * diff --git a/src/db/builder/KingbaseOracle.php b/src/db/builder/KingbaseOracle.php index f2bd141c..f38db278 100644 --- a/src/db/builder/KingbaseOracle.php +++ b/src/db/builder/KingbaseOracle.php @@ -19,41 +19,6 @@ */ class KingbaseOracle extends Oracle { - /** - * 单表 Model 查询显式保留字段名,避免 enable_upper_colname 改变模型主键。 - * - * 元数据中的字段名是目录值,不受 PDO 的列名大小写策略控制。为模型字段增加 - * 同名双引号别名,使返回数据仍使用元数据名称;普通 Query、关联查询、表达式 - * 和用户显式设置的别名继续使用原 Builder 行为,不统一转换结果键。 - */ - protected function parseField(Query $query, array $fields): string - { - $table = $query->getTable(); - if (!$query->getModel() || $query->getOption('join') || !is_string($table) - || false !== strpbrk($table, ',()')) { - return parent::parseField($query, $fields); - } - - $names = $query->getTableFields(); - if (!$names) { - return parent::parseField($query, $fields); - } - if (!$fields || ['*'] === $fields) { - $fields = $names; - } - - $parts = []; - foreach ($fields as $key => $field) { - if (is_int($key) && is_string($field) && in_array($field, $names, true)) { - $parts[] = $this->parseKey($query, $field) . ' AS "' . str_replace('"', '""', $field) . '"'; - } else { - $parts[] = parent::parseField($query, [$key => $field]); - } - } - - return implode(',', $parts); - } - /** * 使用 VALUES 语法构造多行 INSERT。 * diff --git a/src/db/connector/KingbaseMysql.php b/src/db/connector/KingbaseMysql.php index 92d6b299..e8ba1629 100644 --- a/src/db/connector/KingbaseMysql.php +++ b/src/db/connector/KingbaseMysql.php @@ -22,6 +22,50 @@ class KingbaseMysql extends Mysql { use KingbaseConnection; + /** + * 证明等值内连接可以在原分组外键后补充主表主键。 + * + * 仅接受无继承、无分区的普通表,以及真实有效、不可延迟的单列整数主键; + * 关联列必须为相同物理整数类型且非空。表名按实际查询连接的搜索路径解析。 + * 不扩充公开字段结构,也不缓存证明结果,以免同名表重建后沿用旧属性。 + * + * @internal 由金仓MySQL构造器在结构检查通过后调用 + */ + public function canSupplementGroupByPrimaryKey(string $table, string $primaryKey, string $joinedTable, string $foreignKey): bool + { + $sql = <<<'SQL' +SELECT 1 +FROM pg_catalog.pg_class p +JOIN pg_catalog.pg_attribute a ON a.attrelid = p.oid AND a.attname = :pk +JOIN pg_catalog.pg_constraint c ON c.conrelid = p.oid AND c.contype = 'p' +JOIN pg_catalog.pg_index i ON i.indexrelid = c.conindid +JOIN pg_catalog.pg_class f ON f.oid = pg_catalog.to_regclass(:joined_table) +JOIN pg_catalog.pg_attribute b ON b.attrelid = f.oid AND b.attname = :fk +WHERE p.oid = pg_catalog.to_regclass(:main_table) + AND p.relkind = 'r' AND f.relkind = 'r' + AND NOT c.condeferrable AND c.convalidated + AND pg_catalog.array_length(c.conkey, 1) = 1 AND c.conkey[1] = a.attnum + AND i.indisvalid AND i.indisready AND i.indimmediate + AND a.attnum > 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 字面量。 * diff --git a/src/db/connector/KingbaseOracle.php b/src/db/connector/KingbaseOracle.php index 8d0aba22..b070b20b 100644 --- a/src/db/connector/KingbaseOracle.php +++ b/src/db/connector/KingbaseOracle.php @@ -30,13 +30,12 @@ class KingbaseOracle extends Oracle * 字段和主键使用同一物理 Schema/表范围。公开 autoinc 沿用原 Oracle * 组件的主键标记。 * - * 字段名保留目录中的原始大小写。目录值与查询结果列名不是同一层面的信息; - * 单表 Model SELECT 由模式 Builder 使用显式同名别名保持两侧一致,避免 - * enable_upper_colname 改变返回键后丢失模型主键。普通 Query 保留服务端行为。 + * 字段的 name 值保留目录中的原始名称;元数据数组的外层字段键沿用原 + * fieldCase(),按 PDO::ATTR_CASE 配置处理。连接配置要求见 README 使用注意事项。 * * @param string $tableName 表名,可包含 Schema 和别名 * - * @return array 以实际大小写字段名为键的 ThinkORM 字段元数据 + * @return array 外层字段键遵循 PDO::ATTR_CASE 的 ThinkORM 字段元数据 */ public function getFields(string $tableName): array {