25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(objects): add procedure execution dialog
t8y27ab7b8e0f365
diff --git a/apps/desktop/src/components/objects/ObjectBrowser.vue b/apps/desktop/src/components/objects/ObjectBrowser.vueindex 7c29ff14df..b9d7fa18fe 100644--- a/apps/desktop/src/components/objects/ObjectBrowser.vue+++ b/apps/desktop/src/components/objects/ObjectBrowser.vue@@ -23,6 +23,7 @@ import {Pencil,PencilLine,PencilRuler,+ Play,RefreshCw,Scissors,Search,@@ -39,6 +40,7 @@ import { Input } from "@/components/ui/input";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";+import ProcedureExecutionDialog from "@/components/objects/ProcedureExecutionDialog.vue";import * as api from "@/lib/api";import type { ConnectionConfig, ObjectInfo, ObjectSourceKind } from "@/types/database";import { isSchemaAware } from "@/lib/databaseCapabilities";@@ -143,6 +145,8 @@ const emptyPreviewSql = ref("");const showDuplicateDialog = ref(false);const duplicateTarget = ref<ObjectBrowserRow | null>(null);const duplicateTableName = ref("");+const showProcedureExecutionConfirm = ref(false);+const procedureExecutionTarget = ref<ObjectBrowserRow | null>(null);const selectedTableIds = ref<Set<string>>(new Set());const expandedPartitionParentIds = ref<Set<string>>(new Set());const showBatchDropConfirm = ref(false);@@ -406,6 +410,29 @@ async function openNewQuery(row: ObjectBrowserRow) {);}+function openProcedureExecution(row: ObjectBrowserRow) {+ if (row.type !== "PROCEDURE") return;+ procedureExecutionTarget.value = row;+ showProcedureExecutionConfirm.value = true;+}++function openProcedureExecutionSql(sql: string) {+ const row = procedureExecutionTarget.value;+ if (!row || !sql) return;+ const schema = row.schema || selectedSchema.value;+ const tabId = queryStore.createTab(props.connection.id, props.database, `Execute - ${row.name}`, "query", schema);+ queryStore.updateSql(tabId, sql);+}++async function executeProcedureSql(sql: string) {+ const row = procedureExecutionTarget.value;+ if (!row || !sql) return;+ const schema = row.schema || selectedSchema.value;+ const tabId = queryStore.createTab(props.connection.id, props.database, `Execute - ${row.name}`, "query", schema);+ queryStore.updateSql(tabId, sql);+ await queryStore.executeTabSql(tabId, sql);+}+function requestDrop(row: ObjectBrowserRow) {dropTarget.value = row;showDropConfirm.value = true;@@ -1152,6 +1179,7 @@ function getTableMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {function getViewMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {return [{ label: t("contextMenu.viewData"), action: () => openViewData(item), icon: Table2 },+ { label: t("contextMenu.editView"), action: () => openSource(item), icon: PencilLine },{ label: t("contextMenu.viewSource"), action: () => openSource(item), icon: Code2 },{ label: t("contextMenu.viewDdl"), action: () => openViewDdl(item), icon: ScrollText },...(canRename(item)@@ -1177,6 +1205,9 @@ function getViewMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {function getProcFuncMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {return [+ ...(item.type === "PROCEDURE"+ ? [{ label: t("contextMenu.executeProcedure"), action: () => openProcedureExecution(item), icon: Play }]+ : []),{ label: t("contextMenu.viewSource"), action: () => openSource(item), icon: Code2 },...(canRename(item)? [{ label: t("contextMenu.renameObject"), action: () => requestRename(item), icon: Pencil }]@@ -1558,6 +1589,18 @@ function getObjectBrowserMenuItems(item: ObjectBrowserRow): ContextMenuItem[] {@confirm="confirmEmptyTable"/>+ <ProcedureExecutionDialog+ v-if="procedureExecutionTarget"+ v-model:open="showProcedureExecutionConfirm"+ :connection-id="props.connection.id"+ :database="props.database"+ :database-type="props.connection.db_type"+ :schema="procedureExecutionTarget.schema || selectedSchema"+ :routine-name="procedureExecutionTarget.name"+ @open-sql="openProcedureExecutionSql"+ @execute="executeProcedureSql"+ />+<Dialog v-model:open="showDuplicateDialog"><DialogContent class="sm:max-w-[400px]"><DialogHeader>diff --git a/apps/desktop/src/components/objects/ProcedureExecutionDialog.vue b/apps/desktop/src/components/objects/ProcedureExecutionDialog.vuenew file mode 100644index 0000000000..6d80fd3c54--- /dev/null+++ b/apps/desktop/src/components/objects/ProcedureExecutionDialog.vue@@ -0,0 +1,276 @@+<script setup lang="ts">+import { computed, ref, watch } from "vue";+import { CircleHelp, Loader2 } from "lucide-vue-next";+import { useI18n } from "vue-i18n";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import LightTooltip from "@/components/ui/LightTooltip.vue";+import { loadRoutineParameters } from "@/lib/routineParameters";+import {+ acceptsRoutineInput,+ buildProcedureExecutionSql,+ buildProcedureExecutionSqlFromValues,+ type RoutineParameterValue,+} from "@/lib/routineExecutionSql";+import type { DatabaseType } from "@/types/database";++const { t } = useI18n();++const open = defineModel<boolean>("open", { default: false });++const props = defineProps<{+ connectionId: string;+ database: string;+ databaseType?: DatabaseType;+ schema?: string;+ routineName: string;+}>();++const emit = defineEmits<{+ execute: [sql: string];+ openSql: [sql: string];+}>();++const loading = ref(false);+const loadError = ref("");+const parameters = ref<RoutineParameterValue[]>([]);+const sqlDraft = ref("");+const manualSqlDirty = ref(false);+let loadToken = 0;++const generatedSql = computed(() => {+ if (parameters.value.length) {+ return buildProcedureExecutionSqlFromValues({+ databaseType: props.databaseType,+ schema: props.schema,+ routineName: props.routineName,+ parameters: parameters.value,+ });+ }+ return buildProcedureExecutionSql({+ databaseType: props.databaseType,+ schema: props.schema,+ routineName: props.routineName,+ });+});++const inputParameterCount = computed(() => parameters.value.filter(acceptsRoutineInput).length);+const outputParameterCount = computed(() => parameters.value.filter((parameter) => parameter.mode === "OUT").length);++watch(+ () => [open.value, props.connectionId, props.database, props.databaseType, props.schema, props.routineName] as const,+ ([isOpen]) => {+ if (!isOpen || !props.connectionId || !props.database || !props.routineName) return;+ void refreshParameters();+ },+ { immediate: true },+);++watch(+ generatedSql,+ (sql) => {+ if (!manualSqlDirty.value) sqlDraft.value = sql;+ },+ { immediate: true },+);++async function refreshParameters() {+ const token = ++loadToken;+ loading.value = true;+ loadError.value = "";+ parameters.value = [];+ manualSqlDirty.value = false;+ sqlDraft.value = generatedSql.value;+ try {+ const loaded = await loadRoutineParameters({+ connectionId: props.connectionId,+ database: props.database,+ databaseType: props.databaseType,+ schema: props.schema,+ routineName: props.routineName,+ });+ if (token !== loadToken) return;+ parameters.value = loaded.map((parameter) => ({+ ...parameter,+ value: "",+ useNull: false,+ useDefault: !!parameter.hasDefault,+ }));+ sqlDraft.value = generatedSql.value;+ } catch (e: any) {+ if (token !== loadToken) return;+ loadError.value = e?.message || String(e);+ sqlDraft.value = generatedSql.value;+ } finally {+ if (token === loadToken) loading.value = false;+ }+}++function onSqlInput(event: Event) {+ manualSqlDirty.value = true;+ sqlDraft.value = (event.target as HTMLTextAreaElement).value;+}++function resetSqlPreview() {+ manualSqlDirty.value = false;+ sqlDraft.value = generatedSql.value;+}++function close() {+ open.value = false;+}++function openSql() {+ const sql = sqlDraft.value.trim();+ if (!sql) return;+ close();+ emit("openSql", sql);+}++function execute() {+ const sql = sqlDraft.value.trim();+ if (!sql) return;+ close();+ emit("execute", sql);+}++function canEditParameter(parameter: RoutineParameterValue): boolean {+ return acceptsRoutineInput(parameter);+}+</script>++<template>+ <Dialog v-model:open="open">+ <DialogContent+ class="max-h-[86vh] border border-border !bg-background text-foreground shadow-2xl !backdrop-blur-none sm:max-w-[780px]"+ >+ <DialogHeader>+ <DialogTitle>{{ t("contextMenu.confirmExecuteProcedureTitle") }}</DialogTitle>+ </DialogHeader>++ <div class="grid max-h-[calc(86vh-8rem)] gap-4 overflow-y-auto pr-1">+ <div class="flex min-w-0 items-start justify-between gap-3">+ <div class="min-w-0 space-y-1">+ <p class="truncate text-sm text-muted-foreground">+ {{ t("contextMenu.confirmExecuteProcedureMessage", { name: props.routineName }) }}+ </p>+ <p class="truncate font-mono text-xs text-muted-foreground">+ {{ props.schema ? `${props.schema}.${props.routineName}` : props.routineName }}+ </p>+ </div>+ <div class="flex shrink-0 items-center gap-2">+ <Badge v-if="inputParameterCount" variant="outline">+ {{ t("contextMenu.inputParameters", { count: inputParameterCount }) }}+ </Badge>+ <Badge v-if="outputParameterCount" variant="outline">+ {{ t("contextMenu.outputParameters", { count: outputParameterCount }) }}+ </Badge>+ </div>+ </div>++ <div+ v-if="loading"+ class="flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2 text-sm text-muted-foreground"+ >+ <Loader2 class="h-4 w-4 animate-spin" />+ {{ t("contextMenu.loadingProcedureParameters") }}+ </div>++ <div v-else-if="parameters.length" class="overflow-x-auto rounded-md border bg-background">+ <div class="min-w-[650px]">+ <div+ class="grid grid-cols-[minmax(120px,1.2fr)_minmax(96px,1fr)_72px_minmax(160px,1.5fr)_64px_86px] border-b bg-muted px-3 py-2 text-xs font-medium text-muted-foreground"+ >+ <div>{{ t("contextMenu.parameterName") }}</div>+ <div>{{ t("contextMenu.parameterType") }}</div>+ <div>{{ t("contextMenu.parameterMode") }}</div>+ <div>{{ t("contextMenu.parameterValue") }}</div>+ <div>{{ t("contextMenu.parameterNull") }}</div>+ <div class="flex items-center gap-1">+ {{ t("contextMenu.parameterDefault") }}+ <LightTooltip :text="t('contextMenu.parameterDefaultHint')" side="top" :delay="150">+ <button+ type="button"+ class="inline-flex h-4 w-4 items-center justify-center rounded-full text-muted-foreground hover:bg-background hover:text-foreground"+ :aria-label="t('contextMenu.parameterDefaultHint')"+ >+ <CircleHelp class="h-3.5 w-3.5" />+ </button>+ </LightTooltip>+ </div>+ </div>+ <div+ v-for="parameter in parameters"+ :key="`${parameter.ordinal}:${parameter.name}`"+ class="grid grid-cols-[minmax(120px,1.2fr)_minmax(96px,1fr)_72px_minmax(160px,1.5fr)_64px_86px] items-center gap-2 border-b px-3 py-2 text-sm last:border-b-0"+ >+ <div class="min-w-0 truncate font-medium">{{ parameter.name }}</div>+ <div class="min-w-0 truncate text-muted-foreground">{{ parameter.dataType || "-" }}</div>+ <div class="text-xs text-muted-foreground">{{ parameter.mode }}</div>+ <Input+ v-model="parameter.value"+ class="h-8 bg-background font-mono text-xs"+ :disabled="!canEditParameter(parameter) || parameter.useNull || parameter.useDefault"+ :placeholder="+ canEditParameter(parameter) ? t('contextMenu.parameterValuePlaceholder') : t('contextMenu.outputOnly')+ "+ />+ <input+ type="checkbox"+ class="h-4 w-4 accent-primary"+ :checked="!!parameter.useNull"+ :disabled="!canEditParameter(parameter) || parameter.useDefault"+ @change="(event: Event) => (parameter.useNull = (event.target as HTMLInputElement).checked)"+ />+ <input+ type="checkbox"+ class="h-4 w-4 accent-primary"+ :checked="!!parameter.useDefault"+ :disabled="!canEditParameter(parameter) || !parameter.hasDefault || parameter.useNull"+ @change="(event: Event) => (parameter.useDefault = (event.target as HTMLInputElement).checked)"+ />+ </div>+ </div>+ </div>++ <p+ v-else-if="loadError"+ class="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800"+ >+ {{ t("contextMenu.procedureParametersUnavailable") }}+ </p>++ <p v-else class="rounded-md border bg-muted/30 px-3 py-2 text-sm text-muted-foreground">+ {{ t("contextMenu.noProcedureParameters") }}+ </p>++ <div class="grid gap-2">+ <div class="flex items-center justify-between gap-2">+ <div class="text-xs font-medium text-muted-foreground">{{ t("contextMenu.sqlPreview") }}</div>+ <Button v-if="manualSqlDirty" variant="ghost" size="sm" class="h-7 px-2 text-xs" @click="resetSqlPreview">+ {{ t("contextMenu.resetSqlPreview") }}+ </Button>+ </div>+ <textarea+ :value="sqlDraft"+ class="min-h-28 w-full resize-y rounded-md border border-input bg-background px-3 py-2 font-mono text-xs outline-none transition-colors focus:border-ring focus:ring-1 focus:ring-ring/40"+ spellcheck="false"+ @input="onSqlInput"+ ></textarea>+ </div>+ </div>++ <DialogFooter>+ <Button variant="outline" @click="close">{{ t("dangerDialog.cancel") }}</Button>+ <Button variant="outline" :disabled="!sqlDraft.trim()" @click="openSql">+ {{ t("contextMenu.openInSqlEditor") }}+ </Button>+ <Button :disabled="!sqlDraft.trim()" @click="execute">+ {{ t("contextMenu.executeProcedure") }}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+</template>diff --git a/apps/desktop/src/components/sidebar/TreeItem.vue b/apps/desktop/src/components/sidebar/TreeItem.vueindex a50324e229..ec68bd6a87 100644--- a/apps/desktop/src/components/sidebar/TreeItem.vue+++ b/apps/desktop/src/components/sidebar/TreeItem.vue@@ -23,6 +23,7 @@ import {Zap,ListTree,Pencil,+ Play,Plug,Unplug,Pin,@@ -113,6 +114,7 @@ import { focusSidebarRenameInput } from "@/lib/sidebarRenameFocus";import { hasTreeNodeDatabaseContext } from "@/lib/treeNodeContext";import { sidebarDisplayTableName } from "@/lib/sidebarTableNameDisplay";import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";+import ProcedureExecutionDialog from "@/components/objects/ProcedureExecutionDialog.vue";import { isTauriRuntime } from "@/lib/tauriRuntime";import { copyToClipboard } from "@/lib/clipboard";import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";@@ -714,6 +716,7 @@ const showDropSchemaConfirm = ref(false);// --- Procedure / Function Management ---const showDropObjectConfirm = ref(false);+const showProcedureExecutionConfirm = ref(false);function dropObjectSqlOptions(): DropObjectSqlOptions | null {const node = props.node;@@ -784,6 +787,27 @@ function viewObjectDdl() {});}+function openProcedureExecution() {+ const node = props.node;+ if (node.type !== "procedure" || !node.connectionId || !node.database) return;+ showProcedureExecutionConfirm.value = true;+}++function openProcedureExecutionSql(sql: string) {+ const node = props.node;+ if (node.type !== "procedure" || !node.connectionId || !node.database || !sql) return;+ const tabId = queryStore.createTab(node.connectionId, node.database, `Execute - ${node.label}`, "query", node.schema);+ queryStore.updateSql(tabId, sql);+}++async function executeProcedureSql(sql: string) {+ const node = props.node;+ if (node.type !== "procedure" || !node.connectionId || !node.database || !sql) return;+ const tabId = queryStore.createTab(node.connectionId, node.database, `Execute - ${node.label}`, "query", node.schema);+ queryStore.updateSql(tabId, sql);+ await queryStore.executeTabSql(tabId, sql);+}+function requestDropObject() {void refreshDropObjectPreviewSql();showDropObjectConfirm.value = true;@@ -2138,6 +2162,7 @@ function treeItemMenuItems(): ContextMenuItem[] {items.push({ label: "", separator: true });items.push({ label: t("contextMenu.viewData"), action: openData, icon: TableProperties });if (node.type === "view") {+ items.push({ label: t("contextMenu.editView"), action: viewObjectSource, icon: Pencil });items.push({ label: t("contextMenu.viewSource"), action: viewObjectSource, icon: Code2 });items.push({ label: t("contextMenu.viewDdl"), action: viewObjectDdl, icon: FileCode });}@@ -2201,6 +2226,9 @@ function treeItemMenuItems(): ContextMenuItem[] {// 8. Procedure / Functionif (node.type === "procedure" || node.type === "function") {+ if (node.type === "procedure") {+ items.push({ label: t("contextMenu.executeProcedure"), action: openProcedureExecution, icon: Play });+ }items.push({ label: t("contextMenu.viewSource"), action: viewObjectSource, icon: Code2 });if (canRenameObject.value) {items.push({ label: t("contextMenu.renameObject"), action: openRenameObjectDialog, icon: Pencil });@@ -2570,6 +2598,18 @@ function treeItemMenuItems(): ContextMenuItem[] {@confirm="confirmDropObject"/>+ <ProcedureExecutionDialog+ v-if="node.type === 'procedure' && node.connectionId && node.database"+ v-model:open="showProcedureExecutionConfirm"+ :connection-id="node.connectionId"+ :database="node.database"+ :database-type="currentDatabaseType()"+ :schema="node.schema"+ :routine-name="node.label"+ @open-sql="openProcedureExecutionSql"+ @execute="executeProcedureSql"+ />+<Dialog v-model:open="showDuplicateDialog"><DialogContent class="sm:max-w-[400px]"><DialogHeader>diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex f6c6d58534..6e482a7627 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -910,9 +910,32 @@ export default {confirmTruncateTableTitle: "Truncate Table",confirmTruncateTableMessage: 'Are you sure you want to truncate "{name}"? This will remove all rows.',dropTableSuccess: 'Table "{name}" dropped',+ editView: "Edit View",viewSource: "View Source",viewDdl: "View DDL",dropView: "Drop View",+ executeProcedure: "Execute Procedure",+ confirmExecuteProcedureTitle: "Execute Procedure",+ confirmExecuteProcedureMessage: 'Execute procedure "{name}"? You can fill or adjust parameter values first.',+ loadingProcedureParameters: "Loading parameters...",+ procedureParametersUnavailable:+ "Could not load parameter metadata. You can still edit the SQL below and execute it.",+ noProcedureParameters: "No parameters were found. The current SQL will be executed as shown.",+ inputParameters: "{count} input parameters",+ outputParameters: "{count} output parameters",+ parameterName: "Name",+ parameterType: "Type",+ parameterMode: "Mode",+ parameterValue: "Value",+ parameterNull: "NULL",+ parameterDefault: "DEFAULT",+ parameterDefaultHint:+ "When DEFAULT is checked, DBX omits that argument so the database uses the procedure default.",+ parameterValuePlaceholder: "Enter value",+ outputOnly: "Output only",+ sqlPreview: "SQL Preview",+ resetSqlPreview: "Reset SQL",+ openInSqlEditor: "Open in Editor",dropProcedure: "Drop Procedure",dropFunction: "Drop Function",confirmDropViewTitle: "Drop View",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 8533698750..ddff6db931 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -807,9 +807,33 @@ export default {confirmTruncateTableTitle: "Truncar tabla",confirmTruncateTableMessage: '¿Estás seguro de que deseas truncar "{name}"? Esto eliminará todas las filas.',dropTableSuccess: 'Tabla "{name}" eliminada',+ editView: "Editar vista",viewSource: "Ver código fuente",viewDdl: "Ver DDL",dropView: "Eliminar vista",+ executeProcedure: "Ejecutar procedimiento",+ confirmExecuteProcedureTitle: "Ejecutar procedimiento",+ confirmExecuteProcedureMessage:+ '¿Ejecutar el procedimiento "{name}"? Puedes completar o ajustar los valores de los parámetros primero.',+ loadingProcedureParameters: "Cargando parámetros...",+ procedureParametersUnavailable:+ "No se pudo cargar la metadata de parámetros. Aún puedes editar el SQL inferior y ejecutarlo.",+ noProcedureParameters: "No se encontraron parámetros. El SQL actual se ejecutará tal como se muestra.",+ inputParameters: "{count} parámetros de entrada",+ outputParameters: "{count} parámetros de salida",+ parameterName: "Name",+ parameterType: "Type",+ parameterMode: "Mode",+ parameterValue: "Value",+ parameterNull: "NULL",+ parameterDefault: "DEFAULT",+ parameterDefaultHint:+ "Cuando DEFAULT está marcado, DBX omite ese argumento para que la base de datos use el valor predeterminado.",+ parameterValuePlaceholder: "Ingresa un valor",+ outputOnly: "Solo salida",+ sqlPreview: "Vista previa SQL",+ resetSqlPreview: "Restablecer SQL",+ openInSqlEditor: "Abrir en editor",dropProcedure: "Eliminar procedimiento",dropFunction: "Eliminar función",confirmDropViewTitle: "Eliminar vista",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 84de4f89be..05781737a1 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -890,9 +890,30 @@ export default {confirmTruncateTableTitle: "截断表",confirmTruncateTableMessage: "确定要截断「{name}」吗?这将删除所有行。",dropTableSuccess: "表「{name}」已删除",+ editView: "编辑视图",viewSource: "查看源码",viewDdl: "查看 DDL",dropView: "删除视图",+ executeProcedure: "执行过程",+ confirmExecuteProcedureTitle: "执行存储过程",+ confirmExecuteProcedureMessage: "确认执行存储过程「{name}」?可先补充或调整参数值。",+ loadingProcedureParameters: "正在读取参数...",+ procedureParametersUnavailable: "未能读取参数信息,仍可直接编辑下方 SQL 后执行。",+ noProcedureParameters: "未读取到参数,确认后将直接执行当前 SQL。",+ inputParameters: "{count} 个输入参数",+ outputParameters: "{count} 个输出参数",+ parameterName: "Name",+ parameterType: "Type",+ parameterMode: "Mode",+ parameterValue: "Value",+ parameterNull: "NULL",+ parameterDefault: "DEFAULT",+ parameterDefaultHint: "勾选 DEFAULT 时会省略该参数,让数据库使用过程定义里的默认值。",+ parameterValuePlaceholder: "输入参数值",+ outputOnly: "输出参数",+ sqlPreview: "SQL 预览",+ resetSqlPreview: "重置 SQL",+ openInSqlEditor: "打开到编辑器",dropProcedure: "删除存储过程",dropFunction: "删除函数",confirmDropViewTitle: "删除视图",diff --git a/apps/desktop/src/lib/routineExecutionSql.ts b/apps/desktop/src/lib/routineExecutionSql.tsnew file mode 100644index 0000000000..6a0303dcd2--- /dev/null+++ b/apps/desktop/src/lib/routineExecutionSql.ts@@ -0,0 +1,147 @@+import type { DatabaseType } from "@/types/database";+import { isSchemaAware } from "./databaseCapabilities";+import { quoteTableIdentifier } from "./tableSelectSql";++export interface BuildRoutineExecutionSqlOptions {+ databaseType?: DatabaseType;+ schema?: string;+ routineName: string;+}++export type RoutineParameterMode = "IN" | "OUT" | "INOUT" | "RETURN" | "UNKNOWN";++export interface RoutineParameter {+ name: string;+ dataType: string;+ mode: RoutineParameterMode;+ ordinal: number;+ hasDefault?: boolean;+ defaultValue?: string | null;+}++export interface RoutineParameterValue extends RoutineParameter {+ value: string;+ useNull?: boolean;+ useDefault?: boolean;+}++export function qualifiedRoutineName(options: BuildRoutineExecutionSqlOptions): string {+ const { databaseType, schema, routineName } = options;+ if (isSchemaAware(databaseType) && schema) {+ return `${quoteTableIdentifier(databaseType, schema)}.${quoteTableIdentifier(databaseType, routineName)}`;+ }+ return quoteTableIdentifier(databaseType, routineName);+}++export function buildProcedureExecutionSql(options: BuildRoutineExecutionSqlOptions): string {+ return buildProcedureExecutionSqlFromValues({ ...options, parameters: [] });+}++export function buildProcedureExecutionSqlFromValues(+ options: BuildRoutineExecutionSqlOptions & { parameters: RoutineParameterValue[] },+): string {+ const routine = qualifiedRoutineName(options);+ const sortedParameters = [...options.parameters].sort((a, b) => a.ordinal - b.ordinal);+ const values = sortedParameters.filter((parameter) => shouldIncludeParameter(parameter));+ const useNamedArguments = shouldUseNamedArguments(options.databaseType, sortedParameters);+ if (options.databaseType === "sqlserver") {+ const args = values+ .map(+ (parameter) =>+ `${sqlServerParameterName(parameter.name)} = ${routineParameterSqlValue(options.databaseType, parameter)}`,+ )+ .join(", ");+ return args ? `EXEC ${routine} ${args};` : `EXEC ${routine};`;+ }+ if (+ options.databaseType === "oracle" ||+ options.databaseType === "dameng" ||+ options.databaseType === "oceanbase-oracle"+ ) {+ return `BEGIN\n ${routine}(${values.map((parameter) => routineArgumentSql(options.databaseType, parameter, useNamedArguments)).join(", ")});\nEND;`;+ }+ return `CALL ${routine}(${values.map((parameter) => routineArgumentSql(options.databaseType, parameter, useNamedArguments)).join(", ")});`;+}++export function shouldIncludeParameter(parameter: RoutineParameterValue): boolean {+ if (parameter.useDefault && parameter.hasDefault) return false;+ return acceptsRoutineInput(parameter);+}++export function acceptsRoutineInput(parameter: Pick<RoutineParameterValue, "mode">): boolean {+ return parameter.mode === "IN" || parameter.mode === "INOUT" || parameter.mode === "UNKNOWN";+}++export function routineParameterSqlValue(+ databaseType: DatabaseType | undefined,+ parameter: RoutineParameterValue,+): string {+ if (parameter.useNull) return "NULL";+ const raw = parameter.value;+ if (raw.trim() === "") return "NULL";+ if (looksLikeNumericType(parameter.dataType)) return raw.trim();+ if (looksLikeBooleanType(parameter.dataType)) return normalizeBooleanLiteral(raw, databaseType);+ return quoteSqlString(raw);+}++function sqlServerParameterName(name: string): string {+ return name.startsWith("@") ? name : `@${name}`;+}++function routineArgumentSql(+ databaseType: DatabaseType | undefined,+ parameter: RoutineParameterValue,+ useNamedArguments: boolean,+): string {+ const value = routineParameterSqlValue(databaseType, parameter);+ if (!useNamedArguments) return value;+ return `${quoteTableIdentifier(databaseType, parameter.name)} => ${value}`;+}++function shouldUseNamedArguments(+ databaseType: DatabaseType | undefined,+ sortedParameters: RoutineParameterValue[],+): boolean {+ if (+ databaseType !== "postgres" &&+ databaseType !== "oracle" &&+ databaseType !== "dameng" &&+ databaseType !== "oceanbase-oracle"+ ) {+ return false;+ }+ let omittedDefault = false;+ for (const parameter of sortedParameters) {+ if (parameter.useDefault && parameter.hasDefault && acceptsRoutineInput(parameter)) {+ omittedDefault = true;+ continue;+ }+ if (omittedDefault && shouldIncludeParameter(parameter)) return sortedParameters.every((item) => !!item.name);+ }+ return false;+}++function quoteSqlString(value: string): string {+ return `'${value.replace(/'/g, "''")}'`;+}++function looksLikeNumericType(dataType: string): boolean {+ return /\b(bigint|int|integer|smallint|tinyint|serial|number|numeric|decimal|dec|float|double|real|money)\b/i.test(+ dataType,+ );+}++function looksLikeBooleanType(dataType: string): boolean {+ return /\b(bool|boolean|bit)\b/i.test(dataType);+}++function normalizeBooleanLiteral(value: string, databaseType: DatabaseType | undefined): string {+ const normalized = value.trim().toLowerCase();+ const truthy =+ normalized === "true" || normalized === "t" || normalized === "yes" || normalized === "y" || normalized === "1";+ const falsy =+ normalized === "false" || normalized === "f" || normalized === "no" || normalized === "n" || normalized === "0";+ if (!truthy && !falsy) return quoteSqlString(value);+ if (databaseType === "sqlserver") return truthy ? "1" : "0";+ return truthy ? "TRUE" : "FALSE";+}diff --git a/apps/desktop/src/lib/routineParameters.ts b/apps/desktop/src/lib/routineParameters.tsnew file mode 100644index 0000000000..da7d4e2dc6--- /dev/null+++ b/apps/desktop/src/lib/routineParameters.ts@@ -0,0 +1,168 @@+import * as api from "@/lib/api";+import type { DatabaseType, QueryResult } from "@/types/database";+import type { RoutineParameter, RoutineParameterMode } from "./routineExecutionSql";++export interface LoadRoutineParametersOptions {+ connectionId: string;+ database: string;+ databaseType?: DatabaseType;+ schema?: string;+ routineName: string;+}++export async function loadRoutineParameters(options: LoadRoutineParametersOptions): Promise<RoutineParameter[]> {+ const sql = routineParametersQuery(options);+ if (!sql) return [];+ const result = await api.executeQuery(options.connectionId, options.database, sql, options.schema, undefined, {+ maxRows: 200,+ pageSize: 200,+ });+ return routineParametersFromResult(result);+}++export function supportsRoutineParameterMetadata(databaseType?: DatabaseType): boolean {+ return (+ databaseType === "postgres" ||+ databaseType === "mysql" ||+ databaseType === "doris" ||+ databaseType === "starrocks" ||+ databaseType === "sqlserver" ||+ databaseType === "oracle" ||+ databaseType === "dameng" ||+ databaseType === "oceanbase-oracle"+ );+}++export function routineParametersQuery(+ options: Pick<LoadRoutineParametersOptions, "database" | "databaseType" | "schema" | "routineName">,+): string | null {+ if (!supportsRoutineParameterMetadata(options.databaseType)) return null;+ const effectiveSchema =+ options.schema ||+ (options.databaseType === "postgres" ? "public" : "") ||+ (options.databaseType === "mysql" || options.databaseType === "doris" || options.databaseType === "starrocks"+ ? options.database+ : "");+ const schema = quoteSqlLiteral(effectiveSchema);+ const name = quoteSqlLiteral(options.routineName);+ if (options.databaseType === "postgres") {+ return `+SELECT+ NULLIF(arg.name, '') AS name,+ arg.data_type,+ CASE arg.mode+ WHEN 'i' THEN 'IN'+ WHEN 'o' THEN 'OUT'+ WHEN 'b' THEN 'INOUT'+ WHEN 'v' THEN 'IN'+ WHEN 't' THEN 'OUT'+ ELSE 'IN'+ END AS mode,+ arg.ordinal,+ CASE+ WHEN COALESCE(arg.mode, 'i') IN ('i', 'b', 'v') AND p.pronargdefaults > 0 AND arg.input_ordinal > p.pronargs - p.pronargdefaults THEN TRUE+ ELSE FALSE+ END AS has_default+FROM pg_proc p+JOIN pg_namespace n ON n.oid = p.pronamespace+CROSS JOIN LATERAL (+ SELECT+ gs.ordinal AS ordinal,+ p.proargnames[gs.ordinal] AS name,+ CASE+ WHEN p.proallargtypes IS NULL THEN p.proargtypes[gs.ordinal - 1]+ ELSE p.proallargtypes[gs.ordinal]+ END::regtype::text AS data_type,+ COALESCE(p.proargmodes[gs.ordinal], 'i') AS mode,+ COUNT(*) FILTER (WHERE COALESCE(p.proargmodes[gs.ordinal], 'i') IN ('i', 'b', 'v')) OVER (ORDER BY gs.ordinal) AS input_ordinal+ FROM generate_series(1, COALESCE(array_length(p.proallargtypes, 1), p.pronargs)) AS gs(ordinal)+) arg+WHERE p.prokind = 'p'+ AND n.nspname = ${schema}+ AND p.proname = ${name}+ORDER BY arg.ordinal;`.trim();+ }+ if (options.databaseType === "mysql" || options.databaseType === "doris" || options.databaseType === "starrocks") {+ return `+SELECT+ PARAMETER_NAME AS name,+ DTD_IDENTIFIER AS data_type,+ COALESCE(PARAMETER_MODE, 'IN') AS mode,+ ORDINAL_POSITION AS ordinal,+ FALSE AS has_default+FROM information_schema.PARAMETERS+WHERE SPECIFIC_SCHEMA = ${schema}+ AND SPECIFIC_NAME = ${name}+ AND ORDINAL_POSITION > 0+ORDER BY ORDINAL_POSITION;`.trim();+ }+ if (options.databaseType === "sqlserver") {+ return `+SELECT+ p.name AS name,+ TYPE_NAME(p.user_type_id) AS data_type,+ CASE WHEN p.is_output = 1 THEN 'OUT' ELSE 'IN' END AS mode,+ p.parameter_id AS ordinal,+ p.has_default_value AS has_default+FROM sys.parameters p+JOIN sys.objects o ON o.object_id = p.object_id+JOIN sys.schemas s ON s.schema_id = o.schema_id+WHERE o.type IN ('P', 'PC')+ AND s.name = ${schema}+ AND o.name = ${name}+ORDER BY p.parameter_id;`.trim();+ }+ if (+ options.databaseType === "oracle" ||+ options.databaseType === "dameng" ||+ options.databaseType === "oceanbase-oracle"+ ) {+ return `+SELECT+ ARGUMENT_NAME AS name,+ DATA_TYPE AS data_type,+ IN_OUT AS mode,+ POSITION AS ordinal,+ DEFAULTED AS has_default+FROM ALL_ARGUMENTS+WHERE OWNER = UPPER(${schema})+ AND OBJECT_NAME = UPPER(${name})+ AND POSITION > 0+ORDER BY SEQUENCE;`.trim();+ }+ return null;+}++export function routineParametersFromResult(result: QueryResult): RoutineParameter[] {+ return result.rows+ .map((row, index) => ({+ name: String(row[0] || `arg${index + 1}`),+ dataType: String(row[1] || ""),+ mode: normalizeParameterMode(row[2]),+ ordinal: Number(row[3] || index + 1),+ hasDefault: normalizeBoolean(row[4]),+ }))+ .filter((parameter) => parameter.mode !== "RETURN");+}++function normalizeParameterMode(value: unknown): RoutineParameterMode {+ const mode = String(value || "IN")+ .toUpperCase()+ .replace(/\s+/g, "");+ if (mode === "IN") return "IN";+ if (mode === "OUT") return "OUT";+ if (mode === "INOUT" || mode === "IN/OUT") return "INOUT";+ if (mode === "RETURN") return "RETURN";+ return "UNKNOWN";+}++function normalizeBoolean(value: unknown): boolean {+ if (typeof value === "boolean") return value;+ if (typeof value === "number") return value !== 0;+ const text = String(value || "").toLowerCase();+ return text === "true" || text === "yes" || text === "y" || text === "1";+}++function quoteSqlLiteral(value: string): string {+ return `'${value.replace(/'/g, "''")}'`;+}diff --git a/packages/app-tests/routineExecutionSql.test.ts b/packages/app-tests/routineExecutionSql.test.tsnew file mode 100644index 0000000000..7421e3407b--- /dev/null+++ b/packages/app-tests/routineExecutionSql.test.ts@@ -0,0 +1,161 @@+import { strict as assert } from "node:assert";+import test from "node:test";+import {+ buildProcedureExecutionSql,+ buildProcedureExecutionSqlFromValues,+} from "../../apps/desktop/src/lib/routineExecutionSql.ts";+import { routineParametersFromResult, routineParametersQuery } from "../../apps/desktop/src/lib/routineParameters.ts";++test("builds procedure execution templates for common dialect families", () => {+ assert.equal(+ buildProcedureExecutionSql({ databaseType: "postgres", schema: "public", routineName: "refresh_stats" }),+ 'CALL "public"."refresh_stats"();',+ );+ assert.equal(+ buildProcedureExecutionSql({ databaseType: "mysql", schema: "app", routineName: "refresh_stats" }),+ "CALL `refresh_stats`();",+ );+ assert.equal(+ buildProcedureExecutionSql({ databaseType: "sqlserver", schema: "dbo", routineName: "refresh_stats" }),+ "EXEC [dbo].[refresh_stats];",+ );+ assert.equal(+ buildProcedureExecutionSql({ databaseType: "dameng", schema: "SYSDBA", routineName: "refresh_stats" }),+ 'BEGIN\n "SYSDBA"."refresh_stats"();\nEND;',+ );+});++test("builds procedure execution templates from parameter values", () => {+ const parameters = [+ { name: "p_message", dataType: "text", mode: "IN" as const, ordinal: 1, value: "it's ready" },+ { name: "p_count", dataType: "integer", mode: "IN" as const, ordinal: 2, value: "3" },+ { name: "p_debug", dataType: "boolean", mode: "IN" as const, ordinal: 3, value: "true" },+ { name: "p_result", dataType: "text", mode: "OUT" as const, ordinal: 4, value: "" },+ ];++ assert.equal(+ buildProcedureExecutionSqlFromValues({+ databaseType: "postgres",+ schema: "public",+ routineName: "refresh_stats",+ parameters,+ }),+ 'CALL "public"."refresh_stats"(' + "'it''s ready', 3, TRUE);",+ );++ assert.equal(+ buildProcedureExecutionSqlFromValues({+ databaseType: "sqlserver",+ schema: "dbo",+ routineName: "refresh_stats",+ parameters,+ }),+ "EXEC [dbo].[refresh_stats] @p_message = 'it''s ready', @p_count = 3, @p_debug = 1;",+ );+});++test("omits parameters that use database defaults", () => {+ assert.equal(+ buildProcedureExecutionSqlFromValues({+ databaseType: "postgres",+ schema: "public",+ routineName: "refresh_stats",+ parameters: [+ {+ name: "p_message",+ dataType: "text",+ mode: "IN",+ ordinal: 1,+ value: "",+ hasDefault: true,+ useDefault: true,+ },+ ],+ }),+ 'CALL "public"."refresh_stats"();',+ );+});++test("uses named arguments when a defaulted positional argument is skipped", () => {+ assert.equal(+ buildProcedureExecutionSqlFromValues({+ databaseType: "postgres",+ schema: "public",+ routineName: "refresh_stats",+ parameters: [+ {+ name: "p_first",+ dataType: "text",+ mode: "IN",+ ordinal: 1,+ value: "",+ hasDefault: true,+ useDefault: true,+ },+ { name: "p_second", dataType: "integer", mode: "IN", ordinal: 2, value: "8" },+ ],+ }),+ 'CALL "public"."refresh_stats"("p_second" => 8);',+ );++ assert.equal(+ buildProcedureExecutionSqlFromValues({+ databaseType: "oracle",+ schema: "APP",+ routineName: "refresh_stats",+ parameters: [+ {+ name: "P_FIRST",+ dataType: "VARCHAR2",+ mode: "IN",+ ordinal: 1,+ value: "",+ hasDefault: true,+ useDefault: true,+ },+ { name: "P_SECOND", dataType: "NUMBER", mode: "IN", ordinal: 2, value: "8" },+ ],+ }),+ 'BEGIN\n "APP"."refresh_stats"("P_SECOND" => 8);\nEND;',+ );+});++test("maps routine parameter query results into form metadata", () => {+ const parameters = routineParametersFromResult({+ columns: ["name", "data_type", "mode", "ordinal", "has_default"],+ rows: [+ ["p_message", "text", "IN", 1, true],+ ["p_total", "integer", "OUT", 2, false],+ ],+ affected_rows: 0,+ execution_time_ms: 1,+ });++ assert.deepEqual(parameters, [+ { name: "p_message", dataType: "text", mode: "IN", ordinal: 1, hasDefault: true },+ { name: "p_total", dataType: "integer", mode: "OUT", ordinal: 2, hasDefault: false },+ ]);+});++test("builds parameter metadata queries for supported dialects", () => {+ assert.match(+ routineParametersQuery({ database: "app", databaseType: "postgres", schema: "public", routineName: "demo" }) ?? "",+ /pg_proc/,+ );+ assert.match(+ routineParametersQuery({ database: "app", databaseType: "sqlserver", schema: "dbo", routineName: "demo" }) ?? "",+ /sys\.parameters/,+ );+ assert.match(+ routineParametersQuery({ database: "app", databaseType: "mysql", routineName: "demo" }) ?? "",+ /SPECIFIC_SCHEMA = 'app'/,+ );+ assert.match(+ routineParametersQuery({ database: "app", databaseType: "postgres", routineName: "demo" }) ?? "",+ /n\.nspname = 'public'/,+ );+ assert.equal(+ routineParametersQuery({ database: "app", databaseType: "sqlite", schema: "main", routineName: "demo" }),+ null,+ );+});