feat(execution): multi-database SQL execution with scoped targets
This commit is contained in:
1 parent
328a2aa107
commit
71ccb3d97d
46 files changed
+4421
-182
No files matched your search
@@ -6,6 +6,7 @@ import { useConnectionStore } from "@/stores/connectionStore";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import { useToast } from "@/composables/useToast";
|
||||
import { isSingleDatabase, usesTreeSchemaMode } from "@/lib/database/databaseCapabilities";
|
||||
import { supportsConnectionScopedQueryExecution } from "@/lib/database/databaseFeatureSupport";
|
||||
import { supportsConnectionLevelSqlExecution } from "@/lib/connection/connectionLevelDatabaseBootstrap";
|
||||
import { classifySqlActivityKind } from "@/lib/history/historyActivityKind";
|
||||
import { sqlMetadataRefreshTarget } from "@/lib/sql/sqlMetadataRefresh";
|
||||
@@ -19,7 +20,11 @@ import { expandSqlVariables } from "@/lib/sql/sqlVariables";
|
||||
import { enabledSqlParameterSyntaxes, resolveSqlVariableSyntaxToggles } from "@/lib/sql/sqlVariableSyntax";
|
||||
import { assessProductionSql } from "@/lib/database/productionSafety";
|
||||
import { useProductionSafetyStore } from "@/stores/productionSafetyStore";
|
||||
import type { SqlExecutionDangerRequest } from "@/stores/sqlExecutionDangerStore";
|
||||
import type { ConnectionConfig, DatabaseType, QueryTab } from "@/types/database";
|
||||
import type { MultiDbExecutionTarget, MultiDbResultRunExecution, MultiDbTargetExecutionResult } from "@/types/sqlExecution";
|
||||
import { effectiveDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
|
||||
import type { SqlExecutionTargetContext } from "@/lib/database/sqlExecutionTargetRegistry";
|
||||
|
||||
const DANGER_RE = /^\s*(DROP|DELETE|TRUNCATE|ALTER|UPDATE|MERGE|REPLACE)\b/i;
|
||||
|
||||
@@ -27,6 +32,24 @@ interface SqlExecutionOptions {
|
||||
openInNewResultTab?: boolean;
|
||||
}
|
||||
|
||||
interface TargetSqlExecutionInput {
|
||||
tab: QueryTab;
|
||||
connection: ConnectionConfig;
|
||||
sql: string;
|
||||
executionTarget?: MultiDbExecutionTarget;
|
||||
resultRun?: {
|
||||
batchId: string;
|
||||
title: string;
|
||||
target: MultiDbExecutionTarget;
|
||||
};
|
||||
sourceOffset?: number;
|
||||
blockDangerousRedisCommands?: boolean;
|
||||
targetLabel?: string;
|
||||
scopeId?: string;
|
||||
isCancellationRequested?: () => boolean;
|
||||
targetContext?: SqlExecutionTargetContext;
|
||||
}
|
||||
|
||||
export function stripSqlComments(sql: string): string {
|
||||
return sql
|
||||
.replace(/\/\*[\s\S]*?\*\//g, " ")
|
||||
@@ -80,6 +103,7 @@ export function useSqlExecution(deps: {
|
||||
activeOutputView: Ref<"result" | "summary" | "explain" | "chart" | "messages">;
|
||||
blockDangerousRedisCommands?: Ref<boolean>;
|
||||
onMissingDatabase?: () => void;
|
||||
requestDangerConfirmation?: (request: SqlExecutionDangerRequest) => Promise<boolean>;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const queryStore = useQueryStore();
|
||||
@@ -103,6 +127,7 @@ export function useSqlExecution(deps: {
|
||||
const pendingDangerKind = ref<"sql" | "redis">("sql");
|
||||
const pendingDangerSourceOffset = ref<number | undefined>();
|
||||
const pendingOpenInNewResultTab = ref(false);
|
||||
let pendingSqlParameterContinuation: ((sql: string, sourceOffset?: number) => Promise<void> | void) | undefined;
|
||||
|
||||
async function resolvedExecutableSql(source?: SqlExecutionOverride): Promise<{ sql: string; sourceOffset?: number }> {
|
||||
const atSetEnabled = resolveSqlVariableSyntaxToggles(settingsStore.editorSettings.sqlVariableSyntaxOverrides, deps.activeConnection.value?.db_type).atSet;
|
||||
@@ -192,7 +217,7 @@ export function useSqlExecution(deps: {
|
||||
}
|
||||
}
|
||||
|
||||
function prepareSqlParameterDialog(sql: string, sourceOffset?: number, options: SqlExecutionOptions = {}): boolean {
|
||||
function prepareSqlParameterDialog(sql: string, sourceOffset?: number, options: SqlExecutionOptions = {}, continuation?: (sql: string, sourceOffset?: number) => Promise<void> | void): boolean {
|
||||
const databaseType = deps.activeConnection.value?.db_type;
|
||||
const toggles = resolveSqlVariableSyntaxToggles(settingsStore.editorSettings.sqlVariableSyntaxOverrides, databaseType);
|
||||
const enabledSyntaxes = enabledSqlParameterSyntaxes(toggles);
|
||||
@@ -204,10 +229,20 @@ export function useSqlExecution(deps: {
|
||||
sqlParameterEnabledSyntaxes.value = enabledSyntaxes;
|
||||
pendingSourceOffset.value = sourceOffset;
|
||||
pendingOpenInNewResultTab.value = options.openInNewResultTab === true;
|
||||
pendingSqlParameterContinuation = continuation;
|
||||
showSqlParameterDialog.value = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
async function prepareMultiExecute(onReady: (sql: string, sourceOffset?: number) => Promise<void> | void): Promise<boolean> {
|
||||
const tab = deps.activeTab.value;
|
||||
const { sql, sourceOffset } = await resolvedExecutableSql();
|
||||
if (!tab || !sql.trim()) return false;
|
||||
if (supportsSqlTemplateParameters(deps.activeConnection.value, sql) && prepareSqlParameterDialog(sql, sourceOffset, {}, onReady)) return true;
|
||||
await onReady(sql, sourceOffset);
|
||||
return false;
|
||||
}
|
||||
|
||||
async function doExecute(sql?: string, sourceOffset?: number, options: SqlExecutionOptions = {}) {
|
||||
if (sql === undefined) ({ sql, sourceOffset } = await resolvedExecutableSql());
|
||||
const tab = deps.activeTab.value;
|
||||
@@ -263,6 +298,161 @@ export function useSqlExecution(deps: {
|
||||
}
|
||||
}
|
||||
|
||||
async function executeTargetSql(input: TargetSqlExecutionInput): Promise<MultiDbTargetExecutionResult> {
|
||||
const { tab, connection, sql, sourceOffset, targetLabel } = input;
|
||||
const startedAt = Date.now();
|
||||
const executionTab = input.executionTarget
|
||||
? {
|
||||
...tab,
|
||||
connectionId: input.executionTarget.connectionId,
|
||||
catalog: input.executionTarget.catalog,
|
||||
database: input.executionTarget.database,
|
||||
schema: input.executionTarget.schema,
|
||||
}
|
||||
: tab;
|
||||
const finish = (result: MultiDbTargetExecutionResult): MultiDbTargetExecutionResult => ({
|
||||
...result,
|
||||
durationMs: Date.now() - startedAt,
|
||||
});
|
||||
const cancelRequested = () => input.isCancellationRequested?.() === true;
|
||||
const tabCancelRequested = (count: number) => (tab.cancelRequestCount ?? 0) !== count;
|
||||
if (cancelRequested()) return finish({ status: "cancelled" });
|
||||
if (!sql.trim()) return finish({ status: "failed", errorMessage: t("explain.emptySql") });
|
||||
if (requiresDatabaseSelection(executionTab, connection, sql)) {
|
||||
return finish({ status: "failed", errorMessage: t("editor.selectDatabaseRequired") });
|
||||
}
|
||||
|
||||
const blockRedisCommands = input.blockDangerousRedisCommands !== false;
|
||||
if (connection.db_type === "redis" && blockRedisCommands) {
|
||||
const commands = sql
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
let highestSafety: "allowed" | "confirm" | "blocked" = "allowed";
|
||||
for (const command of commands) {
|
||||
const safety = classifyRedisCommandSafety(command);
|
||||
if (safety === "blocked") {
|
||||
highestSafety = "blocked";
|
||||
break;
|
||||
}
|
||||
if (safety === "confirm") highestSafety = "confirm";
|
||||
}
|
||||
if (highestSafety === "blocked") {
|
||||
return finish({ status: "skipped", errorMessage: t("redis.blockedCommand", { command: "Redis" }) });
|
||||
}
|
||||
if (highestSafety === "confirm") {
|
||||
const confirmed = await deps.requestDangerConfirmation?.({
|
||||
sql,
|
||||
kind: "redis",
|
||||
connectionName: connection.name,
|
||||
database: executionTab.database,
|
||||
targetLabel,
|
||||
databaseType: connection.db_type,
|
||||
scopeId: input.scopeId,
|
||||
});
|
||||
if (cancelRequested()) return finish({ status: "cancelled" });
|
||||
if (!confirmed) return finish({ status: "skipped", errorMessage: t("dangerDialog.cancel") });
|
||||
}
|
||||
}
|
||||
|
||||
const productionAssessment = assessProductionSql(sql, connection, executionTab.database);
|
||||
if (productionAssessment.active && productionAssessment.isMutation) {
|
||||
const confirmed = await productionSafetyStore.requestConfirmation({
|
||||
sql,
|
||||
connectionName: connection.name,
|
||||
database: executionTab.database,
|
||||
productionDatabases: productionAssessment.databases,
|
||||
source: t("production.sourceMultiDbSql"),
|
||||
scopeId: input.scopeId,
|
||||
});
|
||||
if (cancelRequested()) return finish({ status: "cancelled" });
|
||||
if (!confirmed) return finish({ status: "skipped", errorMessage: t("dangerDialog.cancel") });
|
||||
}
|
||||
|
||||
if (isDangerousSql(sql, connection.db_type) && settingsStore.editorSettings.confirmDangerousSqlExecution) {
|
||||
const confirmed = await deps.requestDangerConfirmation?.({
|
||||
sql,
|
||||
kind: "sql",
|
||||
connectionName: connection.name,
|
||||
database: executionTab.database,
|
||||
targetLabel,
|
||||
databaseType: connection.db_type,
|
||||
scopeId: input.scopeId,
|
||||
});
|
||||
if (cancelRequested()) return finish({ status: "cancelled" });
|
||||
if (!confirmed) return finish({ status: "skipped", errorMessage: t("dangerDialog.cancel") });
|
||||
}
|
||||
|
||||
if (cancelRequested()) return finish({ status: "cancelled" });
|
||||
const cancelRequestCount = tab.cancelRequestCount ?? 0;
|
||||
const workerId = input.executionTarget ? queryStore.createMultiDbExecutionWorker(tab.id, input.executionTarget, input.scopeId ?? "") : undefined;
|
||||
if (input.executionTarget && !workerId) return finish({ status: "failed", errorMessage: t("multiDbExecute.targetMissingConnection") });
|
||||
const executionTabId = workerId ?? tab.id;
|
||||
const captureWorkerResult = (status: MultiDbResultRunExecution["status"], errorMessage?: string): string | undefined => {
|
||||
if (!workerId || !input.resultRun) return undefined;
|
||||
return queryStore.captureMultiDbExecutionWorkerResult(tab.id, workerId, sql, {
|
||||
kind: "multi-db",
|
||||
batchId: input.resultRun.batchId,
|
||||
target: input.resultRun.target,
|
||||
title: input.resultRun.title,
|
||||
status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
errorMessage,
|
||||
});
|
||||
};
|
||||
try {
|
||||
await queryStore.executeTabSql(executionTabId, sql, {
|
||||
resultBaseSql: sql,
|
||||
...(input.targetContext ? { targetContext: input.targetContext } : {}),
|
||||
...(sourceOffset !== undefined ? { sourceOffset } : {}),
|
||||
...(connection.db_type === "redis" ? { skipRedisSafetyCheck: !blockRedisCommands } : {}),
|
||||
});
|
||||
const latest = queryStore.getExecutionTab(executionTabId) ?? tab;
|
||||
if (cancelRequested() || tabCancelRequested(cancelRequestCount)) {
|
||||
return finish({ status: "cancelled" });
|
||||
}
|
||||
const failure = firstQueryExecutionError(latest);
|
||||
const errorMessage = failure ? String(failure.rows?.[0]?.[0] ?? t("common.failed")) : undefined;
|
||||
const success = !failure;
|
||||
const resultStatus = success ? "success" : "failed";
|
||||
captureWorkerResult(resultStatus, errorMessage);
|
||||
historyStore.add({
|
||||
connection_id: executionTab.connectionId,
|
||||
connection_name: connection.name || "",
|
||||
database: executionTab.database,
|
||||
sql,
|
||||
execution_time_ms: Date.now() - startedAt,
|
||||
success,
|
||||
error: errorMessage,
|
||||
activity_kind: classifySqlActivityKind(sql),
|
||||
operation: primarySqlOperation(sql),
|
||||
affected_rows: success ? latest.result?.affected_rows : undefined,
|
||||
});
|
||||
if (success) {
|
||||
const refreshTarget = sqlMetadataRefreshTarget(sql, executionTab.schema);
|
||||
if (refreshTarget.scope === "connection") {
|
||||
await connectionStore.loadDatabases(executionTab.connectionId, { force: true });
|
||||
} else if (refreshTarget.scope === "database") {
|
||||
await connectionStore.refreshObjectListTreeNode(executionTab.connectionId, executionTab.database, refreshTarget.schema);
|
||||
}
|
||||
}
|
||||
// 多库 worker 路径(workerId 存在)下不切主编辑器输出视图:并行 Promise.all
|
||||
// 会让多个 worker 几乎同时改这个共享 ref,导致主视图在 result/summary 间反复
|
||||
// 跳动(闪烁/竞态)。worker 结果已由 captureMultiDbExecutionWorkerResult 记录
|
||||
// 到 source tab 的 result run 并通过 projectResultRun 投影显示,无需再切主视图。
|
||||
if (!workerId) {
|
||||
deps.activeOutputView.value = success && (latest.result?.columns.length || latest.results?.some((result) => result.columns.length)) ? "result" : "summary";
|
||||
}
|
||||
return finish(success ? { status: "success", errorMessage } : { status: "failed", errorMessage });
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
captureWorkerResult("failed", errorMessage);
|
||||
return finish({ status: "failed", errorMessage });
|
||||
} finally {
|
||||
if (workerId) await queryStore.removeMultiDbExecutionWorker(workerId, input.scopeId);
|
||||
}
|
||||
}
|
||||
|
||||
function cancelActiveExecution() {
|
||||
const tab = deps.activeTab.value;
|
||||
if (!tab) return;
|
||||
@@ -321,7 +511,10 @@ export function useSqlExecution(deps: {
|
||||
const sourceOffset = pendingSourceOffset.value;
|
||||
pendingSourceOffset.value = undefined;
|
||||
pendingOpenInNewResultTab.value = false;
|
||||
await continueExecute(sql, sourceOffset, { openInNewResultTab });
|
||||
const continuation = pendingSqlParameterContinuation;
|
||||
pendingSqlParameterContinuation = undefined;
|
||||
if (continuation) await continuation(sql, sourceOffset);
|
||||
else await continueExecute(sql, sourceOffset, { openInNewResultTab });
|
||||
}
|
||||
|
||||
watch(showSqlParameterDialog, (open) => {
|
||||
@@ -332,6 +525,7 @@ export function useSqlExecution(deps: {
|
||||
sqlParameterEnabledSyntaxes.value = [];
|
||||
pendingSourceOffset.value = undefined;
|
||||
pendingOpenInNewResultTab.value = false;
|
||||
pendingSqlParameterContinuation = undefined;
|
||||
});
|
||||
|
||||
watch(showDangerDialog, (open) => {
|
||||
@@ -360,6 +554,8 @@ export function useSqlExecution(deps: {
|
||||
sqlParameterDatabaseType,
|
||||
sqlParameterEnabledSyntaxes,
|
||||
onSqlParametersConfirm,
|
||||
prepareMultiExecute,
|
||||
executeTargetSql,
|
||||
explainMode,
|
||||
};
|
||||
}
|
||||
@@ -373,11 +569,12 @@ export function supportsSqlTemplateParameters(connection: Pick<ConnectionConfig,
|
||||
export function requiresDatabaseSelection(tab: QueryTab, connection: ConnectionConfig | undefined, _sql = ""): boolean {
|
||||
if (tab.mode !== "query") return false;
|
||||
if (!connection) return false;
|
||||
const databaseType = effectiveDatabaseTypeForConnection(connection) ?? connection.db_type;
|
||||
if (tab.database) return false;
|
||||
if (tab.database === "" && usesTreeSchemaMode(connection.db_type)) return false;
|
||||
if (isSingleDatabase(connection.db_type)) return false;
|
||||
if (tab.database === "" && usesTreeSchemaMode(databaseType)) return false;
|
||||
if (isSingleDatabase(databaseType)) return false;
|
||||
// MySQL-compatible servers decide per statement whether a default database is required.
|
||||
// Keep interactive execution connection-scoped instead of rejecting valid qualified or constant queries.
|
||||
if (supportsConnectionLevelSqlExecution(connection)) return false;
|
||||
return !["elasticsearch", "easysearch", "qdrant", "milvus", "weaviate", "chromadb", "zookeeper"].includes(connection.db_type);
|
||||
return !supportsConnectionScopedQueryExecution(databaseType);
|
||||
}
|
||||
Reference in new issue
Block a user