fix(kingbase): quote MySQL-compatible identifiers

This commit is contained in:
zipg authored and GitHub committed 2026-07-13 18:51:32 +08:00
1 parent 5ceca7fb3e
commit d1cce3ed1e
39 files changed
+373 -23

No files matched your search

@@ -20,6 +20,16 @@ public abstract class AbstractJdbcAgent extends BaseDatabaseAgent {
return connection; return connection;
} }
@Override
public String getIdentifierQuote() {
try {
String quote = requireConnected().getMetaData().getIdentifierQuoteString();
return quote == null || quote.trim().isEmpty() ? "" : quote.trim();
} catch (Exception ignored) {
return "";
}
}
@Override @Override
public final void connect(ConnectParams params) { public final void connect(ConnectParams params) {
uncheckedVoid(() -> { uncheckedVoid(() -> {
@@ -16,6 +16,7 @@ public final class AgentProtocol {
public static final String METHOD_CANCEL_SESSION = "cancel_session"; public static final String METHOD_CANCEL_SESSION = "cancel_session";
public static final String METHOD_TEST_CONNECTION = "test_connection"; public static final String METHOD_TEST_CONNECTION = "test_connection";
public static final String METHOD_VALIDATE_CONNECTION = "validate_connection"; public static final String METHOD_VALIDATE_CONNECTION = "validate_connection";
public static final String METHOD_CONNECTION_INFO = "connection_info";
public static final String METHOD_LIST_DATABASES = "list_databases"; public static final String METHOD_LIST_DATABASES = "list_databases";
public static final String METHOD_LIST_SCHEMAS = "list_schemas"; public static final String METHOD_LIST_SCHEMAS = "list_schemas";
public static final String METHOD_LIST_TABLES = "list_tables"; public static final String METHOD_LIST_TABLES = "list_tables";
@@ -100,6 +101,7 @@ public final class AgentProtocol {
METHOD_CONNECT, METHOD_CONNECT,
METHOD_TEST_CONNECTION, METHOD_TEST_CONNECTION,
METHOD_VALIDATE_CONNECTION, METHOD_VALIDATE_CONNECTION,
METHOD_CONNECTION_INFO,
METHOD_LIST_DATABASES, METHOD_LIST_DATABASES,
METHOD_LIST_SCHEMAS, METHOD_LIST_SCHEMAS,
METHOD_LIST_TABLES, METHOD_LIST_TABLES,
@@ -13,6 +13,10 @@ public interface DatabaseAgent {
boolean testConnection(ConnectParams params); boolean testConnection(ConnectParams params);
default String getIdentifierQuote() {
return "";
}
List<DatabaseInfo> listDatabases(); List<DatabaseInfo> listDatabases();
List<String> listSchemas(); List<String> listSchemas();
@@ -125,6 +125,9 @@ public final class JsonRpcServer {
return Collections.singletonMap("ok", true); return Collections.singletonMap("ok", true);
} }
ensureLiveConnection(method); ensureLiveConnection(method);
if (AgentProtocol.METHOD_CONNECTION_INFO.equals(method)) {
return Collections.singletonMap("identifierQuote", agent.getIdentifierQuote());
}
if (AgentProtocol.METHOD_LIST_DATABASES.equals(method)) { if (AgentProtocol.METHOD_LIST_DATABASES.equals(method)) {
return agent.listDatabases(); return agent.listDatabases();
} }
@@ -28,6 +28,11 @@ public abstract class PostgresLikeAgent extends AbstractJdbcAgent {
return mysqlCompatMode; return mysqlCompatMode;
} }
@Override
public String getIdentifierQuote() {
return mysqlCompatMode ? "`" : super.getIdentifierQuote();
}
@Override @Override
public QueryResult executeQuery(String sql, String schema, ExecuteQueryOptions options) { public QueryResult executeQuery(String sql, String schema, ExecuteQueryOptions options) {
return JdbcExecutor.current().execute( return JdbcExecutor.current().execute(
@@ -39,6 +39,7 @@
"connect", "connect",
"test_connection", "test_connection",
"validate_connection", "validate_connection",
"connection_info",
"list_databases", "list_databases",
"list_schemas", "list_schemas",
"list_tables", "list_tables",
@@ -46,6 +46,7 @@
"cancel_session", "cancel_session",
"test_connection", "test_connection",
"validate_connection", "validate_connection",
"connection_info",
"list_databases", "list_databases",
"list_schemas", "list_schemas",
"list_tables", "list_tables",
@@ -58,12 +58,24 @@ public final class KingbaseAgent extends PostgresLikeAgent {
@Override @Override
protected void afterConnect(ConnectParams params, Connection connection) { protected void afterConnect(ConnectParams params, Connection connection) {
postgresCatalogMode = false; postgresCatalogMode = false;
setMysqlCompatMode(params.isMysql_compat_mode());
if (params.isMysql_compat_mode()) { if (params.isMysql_compat_mode()) {
setMysqlCompatMode(true);
return; return;
} }
postgresCatalogMode = !catalogExists(connection, "sys_catalog.sys_namespace") postgresCatalogMode = !catalogExists(connection, "sys_catalog.sys_namespace")
&& catalogExists(connection, "pg_catalog.pg_namespace"); && catalogExists(connection, "pg_catalog.pg_namespace");
if (!postgresCatalogMode && mysqlSqlModeExists(connection)) {
setMysqlCompatMode(true);
}
}
private static boolean mysqlSqlModeExists(Connection connection) {
try (Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1 FROM sys_settings WHERE LOWER(name) = 'sql_mode'")) {
return rs.next();
} catch (Exception ignored) {
return false;
}
} }
private static boolean catalogExists(Connection connection, String catalog) { private static boolean catalogExists(Connection connection, String catalog) {
@@ -137,6 +137,22 @@ class KingbaseAgentTest extends JdbcFakeExecutionBehaviorTest {
Assertions.assertEquals("SET search_path TO \"app\"", agent.setSchemaSQL("app")); Assertions.assertEquals("SET search_path TO \"app\"", agent.setSchemaSQL("app"));
} }
@Test
void detectsMysqlCompatModeFromServerSqlMode() throws Exception {
List<String> sql = new ArrayList<>();
KingbaseAgent agent = new KingbaseAgent();
Connection connection = mysqlCompatConnection(sql);
Method afterConnect = KingbaseAgent.class.getDeclaredMethod("afterConnect", ConnectParams.class, Connection.class);
afterConnect.setAccessible(true);
afterConnect.invoke(agent, new ConnectParams(), connection);
Assertions.assertTrue(agent.isMysqlCompatMode());
Assertions.assertEquals("`", agent.getIdentifierQuote());
Assertions.assertEquals("SELECT 1 FROM sys_catalog.sys_namespace WHERE 1 = 0", sql.get(0));
Assertions.assertEquals("SELECT 1 FROM sys_settings WHERE LOWER(name) = 'sql_mode'", sql.get(1));
}
@Test @Test
void mysqlCompatListTablesUsesInformationSchema() { void mysqlCompatListTablesUsesInformationSchema() {
List<String> sql = new ArrayList<>(); List<String> sql = new ArrayList<>();
@@ -512,6 +528,26 @@ class KingbaseAgentTest extends JdbcFakeExecutionBehaviorTest {
}); });
} }
private static Connection mysqlCompatConnection(List<String> sql) {
return proxy(Connection.class, (method, args) -> {
if ("createStatement".equals(method.getName())) {
return proxy(Statement.class, (statementMethod, statementArgs) -> {
if ("executeQuery".equals(statementMethod.getName())) {
String query = String.valueOf(statementArgs[0]);
sql.add(query);
if (query.contains("sys_settings")) {
return resultSet(new String[]{"probe"}, new Object[][]{{1}});
}
return resultSet(new String[]{"probe"}, new Object[][]{});
}
return defaultValue(statementMethod.getReturnType());
});
}
if ("isClosed".equals(method.getName())) return false;
return defaultValue(method.getReturnType());
});
}
private static ResultSet resultSet(String[] columns, Object[][] rows) { private static ResultSet resultSet(String[] columns, Object[][] rows) {
int[] index = {-1}; int[] index = {-1};
return proxy(ResultSet.class, (method, args) -> { return proxy(ResultSet.class, (method, args) -> {
@@ -89,7 +89,7 @@ import { formatElapsedSeconds } from "@/lib/common/elapsedTime";
import { dataGridCellDisplayText, dataGridCellEditorText } from "@/lib/dataGrid/dataGridCellCoercion"; import { dataGridCellDisplayText, dataGridCellEditorText } from "@/lib/dataGrid/dataGridCellCoercion";
import { createColumnDrafts } from "@/lib/table/tableStructureEditorState"; import { createColumnDrafts } from "@/lib/table/tableStructureEditorState";
import type { BuildSingleColumnAlterSqlOptions } from "@/lib/table/tableStructureEditorSql"; import type { BuildSingleColumnAlterSqlOptions } from "@/lib/table/tableStructureEditorSql";
import { buildTableSelectSql, quoteTableIdentifier } from "@/lib/table/tableSelectSql"; import { buildTableSelectSql, quoteTableDataIdentifier } from "@/lib/table/tableSelectSql";
import { uuid } from "@/lib/common/utils"; import { uuid } from "@/lib/common/utils";
import { compactHeaderColumnType, resolveHeaderColumnType } from "@/lib/dataGrid/dataGridColumnType"; import { compactHeaderColumnType, resolveHeaderColumnType } from "@/lib/dataGrid/dataGridColumnType";
import { import {
@@ -3958,6 +3958,7 @@ async function buildCurrentCountTarget(): Promise<{ sql: string; schema?: string
if (props.tableMeta) { if (props.tableMeta) {
const sql = await buildDataGridCountSql({ const sql = await buildDataGridCountSql({
databaseType: props.databaseType, databaseType: props.databaseType,
identifierQuote: connectionStore.connectionIdentifierQuote?.(props.connectionId),
catalog: props.tableMeta.catalog, catalog: props.tableMeta.catalog,
schema: props.tableMeta.schema, schema: props.tableMeta.schema,
tableName: props.tableMeta.tableName, tableName: props.tableMeta.tableName,
@@ -5612,6 +5613,7 @@ async function applyOrderBySearch() {
if (!tableMeta) return; if (!tableMeta) return;
const sql = await buildTableSelectSql({ const sql = await buildTableSelectSql({
databaseType: resolvedDatabaseType.value, databaseType: resolvedDatabaseType.value,
identifierQuote: connectionStore.connectionIdentifierQuote?.(props.connectionId),
catalog: tableMeta.catalog, catalog: tableMeta.catalog,
schema: tableMeta.schema, schema: tableMeta.schema,
tableName: tableMeta.tableName, tableName: tableMeta.tableName,
@@ -5644,6 +5646,7 @@ async function applyWhereFilter() {
if (!tableMeta) return; if (!tableMeta) return;
const sql = await buildTableSelectSql({ const sql = await buildTableSelectSql({
databaseType: resolvedDatabaseType.value, databaseType: resolvedDatabaseType.value,
identifierQuote: connectionStore.connectionIdentifierQuote?.(props.connectionId),
catalog: tableMeta.catalog, catalog: tableMeta.catalog,
schema: tableMeta.schema, schema: tableMeta.schema,
tableName: tableMeta.tableName, tableName: tableMeta.tableName,
@@ -5753,7 +5756,7 @@ function columnTypeCacheSignature(): string {
watch(() => [props.result.columns.join("\u0000"), columnFormatterSignatures.value.join("\u0000"), columnTypeCacheSignature()], clearCellFormatCache); watch(() => [props.result.columns.join("\u0000"), columnFormatterSignatures.value.join("\u0000"), columnTypeCacheSignature()], clearCellFormatCache);
function quoteIdent(name: string): string { function quoteIdent(name: string): string {
return quoteTableIdentifier(props.databaseType, name); return quoteTableDataIdentifier(props.databaseType, name, connectionStore.connectionIdentifierQuote?.(props.connectionId));
} }
function queryColumnRef(name: string): string { function queryColumnRef(name: string): string {
@@ -1048,6 +1048,7 @@ async function openNewQuery(row: ObjectBrowserRow) {
tabId, tabId,
await buildTableSelectSql({ await buildTableSelectSql({
databaseType: effectiveDatabaseType.value, databaseType: effectiveDatabaseType.value,
identifierQuote: connectionStore.connectionIdentifierQuote?.(props.connection.id),
schema: row.schema || selectedSchema.value, schema: row.schema || selectedSchema.value,
tableName: row.name, tableName: row.name,
limit: 100, limit: 100,
@@ -1585,6 +1586,7 @@ async function exportDataLegacy(row: ObjectBrowserRow, format: "json" | "sql") {
const queryColumns = props.connection.db_type === "neo4j" ? (tableColumns ?? (await api.getColumns(props.connection.id, props.database, schema || props.database, row.name))).map((column) => column.name) : undefined; const queryColumns = props.connection.db_type === "neo4j" ? (tableColumns ?? (await api.getColumns(props.connection.id, props.database, schema || props.database, row.name))).map((column) => column.name) : undefined;
const result = await fetchTableDataForExport({ const result = await fetchTableDataForExport({
databaseType: effectiveDatabaseType.value, databaseType: effectiveDatabaseType.value,
identifierQuote: connectionStore.connectionIdentifierQuote?.(props.connection.id),
schema, schema,
tableName: row.name, tableName: row.name,
columns: queryColumns, columns: queryColumns,
@@ -1394,6 +1394,7 @@ async function openData() {
const includeRowId = usesSyntheticRowIdKey(effectiveDbType, primaryKeys, tableType); const includeRowId = usesSyntheticRowIdKey(effectiveDbType, primaryKeys, tableType);
const sql = await buildTableSelectSql({ const sql = await buildTableSelectSql({
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote: connectionStore.connectionIdentifierQuote?.(node.connectionId),
schema: tableSchema, schema: tableSchema,
tableName: node.label, tableName: node.label,
tableType, tableType,
@@ -3768,6 +3769,7 @@ async function exportDataLegacy(format: "csv" | "json" | "sql") {
const effectiveDbType = effectiveDatabaseTypeForConnection(config); const effectiveDbType = effectiveDatabaseTypeForConnection(config);
const result = await fetchTableDataForExport({ const result = await fetchTableDataForExport({
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote: connectionStore.connectionIdentifierQuote?.(connectionId),
schema: node.schema, schema: node.schema,
tableName: node.label, tableName: node.label,
tableType: node.tableType, tableType: node.tableType,
@@ -3,7 +3,7 @@ import { useI18n } from "vue-i18n";
import { useConnectionStore } from "@/stores/connectionStore"; import { useConnectionStore } from "@/stores/connectionStore";
import { useQueryStore } from "@/stores/queryStore"; import { useQueryStore } from "@/stores/queryStore";
import { useSettingsStore } from "@/stores/settingsStore"; import { useSettingsStore } from "@/stores/settingsStore";
import { buildTableSelectSql, quoteTableIdentifier } from "@/lib/table/tableSelectSql"; import { buildTableSelectSql, quoteTableDataIdentifier } from "@/lib/table/tableSelectSql";
import { editableRowIdentifierColumns, usesSyntheticRowIdKey } from "@/lib/table/tableEditing"; import { editableRowIdentifierColumns, usesSyntheticRowIdKey } from "@/lib/table/tableEditing";
import { tableMetaForDataTab } from "@/lib/table/tableDataTabMeta"; import { tableMetaForDataTab } from "@/lib/table/tableDataTabMeta";
import * as api from "@/lib/backend/api"; import * as api from "@/lib/backend/api";
@@ -40,7 +40,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
function quoteIdent(tab: QueryTab, name: string): string { function quoteIdent(tab: QueryTab, name: string): string {
const config = connectionStore.getConfig(tab.connectionId); const config = connectionStore.getConfig(tab.connectionId);
return quoteTableIdentifier(effectiveDatabaseTypeForConnection(config), name); return quoteTableDataIdentifier(effectiveDatabaseTypeForConnection(config), name, connectionStore.connectionIdentifierQuote?.(tab.connectionId));
} }
function buildTableSql(tab: QueryTab, options: { orderBy?: string; limit?: number; offset?: number; whereInput?: string } = {}): Promise<string> { function buildTableSql(tab: QueryTab, options: { orderBy?: string; limit?: number; offset?: number; whereInput?: string } = {}): Promise<string> {
@@ -51,6 +51,7 @@ export function useDataGridActions(activeTab: ComputedRef<QueryTab | undefined>)
const useRowId = usesSyntheticRowIdKey(effectiveDbType, primaryKeys, tableMeta?.tableType); const useRowId = usesSyntheticRowIdKey(effectiveDbType, primaryKeys, tableMeta?.tableType);
return buildTableSelectSql({ return buildTableSelectSql({
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote: connectionStore.connectionIdentifierQuote?.(tab.connectionId),
schema: tableMeta?.schema, schema: tableMeta?.schema,
tableName: tableMeta?.tableName ?? "", tableName: tableMeta?.tableName ?? "",
tableType: tableMeta?.tableType, tableType: tableMeta?.tableType,
@@ -56,6 +56,7 @@ async function openTableTarget(target: NavigationTarget, options: { tableInfoTab
await connectionStore.ensureConnected(target.connectionId); await connectionStore.ensureConnected(target.connectionId);
if (!config) throw new Error("Connection config not found"); if (!config) throw new Error("Connection config not found");
const effectiveDbType = effectiveDatabaseTypeForConnection(config); const effectiveDbType = effectiveDatabaseTypeForConnection(config);
const identifierQuote = connectionStore.connectionIdentifierQuote?.(target.connectionId);
const querySchema = metadataSchemaForConnection(config, target.database, target.schema); const querySchema = metadataSchemaForConnection(config, target.database, target.schema);
const targetTableType = target.tableType ?? "TABLE"; const targetTableType = target.tableType ?? "TABLE";
if (config.db_type === "neo4j") { if (config.db_type === "neo4j") {
@@ -63,6 +64,7 @@ async function openTableTarget(target: NavigationTarget, options: { tableInfoTab
const primaryKeys = editableRowIdentifierColumns(effectiveDbType, columns, undefined, targetTableType); const primaryKeys = editableRowIdentifierColumns(effectiveDbType, columns, undefined, targetTableType);
const sql = await buildTableSelectSql({ const sql = await buildTableSelectSql({
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote,
schema: target.schema, schema: target.schema,
catalog: target.catalog, catalog: target.catalog,
tableName: target.tableName, tableName: target.tableName,
@@ -86,6 +88,7 @@ async function openTableTarget(target: NavigationTarget, options: { tableInfoTab
} }
const sql = await buildTableSelectSql({ const sql = await buildTableSelectSql({
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote,
schema: target.schema, schema: target.schema,
catalog: target.catalog, catalog: target.catalog,
tableName: target.tableName, tableName: target.tableName,
@@ -113,6 +116,7 @@ async function openTableTarget(target: NavigationTarget, options: { tableInfoTab
if (fellBackToLimitZero) { if (fellBackToLimitZero) {
const emptySql = await buildTableSelectSql({ const emptySql = await buildTableSelectSql({
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote,
schema: target.schema, schema: target.schema,
catalog: target.catalog, catalog: target.catalog,
tableName: target.tableName, tableName: target.tableName,
@@ -139,6 +143,7 @@ async function openTableTarget(target: NavigationTarget, options: { tableInfoTab
if (!fellBackToLimitZero && (useRowId || config.db_type === "tdengine")) { if (!fellBackToLimitZero && (useRowId || config.db_type === "tdengine")) {
const newSql = await buildTableSelectSql({ const newSql = await buildTableSelectSql({
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote,
schema: target.schema, schema: target.schema,
catalog: target.catalog, catalog: target.catalog,
tableName: target.tableName, tableName: target.tableName,
+14 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { qualifiedTableName, quoteTableIdentifier } from "@/lib/table/tableSelectSql"; import { qualifiedTableName, quoteTableDataIdentifier, quoteTableIdentifier } from "@/lib/table/tableSelectSql";
describe("qualifiedTableName — Doris/StarRocks multi-catalog", () => { describe("qualifiedTableName — Doris/StarRocks multi-catalog", () => {
it("prefixes external catalog for Doris (no schema)", () => { it("prefixes external catalog for Doris (no schema)", () => {
@@ -36,4 +36,17 @@ describe("quoteTableIdentifier", () => {
it("bracket-quotes sqlserver identifiers", () => { it("bracket-quotes sqlserver identifiers", () => {
expect(quoteTableIdentifier("sqlserver", "orders")).toBe("[orders]"); expect(quoteTableIdentifier("sqlserver", "orders")).toBe("[orders]");
}); });
it("uses the connection-reported quote for Kingbase table-data identifiers", () => {
expect(quoteTableDataIdentifier("kingbase", "order", "`")).toBe("`order`");
expect(quoteTableDataIdentifier("kingbase", "MixedCase", '"')).toBe('"MixedCase"');
expect(quoteTableDataIdentifier("kingbase", "order detail", "`")).toBe("`order detail`");
});
it("escapes Kingbase identifiers without maintaining a reserved-word list", () => {
expect(quoteTableDataIdentifier("kingbase", "ANALYZE", "`")).toBe("`ANALYZE`");
expect(quoteTableDataIdentifier("kingbase", "AUTHORIZATION", '"')).toBe('"AUTHORIZATION"');
expect(quoteTableDataIdentifier("kingbase", "COLLATE", "`")).toBe("`COLLATE`");
expect(quoteTableDataIdentifier("kingbase", "a`b", "`")).toBe("`a``b`");
});
}); });
+1
View File
@@ -55,6 +55,7 @@ export const connectDb = forward("connectDb");
export const connectionFinalProxyPort = forward("connectionFinalProxyPort"); export const connectionFinalProxyPort = forward("connectionFinalProxyPort");
export const disconnectDb = forward("disconnectDb"); export const disconnectDb = forward("disconnectDb");
export const checkConnectionHealth = forward("checkConnectionHealth"); export const checkConnectionHealth = forward("checkConnectionHealth");
export const connectionIdentifierQuote = forward("connectionIdentifierQuote");
export const closeDatabaseConnection = forward("closeDatabaseConnection"); export const closeDatabaseConnection = forward("closeDatabaseConnection");
export const refreshConnections = forward("refreshConnections"); export const refreshConnections = forward("refreshConnections");
export const saveConnections = forward("saveConnections"); export const saveConnections = forward("saveConnections");
+5
View File
@@ -225,6 +225,11 @@ export async function checkConnectionHealth(connectionId: string): Promise<void>
return post("/api/connection/check-health", { connectionId }); return post("/api/connection/check-health", { connectionId });
} }
export async function connectionIdentifierQuote(connectionId: string, database?: string): Promise<string | undefined> {
const quote = await post<string | null>("/api/connection/identifier-quote", { connectionId, database });
return quote ?? undefined;
}
export async function closeDatabaseConnection(connectionId: string, database: string): Promise<boolean> { export async function closeDatabaseConnection(connectionId: string, database: string): Promise<boolean> {
return post("/api/connection/close-database", { connectionId, database }); return post("/api/connection/close-database", { connectionId, database });
} }
+5
View File
@@ -652,6 +652,11 @@ export async function checkConnectionHealth(connectionId: string): Promise<void>
return invoke("check_connection_health", { connectionId }); return invoke("check_connection_health", { connectionId });
} }
export async function connectionIdentifierQuote(connectionId: string, database?: string): Promise<string | undefined> {
const quote = await invoke<string | null>("connection_identifier_quote", { connectionId, database });
return quote ?? undefined;
}
export async function closeDatabaseConnection(connectionId: string, database: string): Promise<boolean> { export async function closeDatabaseConnection(connectionId: string, database: string): Promise<boolean> {
return invoke("close_database_connection", { connectionId, database }); return invoke("close_database_connection", { connectionId, database });
} }
@@ -93,6 +93,7 @@ export interface DataGridColumnDistinctValuesSqlOptions {
export interface DataGridCountSqlOptions { export interface DataGridCountSqlOptions {
databaseType?: DatabaseType; databaseType?: DatabaseType;
identifierQuote?: string;
catalog?: string; catalog?: string;
schema?: string; schema?: string;
tableName: string; tableName: string;
@@ -46,6 +46,7 @@ export interface BuildExportInsertStatementsOptions {
export interface BuildExportPageSqlOptions { export interface BuildExportPageSqlOptions {
databaseType?: DatabaseType; databaseType?: DatabaseType;
identifierQuote?: string;
schema?: string; schema?: string;
tableName: string; tableName: string;
limit?: number; limit?: number;
@@ -72,6 +73,7 @@ export function buildInsertStatements(options: BuildExportInsertStatementsOption
export async function buildExportPageSql(options: BuildExportPageSqlOptions): Promise<string> { export async function buildExportPageSql(options: BuildExportPageSqlOptions): Promise<string> {
return buildTableSelectSql({ return buildTableSelectSql({
databaseType: options.databaseType, databaseType: options.databaseType,
identifierQuote: options.identifierQuote,
schema: options.schema, schema: options.schema,
tableName: options.tableName, tableName: options.tableName,
limit: options.limit ?? DATABASE_EXPORT_PAGE_SIZE, limit: options.limit ?? DATABASE_EXPORT_PAGE_SIZE,
@@ -5,6 +5,7 @@ export const TABLE_DATA_EXPORT_PAGE_SIZE = 10_000;
export interface FetchTableDataForExportOptions { export interface FetchTableDataForExportOptions {
databaseType?: DatabaseType; databaseType?: DatabaseType;
identifierQuote?: string;
schema?: string; schema?: string;
tableName: string; tableName: string;
tableType?: string; tableType?: string;
@@ -24,6 +25,7 @@ export async function fetchTableDataForExport(options: FetchTableDataForExportOp
while (true) { while (true) {
const sql = await (options.buildPageSql ?? buildTableSelectSql)({ const sql = await (options.buildPageSql ?? buildTableSelectSql)({
databaseType: options.databaseType, databaseType: options.databaseType,
identifierQuote: options.identifierQuote,
schema: options.schema, schema: options.schema,
tableName: options.tableName, tableName: options.tableName,
tableType: options.tableType, tableType: options.tableType,
@@ -5,6 +5,7 @@ import { parseSqlServerLinkedSchema, sqlServerLinkedTableName } from "@/lib/data
export interface BuildTableSelectSqlOptions { export interface BuildTableSelectSqlOptions {
databaseType?: DatabaseType; databaseType?: DatabaseType;
identifierQuote?: string;
schema?: string; schema?: string;
tableName: string; tableName: string;
tableType?: string; tableType?: string;
@@ -32,6 +33,14 @@ export function quoteTableIdentifier(databaseType: DatabaseType | undefined, nam
return `"${name.replace(/"/g, '""')}"`; return `"${name.replace(/"/g, '""')}"`;
} }
export function quoteTableDataIdentifier(databaseType: DatabaseType | undefined, name: string, identifierQuote?: string): string {
if (databaseType === "kingbase" && identifierQuote != null) {
if (!identifierQuote) return name;
return `${identifierQuote}${name.replaceAll(identifierQuote, identifierQuote + identifierQuote)}${identifierQuote}`;
}
return quoteTableIdentifier(databaseType, name);
}
function quoteCypherIdentifier(name: string): string { function quoteCypherIdentifier(name: string): string {
return `\`${name.replace(/`/g, "``")}\``; return `\`${name.replace(/`/g, "``")}\``;
} }
@@ -462,6 +462,7 @@ describe("queryStore hidden primary key editing", () => {
expect(buildDataGridCountSql).toHaveBeenCalledWith({ expect(buildDataGridCountSql).toHaveBeenCalledWith({
databaseType: "mysql", databaseType: "mysql",
identifierQuote: undefined,
catalog: undefined, catalog: undefined,
schema: "public", schema: "public",
tableName: "users", tableName: "users",
@@ -105,6 +105,7 @@ describe("queryStore table data refresh", () => {
expect(refreshed).toBe(1); expect(refreshed).toBe(1);
expect(mocks.buildTableSelectSql).toHaveBeenCalledWith({ expect(mocks.buildTableSelectSql).toHaveBeenCalledWith({
databaseType: "postgres", databaseType: "postgres",
identifierQuote: undefined,
schema: "public", schema: "public",
tableName: "users", tableName: "users",
tableType: "TABLE", tableType: "TABLE",
@@ -233,6 +233,7 @@ export const useConnectionStore = defineStore("connection", () => {
const treeNodes = ref<TreeNode[]>([]); const treeNodes = ref<TreeNode[]>([]);
const pinnedTreeNodeIds = ref<Set<string>>(new Set()); const pinnedTreeNodeIds = ref<Set<string>>(new Set());
const connectedIds = ref<Set<string>>(new Set()); const connectedIds = ref<Set<string>>(new Set());
const identifierQuotes = ref<Record<string, string>>({});
const lastConnectionHealthCheckAt = ref<Record<string, number>>({}); const lastConnectionHealthCheckAt = ref<Record<string, number>>({});
const agentDrivers = ref<AgentDriverInstallState[]>([]); const agentDrivers = ref<AgentDriverInstallState[]>([]);
let agentDriversRefreshPromise: Promise<void> | null = null; let agentDriversRefreshPromise: Promise<void> | null = null;
@@ -385,6 +386,25 @@ export const useConnectionStore = defineStore("connection", () => {
return configById.value.get(connectionId); return configById.value.get(connectionId);
} }
function connectionIdentifierQuote(connectionId?: string): string | undefined {
if (!connectionId) return undefined;
return identifierQuotes.value[connectionId];
}
function clearConnectionIdentifierQuote(connectionId: string) {
if (!(connectionId in identifierQuotes.value)) return;
const next = { ...identifierQuotes.value };
delete next[connectionId];
identifierQuotes.value = next;
}
async function refreshConnectionIdentifierQuote(connectionId: string, config: ConnectionConfig) {
clearConnectionIdentifierQuote(connectionId);
if (config.db_type !== "kingbase") return;
const quote = await api.connectionIdentifierQuote(connectionId).catch(() => undefined);
if (quote != null) identifierQuotes.value = { ...identifierQuotes.value, [connectionId]: quote };
}
function connectionErrorMessage(error: unknown): string { function connectionErrorMessage(error: unknown): string {
if (error instanceof Error) return error.message; if (error instanceof Error) return error.message;
return String(error); return String(error);
@@ -711,6 +731,7 @@ export const useConnectionStore = defineStore("connection", () => {
function markConnectionLost(connectionId: string, error: unknown) { function markConnectionLost(connectionId: string, error: unknown) {
connectedIds.value.delete(connectionId); connectedIds.value.delete(connectionId);
clearConnectionIdentifierQuote(connectionId);
clearConnectionNodeLoading(connectionId); clearConnectionNodeLoading(connectionId);
clearConnectionHealthCheck(connectionId); clearConnectionHealthCheck(connectionId);
if (activeConnectionId.value === connectionId) activeConnectionId.value = null; if (activeConnectionId.value === connectionId) activeConnectionId.value = null;
@@ -1629,6 +1650,7 @@ export const useConnectionStore = defineStore("connection", () => {
for (const id of removedIds) { for (const id of removedIds) {
clearConnectionError(id); clearConnectionError(id);
connectedIds.value.delete(id); connectedIds.value.delete(id);
clearConnectionIdentifierQuote(id);
clearConnectionHealthCheck(id); clearConnectionHealthCheck(id);
sidebarLayout.value = removeConnectionFromSidebarLayout(sidebarLayout.value, id); sidebarLayout.value = removeConnectionFromSidebarLayout(sidebarLayout.value, id);
} }
@@ -1660,6 +1682,7 @@ export const useConnectionStore = defineStore("connection", () => {
connections.value = nextConnections; connections.value = nextConnections;
rebuildTreeNodes(); rebuildTreeNodes();
connectedIds.value.delete(config.id); connectedIds.value.delete(config.id);
clearConnectionIdentifierQuote(config.id);
clearConnectionHealthCheck(config.id); clearConnectionHealthCheck(config.id);
invalidateCompletionCache(config.id); invalidateCompletionCache(config.id);
clearLoadedChildrenCache(config.id); clearLoadedChildrenCache(config.id);
@@ -1853,6 +1876,7 @@ export const useConnectionStore = defineStore("connection", () => {
await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id); await ensureLocalConnectionAttemptActiveAfterConnectResult(config.id, localAttempt, id);
activeConnectionId.value = id; activeConnectionId.value = id;
connectedIds.value.add(id); connectedIds.value.add(id);
await refreshConnectionIdentifierQuote(id, { ...config, id });
if (id !== config.id) markSuccessfulLocalConnectionAttempt(config.id, localAttempt); if (id !== config.id) markSuccessfulLocalConnectionAttempt(config.id, localAttempt);
markSuccessfulLocalConnectionAttempt(id, localAttempt); markSuccessfulLocalConnectionAttempt(id, localAttempt);
markConnectionHealthChecked(id); markConnectionHealthChecked(id);
@@ -1900,6 +1924,7 @@ export const useConnectionStore = defineStore("connection", () => {
if (!cancelled) return false; if (!cancelled) return false;
clearConnectionError(connectionId); clearConnectionError(connectionId);
connectedIds.value.delete(connectionId); connectedIds.value.delete(connectionId);
clearConnectionIdentifierQuote(connectionId);
clearConnectionHealthCheck(connectionId); clearConnectionHealthCheck(connectionId);
if (activeConnectionId.value === connectionId) activeConnectionId.value = null; if (activeConnectionId.value === connectionId) activeConnectionId.value = null;
invalidateCompletionCache(connectionId); invalidateCompletionCache(connectionId);
@@ -1914,6 +1939,7 @@ export const useConnectionStore = defineStore("connection", () => {
const shouldRemoveOneTimeConnection = getConfig(connectionId)?.one_time === true; const shouldRemoveOneTimeConnection = getConfig(connectionId)?.one_time === true;
connectedIds.value.delete(connectionId); connectedIds.value.delete(connectionId);
clearConnectionIdentifierQuote(connectionId);
forgetSuccessfulLocalConnectionAttempt(connectionId); forgetSuccessfulLocalConnectionAttempt(connectionId);
clearConnectionHealthCheck(connectionId); clearConnectionHealthCheck(connectionId);
const node = findNode(treeNodes.value, connectionId); const node = findNode(treeNodes.value, connectionId);
@@ -2014,6 +2040,7 @@ export const useConnectionStore = defineStore("connection", () => {
await syncMongoLegacyDriverFallback(connectionId, config); await syncMongoLegacyDriverFallback(connectionId, config);
await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id); await ensureLocalConnectionAttemptActiveAfterConnectResult(connectionId, localAttempt, id);
connectedIds.value.add(connectionId); connectedIds.value.add(connectionId);
await refreshConnectionIdentifierQuote(connectionId, config);
markSuccessfulLocalConnectionAttempt(connectionId, localAttempt); markSuccessfulLocalConnectionAttempt(connectionId, localAttempt);
markConnectionHealthChecked(connectionId); markConnectionHealthChecked(connectionId);
activeConnectionId.value = connectionId; activeConnectionId.value = connectionId;
@@ -5089,6 +5116,7 @@ export const useConnectionStore = defineStore("connection", () => {
recordConnectionLostError, recordConnectionLostError,
sidebarLayout, sidebarLayout,
getConfig, getConfig,
connectionIdentifierQuote,
isTreeNodePinned, isTreeNodePinned,
toggleTreeNodePin, toggleTreeNodePin,
addConnection, addConnection,
+10 -4
View File
@@ -34,7 +34,7 @@ import { tableMetaForDataTab } from "@/lib/table/tableDataTabMeta";
import { dataTabExecutionDatabase } from "@/lib/table/dataTabExecutionDatabase"; import { dataTabExecutionDatabase } from "@/lib/table/dataTabExecutionDatabase";
import { tableOpenPageLimit } from "@/lib/table/tableOpenPageLimit"; import { tableOpenPageLimit } from "@/lib/table/tableOpenPageLimit";
import { loadTableMetadata } from "@/lib/metadata/tableMetadataCache"; import { loadTableMetadata } from "@/lib/metadata/tableMetadataCache";
import { buildTableSelectSql, quoteTableIdentifier } from "@/lib/table/tableSelectSql"; import { buildTableSelectSql, quoteTableDataIdentifier } from "@/lib/table/tableSelectSql";
import { connectionQueryExecutionSchema, effectiveDatabaseTypeForConnection, metadataSchemaForConnection } from "@/lib/database/jdbcDialect"; import { connectionQueryExecutionSchema, effectiveDatabaseTypeForConnection, metadataSchemaForConnection } from "@/lib/database/jdbcDialect";
import { frontendQueryTimeoutSecsForSql, queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout"; import { frontendQueryTimeoutSecsForSql, queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";
import { queryResultSourceLabel } from "@/lib/sql/queryResultSource"; import { queryResultSourceLabel } from "@/lib/sql/queryResultSource";
@@ -1625,15 +1625,18 @@ export const useQueryStore = defineStore("query", () => {
for (const tab of matchingTabs) { for (const tab of matchingTabs) {
const tableMeta = tableMetaForDataTab(tab); const tableMeta = tableMetaForDataTab(tab);
if (!tableMeta?.tableName) continue; if (!tableMeta?.tableName) continue;
const conn = useConnectionStore().getConfig(tab.connectionId); const connStore = useConnectionStore();
const conn = connStore.getConfig(tab.connectionId);
const effectiveDbType = effectiveDatabaseTypeForConnection(conn); const effectiveDbType = effectiveDatabaseTypeForConnection(conn);
const identifierQuote = connStore.connectionIdentifierQuote?.(tab.connectionId);
const primaryKeys = tab.tableMeta ? tab.tableMeta.primaryKeys : tableMeta.primaryKeys; const primaryKeys = tab.tableMeta ? tab.tableMeta.primaryKeys : tableMeta.primaryKeys;
const sortOrder = tab.resultSortColumn && tab.resultSortDirection ? `${quoteTableIdentifier(effectiveDbType, tab.resultSortColumn)} ${tab.resultSortDirection.toUpperCase()}` : undefined; const sortOrder = tab.resultSortColumn && tab.resultSortDirection ? `${quoteTableDataIdentifier(effectiveDbType, tab.resultSortColumn, identifierQuote)} ${tab.resultSortDirection.toUpperCase()}` : undefined;
const orderBy = tab.orderByInput?.trim() || sortOrder; const orderBy = tab.orderByInput?.trim() || sortOrder;
const limit = tab.resultPageLimit ?? settingsStore.editorSettings.pageSize ?? tableOpenPageLimit(); const limit = tab.resultPageLimit ?? settingsStore.editorSettings.pageSize ?? tableOpenPageLimit();
const offset = tab.resultPageOffset ?? 0; const offset = tab.resultPageOffset ?? 0;
const sql = await buildTableSelectSql({ const sql = await buildTableSelectSql({
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote,
schema: tableMeta.schema, schema: tableMeta.schema,
tableName: tableMeta.tableName, tableName: tableMeta.tableName,
tableType: tableMeta.tableType, tableType: tableMeta.tableType,
@@ -2967,6 +2970,7 @@ export const useQueryStore = defineStore("query", () => {
if (!tableMeta?.tableName) return undefined; if (!tableMeta?.tableName) return undefined;
return { return {
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote: useConnectionStore().connectionIdentifierQuote?.(current.connectionId),
catalog: tableMeta.catalog, catalog: tableMeta.catalog,
schema: tableMeta.schema, schema: tableMeta.schema,
tableName: tableMeta.tableName, tableName: tableMeta.tableName,
@@ -3578,8 +3582,9 @@ export const useQueryStore = defineStore("query", () => {
const totalRows = typeof tab.resultTotalRowCount === "number" ? tab.resultTotalRowCount : null; const totalRows = typeof tab.resultTotalRowCount === "number" ? tab.resultTotalRowCount : null;
const pageLimit = TABLE_DATA_EXPORT_PAGE_SIZE; const pageLimit = TABLE_DATA_EXPORT_PAGE_SIZE;
const effectiveDbType = effectiveDatabaseTypeForConnection(conn); const effectiveDbType = effectiveDatabaseTypeForConnection(conn);
const identifierQuote = connStore.connectionIdentifierQuote?.(tab.connectionId);
const primaryKeys = tab.tableMeta ? tab.tableMeta.primaryKeys : tableMeta.primaryKeys; const primaryKeys = tab.tableMeta ? tab.tableMeta.primaryKeys : tableMeta.primaryKeys;
const sortOrder = tab.resultSortColumn && tab.resultSortDirection ? `${quoteTableIdentifier(effectiveDbType, tab.resultSortColumn)} ${tab.resultSortDirection.toUpperCase()}` : undefined; const sortOrder = tab.resultSortColumn && tab.resultSortDirection ? `${quoteTableDataIdentifier(effectiveDbType, tab.resultSortColumn, identifierQuote)} ${tab.resultSortDirection.toUpperCase()}` : undefined;
const orderBy = tab.orderByInput?.trim() || sortOrder; const orderBy = tab.orderByInput?.trim() || sortOrder;
const queryTimeoutSecs = queryTimeoutSecsForConnection(conn); const queryTimeoutSecs = queryTimeoutSecsForConnection(conn);
const executionDatabase = dataTabExecutionDatabase(conn, tab.database, tableMeta.catalog); const executionDatabase = dataTabExecutionDatabase(conn, tab.database, tableMeta.catalog);
@@ -3594,6 +3599,7 @@ export const useQueryStore = defineStore("query", () => {
while (true) { while (true) {
const sql = await api.buildTableSelectSql({ const sql = await api.buildTableSelectSql({
databaseType: effectiveDbType, databaseType: effectiveDbType,
identifierQuote,
schema: tableMeta.schema, schema: tableMeta.schema,
tableName: tableMeta.tableName, tableName: tableMeta.tableName,
tableType: tableMeta.tableType, tableType: tableMeta.tableType,
@@ -39,6 +39,7 @@
"connect", "connect",
"test_connection", "test_connection",
"validate_connection", "validate_connection",
"connection_info",
"list_databases", "list_databases",
"list_schemas", "list_schemas",
"list_tables", "list_tables",
@@ -46,6 +46,7 @@
"cancel_session", "cancel_session",
"test_connection", "test_connection",
"validate_connection", "validate_connection",
"connection_info",
"list_databases", "list_databases",
"list_schemas", "list_schemas",
"list_tables", "list_tables",
+29
View File
@@ -2317,6 +2317,35 @@ impl AppState {
keys keys
} }
pub async fn connection_identifier_quote(
&self,
connection_id: &str,
database: Option<&str>,
) -> Result<Option<String>, String> {
let config = self
.configs
.read()
.await
.get(connection_id)
.cloned()
.ok_or_else(|| format!("Connection config not found: {connection_id}"))?;
if !database_capabilities::is_agent_type(&config.db_type) {
return Ok(None);
}
let pool_key = self.get_or_create_pool(connection_id, database).await?;
let client = {
let connections = self.connections.read().await;
match connections.get(&pool_key) {
Some(PoolKind::Agent(client)) => client.clone(),
_ => return Ok(None),
}
};
let mut agent = client.lock().await;
let info = agent.connection_info(Some(db::connection_timeout())).await?;
Ok(Some(info.identifier_quote))
}
pub async fn reset_connection_transport(&self, connection_id: &str) { pub async fn reset_connection_transport(&self, connection_id: &str) {
let layer_count = { let layer_count = {
let configs = self.configs.read().await; let configs = self.configs.read().await;
+31 -6
View File
@@ -217,6 +217,8 @@ pub struct DataGridCountSqlOptions {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub database_type: Option<DatabaseType>, pub database_type: Option<DatabaseType>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub identifier_quote: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub catalog: Option<String>, pub catalog: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<String>, pub schema: Option<String>,
@@ -721,12 +723,21 @@ pub fn build_data_grid_column_distinct_values_sql(options: DataGridColumnDistinc
} }
pub fn build_data_grid_count_sql(options: DataGridCountSqlOptions) -> String { pub fn build_data_grid_count_sql(options: DataGridCountSqlOptions) -> String {
let table = crate::sql_dialect::qualified_table_name_with_catalog( let table = if options.database_type == Some(DatabaseType::Kingbase) {
options.database_type, crate::sql_dialect::table_data_qualified_table_name(
options.catalog.as_deref(), options.database_type,
options.schema.as_deref(), options.schema.as_deref(),
&options.table_name, &options.table_name,
); options.identifier_quote.as_deref(),
)
} else {
crate::sql_dialect::qualified_table_name_with_catalog(
options.database_type,
options.catalog.as_deref(),
options.schema.as_deref(),
&options.table_name,
)
};
let predicate = crate::sql_dialect::normalize_where_input(options.where_input.as_deref()); let predicate = crate::sql_dialect::normalize_where_input(options.where_input.as_deref());
let where_clause = if predicate.is_empty() { String::new() } else { format!(" WHERE ({predicate})") }; let where_clause = if predicate.is_empty() { String::new() } else { format!(" WHERE ({predicate})") };
format!("SELECT COUNT(*) AS cnt FROM {table}{where_clause}") format!("SELECT COUNT(*) AS cnt FROM {table}{where_clause}")
@@ -3060,6 +3071,7 @@ mod tests {
assert_eq!( assert_eq!(
build_data_grid_count_sql(DataGridCountSqlOptions { build_data_grid_count_sql(DataGridCountSqlOptions {
database_type: Some(DatabaseType::Postgres), database_type: Some(DatabaseType::Postgres),
identifier_quote: None,
catalog: None, catalog: None,
schema: Some("public".to_string()), schema: Some("public".to_string()),
table_name: "users".to_string(), table_name: "users".to_string(),
@@ -3070,6 +3082,7 @@ mod tests {
assert_eq!( assert_eq!(
build_data_grid_count_sql(DataGridCountSqlOptions { build_data_grid_count_sql(DataGridCountSqlOptions {
database_type: Some(DatabaseType::Doris), database_type: Some(DatabaseType::Doris),
identifier_quote: None,
catalog: Some("iceberg_catalog".to_string()), catalog: Some("iceberg_catalog".to_string()),
schema: Some("sales".to_string()), schema: Some("sales".to_string()),
table_name: "orders".to_string(), table_name: "orders".to_string(),
@@ -3080,6 +3093,7 @@ mod tests {
assert_eq!( assert_eq!(
build_data_grid_count_sql(DataGridCountSqlOptions { build_data_grid_count_sql(DataGridCountSqlOptions {
database_type: Some(DatabaseType::StarRocks), database_type: Some(DatabaseType::StarRocks),
identifier_quote: None,
catalog: Some("hive_catalog".to_string()), catalog: Some("hive_catalog".to_string()),
schema: None, schema: None,
table_name: "orders".to_string(), table_name: "orders".to_string(),
@@ -3087,6 +3101,17 @@ mod tests {
}), }),
"SELECT COUNT(*) AS cnt FROM `hive_catalog`.`orders`" "SELECT COUNT(*) AS cnt FROM `hive_catalog`.`orders`"
); );
assert_eq!(
build_data_grid_count_sql(DataGridCountSqlOptions {
database_type: Some(DatabaseType::Kingbase),
identifier_quote: Some("`".to_string()),
catalog: None,
schema: Some("cqbq_ls".to_string()),
table_name: "ANALYZE".to_string(),
where_input: None,
}),
"SELECT COUNT(*) AS cnt FROM `cqbq_ls`.`ANALYZE`"
);
} }
#[test] #[test]
+14 -1
View File
@@ -373,6 +373,7 @@ pub enum AgentMethod {
CancelSession, CancelSession,
TestConnection, TestConnection,
ValidateConnection, ValidateConnection,
ConnectionInfo,
ListDatabases, ListDatabases,
ListSchemas, ListSchemas,
ListTables, ListTables,
@@ -400,7 +401,7 @@ pub enum AgentMethod {
} }
impl AgentMethod { impl AgentMethod {
pub const ALL: [Self; 32] = [ pub const ALL: [Self; 33] = [
Self::Handshake, Self::Handshake,
Self::Connect, Self::Connect,
Self::OpenSession, Self::OpenSession,
@@ -409,6 +410,7 @@ impl AgentMethod {
Self::CancelSession, Self::CancelSession,
Self::TestConnection, Self::TestConnection,
Self::ValidateConnection, Self::ValidateConnection,
Self::ConnectionInfo,
Self::ListDatabases, Self::ListDatabases,
Self::ListSchemas, Self::ListSchemas,
Self::ListTables, Self::ListTables,
@@ -445,6 +447,7 @@ impl AgentMethod {
Self::CancelSession => "cancel_session", Self::CancelSession => "cancel_session",
Self::TestConnection => "test_connection", Self::TestConnection => "test_connection",
Self::ValidateConnection => "validate_connection", Self::ValidateConnection => "validate_connection",
Self::ConnectionInfo => "connection_info",
Self::ListDatabases => "list_databases", Self::ListDatabases => "list_databases",
Self::ListSchemas => "list_schemas", Self::ListSchemas => "list_schemas",
Self::ListTables => "list_tables", Self::ListTables => "list_tables",
@@ -473,6 +476,12 @@ impl AgentMethod {
} }
} }
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentConnectionInfo {
pub identifier_quote: String,
}
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct AgentTableReadStartParams { pub struct AgentTableReadStartParams {
@@ -910,6 +919,10 @@ impl AgentDriverClient {
self.call_method_with_timeout(AgentMethod::ValidateConnection, serde_json::json!({}), timeout_duration).await self.call_method_with_timeout(AgentMethod::ValidateConnection, serde_json::json!({}), timeout_duration).await
} }
pub async fn connection_info(&mut self, timeout_duration: Option<Duration>) -> Result<AgentConnectionInfo, String> {
self.call_method_with_timeout(AgentMethod::ConnectionInfo, serde_json::json!({}), timeout_duration).await
}
pub async fn disconnect(&mut self) -> Result<Value, String> { pub async fn disconnect(&mut self) -> Result<Value, String> {
if self.shared_runtime.is_some() { if self.shared_runtime.is_some() {
let session_id = self.agent_session_id.as_ref().ok_or("Shared Agent session id is missing")?.clone(); let session_id = self.agent_session_id.as_ref().ok_or("Shared Agent session id is missing")?.clone();
+1
View File
@@ -14,5 +14,6 @@ pub use identifiers::{
normalize_where_input, qualified_table_name, qualified_table_name_with_catalog, quote_table_identifier, normalize_where_input, qualified_table_name, qualified_table_name_with_catalog, quote_table_identifier,
}; };
pub(crate) use identifiers::{parse_sqlserver_linked_schema_ref, qualified_transfer_table, quote_transfer_identifier}; pub(crate) use identifiers::{parse_sqlserver_linked_schema_ref, qualified_transfer_table, quote_transfer_identifier};
pub(crate) use table_select::table_data_qualified_table_name;
pub use table_select::{build_count_table_sql, build_table_data_select_sql, build_table_select_sql}; pub use table_select::{build_count_table_sql, build_table_data_select_sql, build_table_select_sql};
pub use types::*; pub use types::*;
@@ -21,12 +21,21 @@ pub fn build_table_data_select_sql(options: TableDataSelectSqlOptions) -> String
} }
// Doris / StarRocks multi-catalog: prefix the catalog for external-catalog tables. // Doris / StarRocks multi-catalog: prefix the catalog for external-catalog tables.
let table = qualified_table_name_with_catalog( let table = if database_type == Some(DatabaseType::Kingbase) {
database_type, table_data_qualified_table_name(
options.catalog.as_deref(), database_type,
options.schema.as_deref(), options.schema.as_deref(),
&options.table_name, &options.table_name,
); options.identifier_quote.as_deref(),
)
} else {
qualified_table_name_with_catalog(
database_type,
options.catalog.as_deref(),
options.schema.as_deref(),
&options.table_name,
)
};
let predicate = normalize_where_input(options.where_input.as_deref()); let predicate = normalize_where_input(options.where_input.as_deref());
let where_clause = if predicate.is_empty() { String::new() } else { format!(" WHERE ({predicate})") }; let where_clause = if predicate.is_empty() { String::new() } else { format!(" WHERE ({predicate})") };
let default_order_by = if database_type == Some(DatabaseType::InfluxDb) { let default_order_by = if database_type == Some(DatabaseType::InfluxDb) {
@@ -143,6 +152,40 @@ pub fn build_table_data_select_sql(options: TableDataSelectSqlOptions) -> String
} }
} }
pub(crate) fn table_data_qualified_table_name(
database_type: Option<DatabaseType>,
schema: Option<&str>,
table_name: &str,
identifier_quote: Option<&str>,
) -> String {
if database_type != Some(DatabaseType::Kingbase) {
return qualified_table_name(database_type, schema, table_name);
}
let table = quote_table_data_identifier(database_type, table_name, identifier_quote);
schema
.map(str::trim)
.filter(|schema| !schema.is_empty())
.map(|schema| format!("{}.{}", quote_table_data_identifier(database_type, schema, identifier_quote), table))
.unwrap_or(table)
}
fn quote_table_data_identifier(
database_type: Option<DatabaseType>,
name: &str,
identifier_quote: Option<&str>,
) -> String {
if database_type != Some(DatabaseType::Kingbase) {
return quote_table_identifier(database_type, name);
}
let Some(quote) = identifier_quote else {
return quote_table_identifier(database_type, name);
};
if quote.is_empty() {
return name.to_string();
}
format!("{quote}{}{quote}", name.replace(quote, &format!("{quote}{quote}")))
}
fn is_view_table_type(table_type: Option<&str>) -> bool { fn is_view_table_type(table_type: Option<&str>) -> bool {
table_type.is_some_and(|value| value.to_ascii_uppercase().contains("VIEW")) table_type.is_some_and(|value| value.to_ascii_uppercase().contains("VIEW"))
} }
@@ -418,6 +461,7 @@ mod tests {
fn opts(database_type: DatabaseType, catalog: Option<&str>, table: &str) -> TableDataSelectSqlOptions { fn opts(database_type: DatabaseType, catalog: Option<&str>, table: &str) -> TableDataSelectSqlOptions {
TableDataSelectSqlOptions { TableDataSelectSqlOptions {
database_type: Some(database_type), database_type: Some(database_type),
identifier_quote: None,
schema: None, schema: None,
table_name: table.to_string(), table_name: table.to_string(),
catalog: catalog.map(|c| c.to_string()), catalog: catalog.map(|c| c.to_string()),
+43
View File
@@ -21,6 +21,11 @@ fn quotes_identifiers_by_database_type() {
assert_eq!(quote_table_identifier(Some(DatabaseType::StarRocks), "user`name"), "`user``name`"); assert_eq!(quote_table_identifier(Some(DatabaseType::StarRocks), "user`name"), "`user``name`");
assert_eq!(quote_table_identifier(Some(DatabaseType::SqlServer), "user]name"), "[user]]name]"); assert_eq!(quote_table_identifier(Some(DatabaseType::SqlServer), "user]name"), "[user]]name]");
assert_eq!(quote_table_identifier(Some(DatabaseType::Postgres), "user\"name"), "\"user\"\"name\""); assert_eq!(quote_table_identifier(Some(DatabaseType::Postgres), "user\"name"), "\"user\"\"name\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Kingbase), "cqbq_ls"), "\"cqbq_ls\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Kingbase), "actionlogs"), "\"actionlogs\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Kingbase), "order"), "\"order\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Kingbase), "MixedCase"), "\"MixedCase\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Kingbase), "order detail"), "\"order detail\"");
assert_eq!(quote_table_identifier(Some(DatabaseType::Informix), "users_1"), "users_1"); assert_eq!(quote_table_identifier(Some(DatabaseType::Informix), "users_1"), "users_1");
assert_eq!(quote_table_identifier(Some(DatabaseType::Jdbc), "users_1"), "users_1"); assert_eq!(quote_table_identifier(Some(DatabaseType::Jdbc), "users_1"), "users_1");
assert_eq!(quote_table_identifier(Some(DatabaseType::Jdbc), "user name"), "user name"); assert_eq!(quote_table_identifier(Some(DatabaseType::Jdbc), "user name"), "user name");
@@ -31,6 +36,10 @@ fn quotes_identifiers_by_database_type() {
fn qualifies_schema_only_for_schema_aware_databases() { fn qualifies_schema_only_for_schema_aware_databases() {
assert_eq!(qualified_table_name(Some(DatabaseType::Postgres), Some("public"), "users"), "\"public\".\"users\""); assert_eq!(qualified_table_name(Some(DatabaseType::Postgres), Some("public"), "users"), "\"public\".\"users\"");
assert_eq!(qualified_table_name(Some(DatabaseType::Kwdb), Some("public"), "users"), "\"public\".\"users\""); assert_eq!(qualified_table_name(Some(DatabaseType::Kwdb), Some("public"), "users"), "\"public\".\"users\"");
assert_eq!(
qualified_table_name(Some(DatabaseType::Kingbase), Some("cqbq_ls"), "actionlogs"),
"\"cqbq_ls\".\"actionlogs\""
);
assert_eq!(qualified_table_name(Some(DatabaseType::Mysql), Some("public"), "users"), "`public`.`users`"); assert_eq!(qualified_table_name(Some(DatabaseType::Mysql), Some("public"), "users"), "`public`.`users`");
assert_eq!(qualified_table_name(Some(DatabaseType::Goldendb), Some("public"), "users"), "`public`.`users`"); assert_eq!(qualified_table_name(Some(DatabaseType::Goldendb), Some("public"), "users"), "`public`.`users`");
assert_eq!(qualified_table_name(Some(DatabaseType::StarRocks), Some("warehouse"), "users"), "`warehouse`.`users`"); assert_eq!(qualified_table_name(Some(DatabaseType::StarRocks), Some("warehouse"), "users"), "`warehouse`.`users`");
@@ -244,6 +253,10 @@ fn builds_select_sql_with_limit_syntax_for_database_type() {
#[test] #[test]
fn builds_table_data_where_and_schema_queries() { fn builds_table_data_where_and_schema_queries() {
assert_eq!(
build_count_table_sql(Some(DatabaseType::Kingbase), Some("cqbq_ls"), "actionlogs"),
"SELECT COUNT(*) AS row_count FROM \"cqbq_ls\".\"actionlogs\""
);
assert_eq!( assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions { build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(DatabaseType::Mysql), database_type: Some(DatabaseType::Mysql),
@@ -298,6 +311,36 @@ fn builds_table_data_where_and_schema_queries() {
}), }),
"SELECT * FROM \"public\".\"orders\" WHERE (amount > 10) LIMIT 50 OFFSET 100;" "SELECT * FROM \"public\".\"orders\" WHERE (amount > 10) LIMIT 50 OFFSET 100;"
); );
assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(DatabaseType::Kingbase),
identifier_quote: Some("`".to_string()),
schema: Some("cqbq_ls".to_string()),
table_name: "actionlogs".to_string(),
table_type: None,
primary_keys: Vec::new(),
columns: Vec::new(),
fallback_order_columns: Vec::new(),
order_by: None,
limit: Some(100),
offset: None,
where_input: None,
include_row_id: false,
..Default::default()
}),
"SELECT * FROM `cqbq_ls`.`actionlogs` LIMIT 100;"
);
assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(DatabaseType::Kingbase),
identifier_quote: Some("\"".to_string()),
schema: Some("App Schema".to_string()),
table_name: "ANALYZE".to_string(),
limit: Some(100),
..Default::default()
}),
"SELECT * FROM \"App Schema\".\"ANALYZE\" LIMIT 100;"
);
assert_eq!( assert_eq!(
build_table_data_select_sql(TableDataSelectSqlOptions { build_table_data_select_sql(TableDataSelectSqlOptions {
database_type: Some(DatabaseType::Xugu), database_type: Some(DatabaseType::Xugu),
+2
View File
@@ -22,6 +22,8 @@ pub struct TableDataSelectSqlOptions {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub database_type: Option<DatabaseType>, pub database_type: Option<DatabaseType>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub identifier_quote: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<String>, pub schema: Option<String>,
pub table_name: String, pub table_name: String,
/// Doris / StarRocks multi-catalog: when set to a non-`internal` catalog, /// Doris / StarRocks multi-catalog: when set to a non-`internal` catalog,
+1
View File
@@ -222,6 +222,7 @@ async fn main() {
.route("/connection/final-proxy-port", post(routes::connection::connection_final_proxy_port)) .route("/connection/final-proxy-port", post(routes::connection::connection_final_proxy_port))
.route("/connection/disconnect", post(routes::connection::disconnect_db)) .route("/connection/disconnect", post(routes::connection::disconnect_db))
.route("/connection/check-health", post(routes::connection::check_connection_health)) .route("/connection/check-health", post(routes::connection::check_connection_health))
.route("/connection/identifier-quote", post(routes::connection::connection_identifier_quote))
.route("/connection/close-database", post(routes::connection::close_database_connection)) .route("/connection/close-database", post(routes::connection::close_database_connection))
.route("/connection/save", post(routes::connection::save_connections)) .route("/connection/save", post(routes::connection::save_connections))
.route("/connection/list", get(routes::connection::load_connections)) .route("/connection/list", get(routes::connection::load_connections))
+19
View File
@@ -30,6 +30,13 @@ pub struct CloseDatabaseConnectionRequest {
pub database: String, pub database: String,
} }
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionIdentifierQuoteRequest {
pub connection_id: String,
pub database: Option<String>,
}
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct SaveConnectionsRequest { pub struct SaveConnectionsRequest {
@@ -133,6 +140,18 @@ pub async fn check_connection_health(
Ok(Json(())) Ok(Json(()))
} }
pub async fn connection_identifier_quote(
State(state): State<Arc<WebState>>,
Json(body): Json<ConnectionIdentifierQuoteRequest>,
) -> Result<Json<Option<String>>, AppError> {
state
.app
.connection_identifier_quote(&body.connection_id, body.database.as_deref())
.await
.map(Json)
.map_err(AppError)
}
pub async fn close_database_connection( pub async fn close_database_connection(
State(state): State<Arc<WebState>>, State(state): State<Arc<WebState>>,
Json(body): Json<CloseDatabaseConnectionRequest>, Json(body): Json<CloseDatabaseConnectionRequest>,
+9
View File
@@ -1245,6 +1245,15 @@ pub async fn check_connection_health(state: State<'_, Arc<AppState>>, connection
state.check_connection_health(&connection_id).await state.check_connection_health(&connection_id).await
} }
#[tauri::command]
pub async fn connection_identifier_quote(
state: State<'_, Arc<AppState>>,
connection_id: String,
database: Option<String>,
) -> Result<Option<String>, String> {
state.connection_identifier_quote(&connection_id, database.as_deref()).await
}
/// Check whether a connection has read-only protection enabled. /// Check whether a connection has read-only protection enabled.
/// Returns an error if the connection is read-only, preventing write operations. /// Returns an error if the connection is read-only, preventing write operations.
pub async fn ensure_connection_writable( pub async fn ensure_connection_writable(
+1
View File
@@ -915,6 +915,7 @@ pub fn run() {
commands::connection::close_database_connection, commands::connection::close_database_connection,
commands::connection::refresh_connections, commands::connection::refresh_connections,
commands::connection::check_connection_health, commands::connection::check_connection_health,
commands::connection::connection_identifier_quote,
commands::connection::save_connections, commands::connection::save_connections,
commands::connection::load_connections, commands::connection::load_connections,
commands::connection::save_sidebar_layout, commands::connection::save_sidebar_layout,