diff --git a/Document-Chinese.md b/Document-Chinese.md
index c88f0d98..4b02859c 100644
--- a/Document-Chinese.md
+++ b/Document-Chinese.md
@@ -397,6 +397,14 @@ DELETE:
删除数据 | base_url/delete/ | {
TableName:{<
###
3.2 功能符
+
+#### KingbaseES 接入与迁移
+
+- 使用 MySQL、Oracle 或 SQL Server 兼容模式时,将 `@database` 或后端 `DEFAULT_DATABASE` 配置为 `KINGBASE_AUTO`,并由应用提供运行时 Kingbase JDBC 驱动。APIJSON 使用 `SHOW database_mode` 识别模式,并缓存数据源的识别结果。
+- 从 `KINGBASE_MYSQL`、`KINGBASE_ORACLE` 或 `KINGBASE_SQLSERVER` 直接配置迁移时,请改为 `KINGBASE_AUTO`。这三个标识仍可用于后端 `gainKingbaseExpectedDatabase()` 的期望模式校验,但不再作为直接配置值。原有 `KINGBASE` 入口保留旧行为,不自动探测模式。
+- 自管数据源可覆盖 `openKingbaseModeConnection()`,返回可由探测器关闭的连接。探测连接和缓存键不能依赖已解析的 SQL 方言;如果同一数据源切换目标实例,请使用 `KINGBASE_MODE_RESOLVER.invalidate(config)` 清除旧的模式缓存。
+
+默认 Maven 测试不需要 Kingbase 驱动。要单独验证 JDBC 驱动合约,可运行 `mvn -Pkingbase-driver-tests -Dtest=KingbaseTypeMappingTest test`,按需要通过 `-Dkingbase.jdbc.version` 指定可从 Maven 仓库获取的驱动版本。这不等同于实库测试。
功能 | 键值对格式 | 使用示例
------------ | ------------ | ------------
diff --git a/pom.xml b/pom.xml
index 25aab26f..99df66c5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -18,6 +18,7 @@
UTF-8
1.8
1.8
+ 9.0.0
@@ -29,6 +30,21 @@
+
+
+
+ kingbase-driver-tests
+
+
+ cn.com.kingbase
+ kingbase8
+ ${kingbase.jdbc.version}
+ test
+
+
+
+
+
diff --git a/src/main/java/apijson/orm/AbstractFunctionParser.java b/src/main/java/apijson/orm/AbstractFunctionParser.java
index 6c4e248e..2375e706 100755
--- a/src/main/java/apijson/orm/AbstractFunctionParser.java
+++ b/src/main/java/apijson/orm/AbstractFunctionParser.java
@@ -884,6 +884,21 @@ public String toFunctionCallString(boolean useValue, String quote) {
return s + ")";
}
+ /** Encode the arguments of a text CALL before Kingbase Oracle prepares it. */
+ String toKingbaseOracleCallString() {
+ StringBuilder call = new StringBuilder(getMethod()).append('(');
+ Object[] args = getValues();
+ if (args != null) {
+ for (int i = 0; i < args.length; i++) {
+ if (i > 0) call.append(',');
+ Object arg = args[i];
+ if (arg instanceof Boolean || arg instanceof Number) call.append(arg);
+ else call.append("E'").append(String.valueOf(arg).replace("\\", "\\\\").replace("'", "''")).append('\'');
+ }
+ }
+ return call.append(')').toString();
+ }
+
}
/**
diff --git a/src/main/java/apijson/orm/AbstractObjectParser.java b/src/main/java/apijson/orm/AbstractObjectParser.java
index 79ed5738..af2a99e2 100755
--- a/src/main/java/apijson/orm/AbstractObjectParser.java
+++ b/src/main/java/apijson/orm/AbstractObjectParser.java
@@ -1112,7 +1112,7 @@ public void parseFunction(String rawKey, String key, String value, String parent
if (StringUtil.isNotEmpty(sch, true)) {
config.setSchema(sch);
}
- config.setProcedure(fb.toFunctionCallString(true));
+ config.setProcedure(config.isKingBaseOracle() ? fb.toKingbaseOracleCallString() : fb.toFunctionCallString(true));
result = parseResponse(config, true);
key = key.substring(1);
diff --git a/src/main/java/apijson/orm/AbstractParser.java b/src/main/java/apijson/orm/AbstractParser.java
index 159536fd..f0505537 100755
--- a/src/main/java/apijson/orm/AbstractParser.java
+++ b/src/main/java/apijson/orm/AbstractParser.java
@@ -683,18 +683,33 @@ public void onVerifyRole(@NotNull SQLConfig config) throws Exception {
}
if (isNeedVerifyRole()) {
- if (config.getRole() == null) {
- if (globalRole != null) {
- config.setRole(globalRole);
- } else {
- config.setRole(getVisitor().getId() == null ? AbstractVerifier.UNKNOWN : AbstractVerifier.LOGIN);
+ verifyConfigRole(config);
+ List jl = config.getJoinList();
+ if (jl != null) {
+ // Verify the joined rows before SQL generation and before caching any child results.
+ for (Join join : jl) {
+ SQLConfig child = join.getJoinConfig();
+ if (child != null) { // && child.isKingBaseSQLServer() {
+ verifyConfigRole(child);
+ }
+
+ SQLConfig cache = join.getCacheConfig();
+ if (cache != null && cache != child) { // && cache.isKingBaseSQLServer() {
+ verifyConfigRole(cache);
+ }
}
}
- getVerifier().verifyAccess(config);
}
}
+ private void verifyConfigRole(SQLConfig config) throws Exception {
+ if (config.getRole() == null) {
+ config.setRole(globalRole != null ? globalRole : (getVisitor().getId() == null ? AbstractVerifier.UNKNOWN : AbstractVerifier.LOGIN));
+ }
+ getVerifier().verifyAccess(config);
+ }
+
@Override
public M parseCorrectRequest(RequestMethod method, String tag, int version, String name, @NotNull M request
@@ -1106,6 +1121,8 @@ public M getStructure(@NotNull String table, String method, String tag, int vers
config.setParser(this);
config.setPrepared(false);
config.setColumn(Arrays.asList("structure"));
+ // Only the three compatibility modes opt into TEXT/CLOB-backed rules.
+ config.setJson(Arrays.asList("structure"));
Map where = new HashMap();
where.put("method", method);
@@ -1126,7 +1143,9 @@ public M getStructure(@NotNull String table, String method, String tag, int vers
// AbstractVerifier.REQUEST_MAP.put(cacheKey, versionedMap);
}
- return JSON.get(result, "structure"); //解决返回值套了一层 "structure":{}
+ // Legacy KINGBASE and native databases keep the original cached-rule contract.
+ Object structure = result == null ? null : result.get("structure");
+ return structure instanceof String ? JSON.parseObject(structure) : (M) structure;
}
@@ -1534,6 +1553,7 @@ else if (childKeys.length == 1 && isTableKey(childKeys[0])) { // 可能无需
JOIN_COPY_KEY_LIST.add(KEY_ORDER);
JOIN_COPY_KEY_LIST.add(KEY_KEY);
JOIN_COPY_KEY_LIST.add(KEY_RAW);
+ JOIN_COPY_KEY_LIST.add(KEY_JSON);
}
/**JOIN 多表同时筛选
@@ -1677,6 +1697,18 @@ else if (join != null){
}
boolean isAppJoin = "@".equals(joinType);
+ // String joinDatabase = getString(tableObj, KEY_DATABASE);
+ // if (joinDatabase == null) {
+ // joinDatabase = getString(request, KEY_DATABASE);
+ // if (joinDatabase == null) {
+ // joinDatabase = getGlobalDatabase();
+ // if (joinDatabase == null) {
+ // joinDatabase = AbstractSQLConfig.DEFAULT_DATABASE;
+ // }
+ // }
+ // }
+
+ // boolean copyJoinJson = SQLConfig.DATABASE_KINGBASE_AUTO.equals(joinDatabase);
M refObj = JSON.createJSONObject();
@@ -1758,7 +1790,7 @@ else if (join != null){
}
if (k.startsWith("@")) {
- if (JOIN_COPY_KEY_LIST.contains(k)) {
+ if (JOIN_COPY_KEY_LIST.contains(k)) { // 直接 JOIN_COPY_KEY_LIST.add(KEY_JSON) || (copyJoinJson && KEY_JSON.equals(k))) {
requestObj.put(k, v); // 保留
}
}
diff --git a/src/main/java/apijson/orm/AbstractSQLConfig.java b/src/main/java/apijson/orm/AbstractSQLConfig.java
index 2c76d091..166f3ec7 100755
--- a/src/main/java/apijson/orm/AbstractSQLConfig.java
+++ b/src/main/java/apijson/orm/AbstractSQLConfig.java
@@ -11,6 +11,7 @@
import apijson.orm.exception.UnsupportedDataTypeException;
import apijson.orm.model.*;
+import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Pattern;
@@ -76,6 +77,16 @@ public abstract class AbstractSQLConfig, L exte
// * 和 / 不能同时出现,防止 /* */ 段注释! # 和 -- 不能出现,防止行注释! ; 不能出现,防止隔断SQL语句!空格不能出现,防止 CRUD,DROP,SHOW TABLES等语句!
public static Pattern PATTERN_RANGE;
public static Pattern PATTERN_FUNCTION;
+ private static final Pattern MYSQL_INTERVAL_LITERAL_PATTERN = Pattern.compile(
+ "(?i)^INTERVAL\\s+([+-]?\\d+|'[+-]?\\d+'|\\?)\\s+"
+ + "(MICROSECOND|SECOND|MINUTE|HOUR|DAY|WEEK|MONTH|QUARTER|YEAR)$"
+ );
+ private static final Pattern MYSQL_TIME_FRACTION_PATTERN = Pattern.compile("\\.([0-9]+)$");
+ private static final Pattern KINGBASE_JSON_LENGTH_FILTER = Pattern.compile(
+ "json_length\\(\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*\\)\\s*(<=|>=|<>|!=|=|<|>)\\s*([0-9]+)");
+ private static final int KINGBASE_MYSQL_IDENTIFIER_BYTES = 63;
+ private static final String KINGBASE_MYSQL_PROJECTION_PREFIX = "$apijson$";
+ static final String KINGBASE_SQLSERVER_JOIN_KEY_PREFIX = "_apijson_join_";
/**
* 表 SCHEMA 映射
@@ -157,9 +168,7 @@ public abstract class AbstractSQLConfig, L exte
DATABASE_LIST.add(DATABASE_COCKROACHDB);
DATABASE_LIST.add(DATABASE_DAMENG);
DATABASE_LIST.add(DATABASE_KINGBASE);
- DATABASE_LIST.add(DATABASE_KINGBASE_MYSQL);
- DATABASE_LIST.add(DATABASE_KINGBASE_ORACLE);
- DATABASE_LIST.add(DATABASE_KINGBASE_SQLSERVER);
+ DATABASE_LIST.add(DATABASE_KINGBASE_AUTO);
DATABASE_LIST.add(DATABASE_ELASTICSEARCH);
DATABASE_LIST.add(DATABASE_MANTICORE);
DATABASE_LIST.add(DATABASE_CLICKHOUSE);
@@ -889,6 +898,22 @@ public static boolean allowPartialUpdateFailed(String table) {
@NotNull
@Override
public String getIdKey() {
+ return isKingBaseCompatibilityMode() ? getMetadataIdKey(getTable()) : KEY_ID;
+ }
+
+ protected static String getMetadataIdKey(String table) {
+ if (Table.TAG.equals(table)) {
+ return "table_name";
+ }
+ if (Column.TAG.equals(table)) {
+ return "ordinal_position";
+ }
+ if (PgClass.TAG.equals(table)) {
+ return "oid";
+ }
+ if (PgAttribute.TAG.equals(table)) {
+ return "attnum";
+ }
return KEY_ID;
}
@NotNull
@@ -933,6 +958,11 @@ public String getUserIdKey() {
private List json; //需要转为 JSON 的字段,','分隔
private Subquery from; //子查询临时表
private List column; //表内字段名(或函数名,仅查询操作可用)的字符串数组,','分隔
+ private Map columnAliasExpressionMap;
+ private Map kingbaseProjectionLabels;
+ private Set kingbaseMySQLLocalDateTimeAliases;
+ private Set kingbaseMySQLSumAliases;
+ private Map kingbaseMySQLHavingOrderAliases;
private List> values; //对应表内字段的值的字符串数组,','分隔
private List nulls;
private Map cast;
@@ -1091,13 +1121,56 @@ public AbstractSQLConfig setDatabase(String database) {
this.database = database;
return this;
}
+ /** Validate a resolved backend/default database against the public configuration allowlist. */
+ public static void validateConfiguredDatabase(String database) {
+ if (! DATABASE_LIST.contains(database)) {
+ throw new IllegalArgumentException("Unsupported database configuration: " + database + "; allowed values: " + DATABASE_LIST);
+ }
+ }
/**
- * @return db == null ? DEFAULT_DATABASE : db
+ * @return the SQL dialect, detecting KINGBASE_AUTO on first use and checking
+ * the optional backend expectation on every resolution
*/
@NotNull
public String gainSQLDatabase() {
- String db = getDatabase();
- return db == null ? DEFAULT_DATABASE : db; // "" 表示已设置,不需要用全局默认的 StringUtil.isEmpty(db, false)) {
+ return resolveSQLDatabase(getDatabase());
+ }
+
+ /** Resolve a configured route, including routes supplied by framework configuration stores. */
+ protected String resolveSQLDatabase(String db) {
+ db = db == null ? DEFAULT_DATABASE : db;
+ if (DATABASE_KINGBASE_AUTO.equals(db) || (KingbaseSQLDialect.from(db).isKingbase() && ! DATABASE_KINGBASE.equals(db))) {
+ validateConfiguredDatabase(db);
+ }
+ if (! KingbaseModeResolver.requiresDetection(db)) {
+ return db;
+ }
+ String actual = KINGBASE_MODE_RESOLVER.resolve(this);
+ // Backend expectations are checked for every caller, including cache hits.
+ return KingbaseModeResolver.requireExpectedMode(actual, gainKingbaseExpectedDatabase());
+ }
+
+ /** Shared successful detections; clear after replacing a data source's target. */
+ public static final KingbaseModeResolver KINGBASE_MODE_RESOLVER = new KingbaseModeResolver();
+
+ /** Optional backend-only assertion. Null accepts any supported detected mode.
+ * Override using deployment configuration, never request-controlled values. */
+ protected String gainKingbaseExpectedDatabase() {
+ return null;
+ }
+
+ /**
+ * Borrow a dedicated detection connection. It is closed (returned to its pool)
+ * by the resolver. Override for application-managed DataSources. This method
+ * and the cache key must not depend on an already resolved SQL dialect.
+ */
+ protected java.sql.Connection openKingbaseModeConnection() throws java.sql.SQLException {
+ return java.sql.DriverManager.getConnection(gainDBUri(), gainDBAccount(), gainDBPassword());
+ }
+
+ /** Override when routing uses additional application context. Never include passwords. */
+ protected Object gainKingbaseModeCacheKey() {
+ return Arrays.asList(getClass(), gainDBUri(), gainDBAccount(), getDatasource(), getNamespace(), getCatalog());
}
@Override
@@ -1190,7 +1263,7 @@ public boolean isKingBase() {
return isKingBase(gainSQLDatabase());
}
public static boolean isKingBase(String db) {
- return KingbaseSQLDialect.from(db).isKingbase();
+ return DATABASE_KINGBASE.equals(db);
}
@Override
@@ -1440,7 +1513,7 @@ public String getQuote() { // MongoDB 同时支持 `tbl` 反引号 和 "col"
return "";
}
KingbaseSQLDialect kingbaseDialect = KingbaseSQLDialect.from(gainSQLDatabase());
- if (kingbaseDialect.isKingbase()) {
+ if (kingbaseDialect.isKingbase() && kingbaseDialect != KingbaseSQLDialect.LEGACY) {
return kingbaseDialect.getIdentifierQuote();
}
return isMySQL() || isMariaDB() || isTiDB() || isClickHouse() || isTDengine() || isMilvus() || isDoris() || isStarRocks() ? "`" : "\"";
@@ -1554,6 +1627,20 @@ public String gainSQLTable() {
// return DATABASE_POSTGRESQL.equals(getDatabase()) ? t.toLowerCase() : t;
String ot = getTable();
String nt = TABLE_KEY_MAP.get(ot);
+ if ((isKingBaseSQLServer() || isKingBaseOracle()) && (StringUtil.isEmpty(nt) || Objects.equals(ot, nt))) {
+ if (Table.class.getSimpleName().equals(ot)) {
+ nt = Table.TABLE_NAME;
+ }
+ else if (Column.class.getSimpleName().equals(ot)) {
+ nt = Column.TABLE_NAME;
+ }
+ else if (PgClass.class.getSimpleName().equals(ot)) {
+ nt = PgClass.TABLE_NAME;
+ }
+ else if (PgAttribute.class.getSimpleName().equals(ot)) {
+ nt = PgAttribute.TABLE_NAME;
+ }
+ }
return StringUtil.isEmpty(nt) ? ot : nt;
}
@@ -1660,9 +1747,11 @@ public String gainGroupString(boolean hasPrefix) {
group = StringUtil.trim(group);
+ String kingbaseMainGroup = gainKingbaseMySQLMainGroupForJoin(joinGroup);
String[] keys = StringUtil.split(group);
if (keys == null || keys.length <= 0) {
- return StringUtil.isEmpty(joinGroup, true) ? "" : (hasPrefix ? " GROUP BY " : "") + joinGroup;
+ String groups = StringUtil.concat(kingbaseMainGroup, joinGroup, ", ", true);
+ return StringUtil.isEmpty(groups, true) ? "" : (hasPrefix ? " GROUP BY " : "") + groups;
}
for (int i = 0; i < keys.length; i++) {
@@ -1676,7 +1765,44 @@ public String gainGroupString(boolean hasPrefix) {
keys[i] = gainKey(keys[i]);
}
- return (hasPrefix ? " GROUP BY " : "") + StringUtil.concat(StringUtil.get(keys), joinGroup, ", ");
+ String groups = StringUtil.concat(StringUtil.get(keys), kingbaseMainGroup, ", ", true);
+ groups = StringUtil.concat(groups, joinGroup, ", ", true);
+ return (hasPrefix ? " GROUP BY " : "") + groups;
+ }
+
+ /**
+ * MySQL can infer that a selected main-table JOIN key is functionally
+ * dependent on the grouped vice-table key. Kingbase MySQL mode follows the
+ * stricter PostgreSQL grouping rule and requires that selected key to appear
+ * explicitly in GROUP BY. Supplement explicit main-table scalar projections
+ * only when grouping comes from a SQL JOIN; native databases and
+ * ordinary non-JOIN grouping remain unchanged.
+ */
+ protected String gainKingbaseMySQLMainGroupForJoin(String joinGroup) {
+ if (isKingBaseMySQL() == false || StringUtil.isNotEmpty(group, true)
+ || StringUtil.isEmpty(joinGroup, true) || column == null || column.isEmpty()) {
+ return "";
+ }
+
+ String selectedGroup = "";
+ int projection = 1;
+ for (String item : column) {
+ String key = StringUtil.trim(item);
+ int alias = KingbaseMySQLExpressions.aliasIndex(key);
+ if (alias >= 0) key = key.substring(0, alias);
+ if (key.matches("[A-Za-z_][A-Za-z0-9_]*")) { // TODO static final PATTERN_KINGBASE_KEYWORD = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*")
+ selectedGroup = StringUtil.concat(selectedGroup, gainKey(key), ", ", true);
+ } else if (key.contains("(") && ! ( KingbaseMySQLExpressions.hasAggregateOrWindow(key, SQL_AGGREGATE_FUNCTION_MAP.keySet())
+ || KingbaseMySQLExpressions.hasVolatileFunction(key) )
+ ) {
+ // A repeated bound expression has different parameter identities ($1/$2)
+ // and is not an equal GROUP BY expression. Reference its validated SELECT
+ // position instead, without duplicating arguments or evaluating it again.
+ selectedGroup = StringUtil.concat(selectedGroup, String.valueOf(projection), ", ", true);
+ }
+ projection += KingbaseMySQLExpressions.projectionSize(item);
+ }
+ return selectedGroup;
}
@Override
@@ -1771,6 +1897,12 @@ protected String gainHavingItem(String quote, String table, String alias
throw new UnsupportedOperationException("@having:value 的 value 中字符串 " + expression + " 不合法!"
+ "不允许传超过 100 个字符的函数或表达式!请用 @raw 简化传参!");
}
+ if (columnAliasExpressionMap != null && (! columnAliasExpressionMap.isEmpty()) && isKingBaseMySQL()) {
+ String comparison = KingbaseHavingExpression.parse(expression, columnAliasExpressionMap.keySet(), quote);
+ if (comparison != null) {
+ return comparison;
+ }
+ }
int start = expression.indexOf("(");
if (start < 0) {
@@ -1805,7 +1937,357 @@ else if (SQL_FUNCTION_MAP.containsKey(method) == false) {
}
}
- return method + parseSQLExpression(KEY_HAVING, expression.substring(start), containRaw, false, null);
+ if (containRaw == false && "json_length".equalsIgnoreCase(method) && isKingBaseSQLServer()) {
+ return parseSQLExpression(KEY_HAVING, expression, false, false, null);
+ }
+ if (containRaw == false && isKingBaseOracle()) {
+ java.util.regex.Matcher length = KINGBASE_JSON_LENGTH_FILTER.matcher(expression);
+ if (length.matches()) {
+ return "jsonb_array_length(CAST(" + gainKingbaseOracleJsonLengthKey(length.group(1)) + " AS jsonb))"
+ + length.group(2) + length.group(3);
+ }
+ }
+
+ // MATCH(...) AGAINST(...) is a two-part full-text expression. Passing only
+ // the substring beginning with '(' drops the MATCH function name, which
+ // prevents database-specific full-text conversion from recognizing it.
+ if ((expression.indexOf(")AGAINST(") > start && isKingBaseCompatibilityMode())
+ || ("length".equalsIgnoreCase(method) && isKingBaseMySQL())) {
+ return parseSQLExpression(KEY_HAVING, expression, containRaw, false, null);
+ }
+ return gainSQLFunction(method) + parseSQLExpression(KEY_HAVING, expression.substring(start), containRaw, false, null);
+ }
+
+ private String gainKingbaseOracleJsonLengthKey(String key) {
+ List raw = getRaw();
+ if (column == null || (! RequestMethod.isGetMethod(getMethod(), false)) || (raw != null && raw.contains(KEY_COLUMN))) {
+ return gainKey(key);
+ }
+
+ // A row filter cannot read a SELECT alias. Resolve a direct projection
+ // before a physical column with the same name can shadow the alias.
+ String source = null;
+ for (String expression : column) {
+ String[] projections = expression.indexOf('(') < 0 ? StringUtil.split(expression) : new String[] {expression};
+ if (projections == null) {
+ continue;
+ }
+
+ for (String projection : projections) {
+ int index = KingbaseMySQLExpressions.aliasIndex(projection);
+ if (index <= 0 || ! key.equals(projection.substring(index + 1))) {
+ continue;
+ }
+
+ String name = projection.substring(0, index);
+ if ((! StringUtil.isName(name)) || RAW_MAP.containsKey(name) || (source != null && ! source.equals(name))) {
+ throw new UnsupportedOperationException("Kingbase Oracle json_length HAVING alias must refer to a single column: " + key);
+ }
+
+ source = name;
+ }
+ }
+
+ return source == null ? gainKey(key) : gainSQLKey(source);
+ }
+
+ /**
+ * Converts a request-level SQL function name to the function exposed by the
+ * selected database dialect. JSON_LENGTH deliberately retains its full MySQL
+ * contract (objects, scalars and optional paths), supplied by mysql_json on
+ * Kingbase. JSON_ARRAY_LENGTH is not an equivalent replacement.
+ */
+ protected String gainSQLFunction(String function) {
+ return function;
+ }
+
+ /**
+ * Builds a function expression after its arguments have passed the normal
+ * APIJSON validation and quoting pipeline. With mysql_interval_style=off,
+ * Kingbase needs a quoted interval. Keep DATE_ADD/DATE_SUB themselves: their
+ * DATE, DATETIME and text return rules differ from date +/- interval.
+ */
+ protected String gainSQLFunctionExpression(String function, String[] args, boolean distinct, String suffix) {
+ boolean isKingBaseMySQL = isKingBaseMySQL();
+ List