Skip to content

armgit / dbx

Public Imported from GitHub
0

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。

feat(editor): add SQL intention actions (Alt+Enter style)

大峰f66a18d88ddc
diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vue
index 8d4513dd05..c4a083a354 100644
--- a/apps/desktop/src/components/editor/QueryEditor.vue
+++ b/apps/desktop/src/components/editor/QueryEditor.vue
@@ -114,6 +114,8 @@ import type { StatementExecutionMarker } from "@/lib/tabs/tabPresentation";
import { isSchemaAware, isSingleDatabase, supportsDatabaseNameCompletion, supportsDatabaseSchemaQualifier, supportsSqlInListPaste } from "@/lib/database/databaseFeatureSupport";
import { metadataSchemaForConnection, sqlSnippetDatabaseTypeForConnection } from "@/lib/database/jdbcDialect";
import { usesLocalOnlyEditorCompletionMetadata, usesOnDemandOnlyEditorColumnMetadata } from "@/lib/metadata/completionMetadataPolicy";
+import { loadTableMetadata } from "@/lib/metadata/tableMetadataCache";
+import { analyzeIntentionActions, prepareExpandWildcardContext, buildExpandWildcardReplacement, type IntentionAction } from "@/lib/editor/sqlIntentionActions";
import { loadObjectDdl } from "@/lib/metadata/objectDdlCache";
import { loadObjectMetadataFacet } from "@/lib/metadata/objectMetadataCache";
import { queryContextObjectActions, queryContextObjectRoute, queryTableCandidateAtSqlPosition, queryTableNavigationTargetAtSqlPosition, resolveQueryContextCandidateDatabase, resolveQueryContextObjectTarget, type QueryContextObjectAction } from "@/lib/sql/queryCursorTableTarget";
@@ -366,6 +368,121 @@ function applyDelimitedListResult(result: string) {
focusEditor();
}
+// ==================== Intention Popup ====================
+
+interface IntentionPopupState {
+ visible: boolean;
+ // 直接复用 IntentionAction 类型,避免手动重声明导致 replacements 等字段丢失(TS2551)
+ actions: IntentionAction[];
+ position: { x: number; y: number };
+ selectedIndex: number;
+}
+
+const intentionPopup = ref<IntentionPopupState | null>(null);
+
+function getIntentionActionLabel(kind: string): string {
+ switch (kind) {
+ case "expand_wildcard":
+ return t("intentionExpandWildcard");
+ case "qualify_identifier":
+ return t("intentionQualifyIdentifier");
+ case "unqualify_identifier":
+ return t("intentionUnqualifyIdentifier");
+ case "batch_qualify_identifiers":
+ return t("intentionBatchQualifyIdentifiers");
+ default:
+ return kind;
+ }
+}
+
+function closeIntentionPopup() {
+ document.removeEventListener("keydown", onIntentionPopupKey);
+ intentionPopup.value = null;
+ focusEditor();
+}
+
+function onIntentionPopupKey(e: KeyboardEvent) {
+ if (!intentionPopup.value?.visible) return;
+ switch (e.key) {
+ case "Escape":
+ e.preventDefault();
+ closeIntentionPopup();
+ break;
+ case "ArrowDown":
+ e.preventDefault();
+ intentionPopup.value.selectedIndex = Math.min(intentionPopup.value.selectedIndex + 1, intentionPopup.value.actions.length - 1);
+ break;
+ case "ArrowUp":
+ e.preventDefault();
+ intentionPopup.value.selectedIndex = Math.max(intentionPopup.value.selectedIndex - 1, 0);
+ break;
+ case "Enter":
+ e.preventDefault();
+ executeIntentionAction(intentionPopup.value.actions[intentionPopup.value.selectedIndex]);
+ break;
+ }
+}
+
+function executeIntentionAction(action: IntentionPopupState["actions"][number]) {
+ if (!intentionPopup.value) return;
+ closeIntentionPopup();
+
+ const currentView = view.value;
+ if (!currentView) return;
+
+ switch (action.kind) {
+ case "expand_wildcard": {
+ const sql = currentView.state.doc.toString();
+ const cursor = currentView.state.selection.main.head;
+ void (async () => {
+ try {
+ const ctx = prepareExpandWildcardContext(sql, cursor, props.databaseType, sqlBehaviorDialect());
+ if (!ctx) return;
+
+ const replacement = await buildExpandWildcardReplacement(props.databaseType, ctx.rowSources, async (source) => {
+ const schema = source.metadataTarget?.schema;
+ const tableName = source.metadataTarget?.table ?? source.name;
+ if (!tableName) return [];
+ const result = await loadTableMetadata({
+ connectionId: props.connectionId ?? "",
+ database: props.database ?? "",
+ schema,
+ tableName,
+ databaseType: props.databaseType ?? "mysql",
+ force: false,
+ });
+ return result.metadata.columns.map((c) => c.name);
+ });
+ const v = view.value;
+ if (!v || v.state.doc.toString() !== sql) return;
+ v.dispatch({ changes: { from: ctx.starSpan.start, to: ctx.starSpan.end, insert: replacement } });
+ } catch {
+ // metadata load failed
+ }
+ })();
+ break;
+ }
+ case "qualify_identifier":
+ case "unqualify_identifier":
+ currentView.dispatch({
+ changes: { from: action.span.start, to: action.span.end, insert: action.replacement },
+ });
+ break;
+
+ case "batch_qualify_identifiers": {
+ // 按从后往前的顺序逐一替换,避免 offset 漂移
+ const reps = action.replacements ?? [];
+ for (let i = reps.length - 1; i >= 0; i--) {
+ const r = reps[i];
+ currentView.dispatch({
+ changes: { from: r.span.start, to: r.span.end, insert: r.replacement },
+ });
+ }
+ break;
+ }
+ }
+}
+
const executeContextMenuLabel = computed(() => t(hasSelectedSql.value ? "editor.contextMenu.executeSelection" : "editor.contextMenu.executeCurrent"));
interface EditorGestureEvent extends Event {
@@ -1525,6 +1642,41 @@ const contextMenuItems = computed<ContextMenuItem[]>(() => {
];
});
+function handleSqlIntentionActions(currentView: EditorViewType): boolean {
+ if (props.readOnly) return false;
+ try {
+ const sql = currentView.state.doc.toString();
+ const sel = currentView.state.selection.main;
+
+ const actions = analyzeIntentionActions({
+ sql,
+ cursor: sel.head,
+ databaseType: props.databaseType,
+ dialect: sqlBehaviorDialect(),
+ selection: sel.from !== sel.to ? { from: sel.from, to: sel.to } : undefined,
+ });
+
+ if (actions.length === 0) return false;
+
+ // 计算光标视口坐标,用于定位弹出菜单
+ const coords = currentView.coordsAtPos(sel.head);
+ if (!coords) return false;
+
+ // 显示弹出菜单(参考 DataGrip Alt+Enter 意图操作弹出菜单)
+ intentionPopup.value = {
+ visible: true,
+ actions,
+ position: { x: coords.right + 8, y: coords.bottom + 4 },
+ selectedIndex: 0,
+ };
+ document.addEventListener("keydown", onIntentionPopupKey);
+ return true;
+ } catch (err) {
+ console.error("[SQL Intention] error:", err);
+ return false;
+ }
+}
+
function runKeymapExtension(codeMirrorKeymap: (typeof import("@codemirror/view"))["keymap"]) {
const shortcuts = normalizeShortcutSettings(settingsStore.editorSettings.shortcuts);
const Prec = codeMirrorPrec;
@@ -1585,6 +1737,7 @@ function runKeymapExtension(codeMirrorKeymap: (typeof import("@codemirror/view")
if (sql.trim()) emit("sendSelectionToAi", sql);
return true;
}),
+ ...binding(shortcuts.sqlIntentionActions, handleSqlIntentionActions),
...createQueryEditorSearchKeymap({
openSearch,
openReplace,
@@ -1606,7 +1759,7 @@ function extendQueryEditorSelectionForView(currentView: EditorViewType): boolean
const language = databaseType === "redis" || databaseType === "mongodb" || databaseType === "elasticsearch" || databaseType === "victoriametrics" ? "text" : "sql";
return extendQueryEditorSelection(currentView, {
databaseType,
- dialect: props.syntaxDialect ?? props.dialect,
+ dialect: sqlBehaviorDialect(),
language,
});
}
@@ -5269,6 +5422,17 @@ defineExpose({
<EditorSearchPanel ref="searchPanelRef" :view="view" />
<SqlExecutionTargetPicker v-if="pickerVisible" :candidates="pickerCandidates" :active-index="pickerActiveIndex" :anchor="pickerAnchor" @update:active-index="onPickerActiveIndexChange" @confirm="onPickerConfirm" @cancel="closePicker" />
<DelimitedListDialog v-model:open="delimitedListOpen" :selected-text="delimitedListSelectedText" @confirm="applyDelimitedListResult" />
+ <!-- SQL 意图操作弹出菜单(参考 DataGrip Alt+Enter) -->
+ <Teleport to="body">
+ <div v-if="intentionPopup?.visible" class="intention-popup-overlay" @click.self="closeIntentionPopup">
+ <div class="intention-popup" :style="{ left: intentionPopup.position.x + 'px', top: intentionPopup.position.y + 'px' }">
+ <div v-for="(action, i) in intentionPopup.actions" :key="i" class="intention-popup-item" :class="{ 'intention-popup-item--active': i === intentionPopup.selectedIndex }" @click="executeIntentionAction(action)" @mouseenter="intentionPopup.selectedIndex = i">
+ <span class="intention-popup-item__icon">💡</span>
+ <span class="intention-popup-item__label">{{ action.label || getIntentionActionLabel(action.kind) }}</span>
+ </div>
+ </div>
+ </div>
+ </Teleport>
</div>
</template>
@@ -5482,3 +5646,54 @@ defineExpose({
height: 16px;
}
</style>
+
+<style>
+.intention-popup-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 9999;
+ background: transparent;
+}
+
+.intention-popup {
+ position: fixed;
+ z-index: 10000;
+ min-width: 220px;
+ max-width: 360px;
+ background: var(--popover);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
+ padding: 4px 0;
+ overflow: hidden;
+}
+
+.intention-popup-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px;
+ cursor: pointer;
+ color: var(--foreground);
+ font-size: 13px;
+ line-height: 1.5;
+ transition: background 0.1s;
+}
+
+.intention-popup-item:hover,
+.intention-popup-item--active {
+ background: var(--accent);
+ color: var(--accent-foreground);
+}
+
+.intention-popup-item__icon {
+ font-size: 14px;
+ flex-shrink: 0;
+}
+
+.intention-popup-item__label {
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ overflow: hidden;
+}
+</style>
diff --git a/apps/desktop/src/components/ui/CustomContextMenu.vue b/apps/desktop/src/components/ui/CustomContextMenu.vue
index 790ec7ca19..3bf9c6a475 100644
--- a/apps/desktop/src/components/ui/CustomContextMenu.vue
+++ b/apps/desktop/src/components/ui/CustomContextMenu.vue
@@ -1,23 +1,10 @@
<script setup lang="ts">
-import { ref, watch, onBeforeUnmount, onMounted, nextTick, type Component } from "vue";
+import { ref, watch, onBeforeUnmount, onMounted, nextTick } from "vue";
import { Check, ChevronRight } from "@lucide/vue";
import { shortcutDisplayKeys } from "@/lib/editor/shortcutDisplay";
-import { registerGlobalContextMenu, type ContextMenuRegistration } from "@/components/ui/customContextMenuRegistry";
-
-export interface ContextMenuItem {
- label: string;
- action?: () => void;
- disabled?: boolean | (() => boolean);
- separator?: boolean;
- icon?: Component;
- iconClass?: string;
- checked?: boolean;
- // Raw shortcut syntax such as `Mod+C` or `Shift+Alt+U`; display formatting stays in this component.
- shortcut?: string;
- variant?: "default" | "destructive";
- visible?: boolean;
- children?: ContextMenuItem[];
-}
+import { registerGlobalContextMenu, type ContextMenuRegistration, type ContextMenuItem } from "@/components/ui/customContextMenuRegistry";
+
+export type { ContextMenuItem };
type ContextMenuItemsSource = ContextMenuItem[] | (() => ContextMenuItem[]);
diff --git a/apps/desktop/src/components/ui/customContextMenuRegistry.ts b/apps/desktop/src/components/ui/customContextMenuRegistry.ts
index fcca5d2e20..38de807111 100644
--- a/apps/desktop/src/components/ui/customContextMenuRegistry.ts
+++ b/apps/desktop/src/components/ui/customContextMenuRegistry.ts
@@ -1,3 +1,20 @@
+import type { Component } from "vue";
+
+export interface ContextMenuItem {
+ label: string;
+ action?: () => void;
+ disabled?: boolean | (() => boolean);
+ separator?: boolean;
+ icon?: Component;
+ iconClass?: string;
+ checked?: boolean;
+ // Raw shortcut syntax such as `Mod+C` or `Shift+Alt+U`; display formatting stays in this component.
+ shortcut?: string;
+ variant?: "default" | "destructive";
+ visible?: boolean;
+ children?: ContextMenuItem[];
+}
+
export type ContextMenuClose = () => void;
/** Marker attribute on scrollable context menu / submenu roots. */
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 5c5467c861..e41e1ec46c 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -5543,6 +5543,11 @@ export default {
shortcutOpenDataInNewTab: "Open data in new tab (mouse click)",
shortcutViewTableDdl: "View table DDL",
shortcutSendSelectionToAi: "Send selection to AI",
+ shortcutSqlIntentionActions: "SQL Intention Actions (Expand * / Qualify Identifier)",
+ intentionExpandWildcard: "Expand * to Column List",
+ intentionQualifyIdentifier: "Qualify Identifier",
+ intentionUnqualifyIdentifier: "Unqualify Identifier",
+ intentionBatchQualifyIdentifiers: "Batch Qualify Identifiers",
shortcutToggleFold: "Toggle fold",
shortcutScopeGlobal: "Global",
shortcutScopeEditor: "SQL editor",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 5cdc6eb31e..f3f6b59880 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -5260,6 +5260,11 @@ export default withEnglishFallback({
shortcutOpenDataInNewTab: "Abrir datos en una pestaña nueva (clic del ratón)",
shortcutViewTableDdl: "Ver DDL de la tabla",
shortcutSendSelectionToAi: "Enviar selección a IA",
+ shortcutSqlIntentionActions: "Acciones de intención SQL (Expandir * / Calificar identificador)",
+ intentionExpandWildcard: "Expandir * a lista de columnas",
+ intentionQualifyIdentifier: "Calificar identificador",
+ intentionUnqualifyIdentifier: "Descalificar identificador",
+ intentionBatchQualifyIdentifiers: "Calificar identificadores en lote",
shortcutToggleFold: "Contraer/expandir código",
shortcutScopeGlobal: "Global",
shortcutScopeEditor: "Editor SQL",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 4520534adc..d578052630 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -5260,6 +5260,11 @@ export default withEnglishFallback({
shortcutOpenDataInNewTab: "Apri dati in una nuova scheda (clic del mouse)",
shortcutViewTableDdl: "Visualizza DDL tabella",
shortcutSendSelectionToAi: "Invia selezione ad AI",
+ shortcutSqlIntentionActions: "Azioni di intento SQL (Espandi * / Qualifica identificatore)",
+ intentionExpandWildcard: "Espandi * in elenco colonne",
+ intentionQualifyIdentifier: "Qualifica identificatore",
+ intentionUnqualifyIdentifier: "Rimuovi qualifica",
+ intentionBatchQualifyIdentifiers: "Qualifica identificatori in batch",
shortcutToggleFold: "Comprimi/espandi codice",
shortcutScopeGlobal: "Globale",
shortcutScopeEditor: "Editor SQL",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 90dc6b4048..27201d5397 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -5277,6 +5277,11 @@ export default withEnglishFallback({
shortcutOpenDataInNewTab: "新しいデータタブで開く(マウスクリック)",
shortcutViewTableDdl: "テーブルDDLを表示",
shortcutSendSelectionToAi: "選択範囲をAIに送信",
+ shortcutSqlIntentionActions: "SQL インテント操作(* の展開 / 識別子の修飾)",
+ intentionExpandWildcard: "* を列リストに展開",
+ intentionQualifyIdentifier: "識別子を修飾",
+ intentionUnqualifyIdentifier: "修飾を解除",
+ intentionBatchQualifyIdentifiers: "識別子を一括修飾",
shortcutToggleFold: "折りたたみの切り替え",
shortcutScopeGlobal: "グローバル",
shortcutScopeEditor: "SQLエディタ",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 6d470d6241..22fc66175c 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -5038,6 +5038,11 @@ export default withEnglishFallback({
shortcutOpenDataInNewTab: "새 탭에서 데이터 열기 (마우스 클릭)",
shortcutViewTableDdl: "테이블 DDL 보기",
shortcutSendSelectionToAi: "선택 영역을 AI로 보내기",
+ shortcutSqlIntentionActions: "SQL 인텐트 동작 (* 펼치기 / 식별자 한정)",
+ intentionExpandWildcard: "* 을(를) 열 목록으로 펼치기",
+ intentionQualifyIdentifier: "식별자 한정",
+ intentionUnqualifyIdentifier: "한정 해제",
+ intentionBatchQualifyIdentifiers: "식별자 일괄 한정",
shortcutScopeGlobal: "전역",
shortcutScopeEditor: "SQL 편집기",
shortcutScopeGrid: "데이터 그리드",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index ed6887aa3a..27d93eebf7 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -5262,6 +5262,11 @@ export default withEnglishFallback({
shortcutOpenDataInNewTab: "Abrir dados em nova aba (clique do mouse)",
shortcutViewTableDdl: "Ver DDL da tabela",
shortcutSendSelectionToAi: "Enviar seleção para IA",
+ shortcutSqlIntentionActions: "Ações de intenção SQL (Expandir * / Qualificar identificador)",
+ intentionExpandWildcard: "Expandir * para lista de colunas",
+ intentionQualifyIdentifier: "Qualificar identificador",
+ intentionUnqualifyIdentifier: "Remover qualificação",
+ intentionBatchQualifyIdentifiers: "Qualificar identificadores em lote",
shortcutToggleFold: "Recolher/expandir código",
shortcutScopeGlobal: "Global",
shortcutScopeEditor: "Editor SQL",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index f83448d95d..d31bb8c741 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -5542,6 +5542,11 @@ export default withEnglishFallback({
shortcutOpenDataInNewTab: "在新数据标签页中打开(鼠标点击)",
shortcutViewTableDdl: "查看表 DDL",
shortcutSendSelectionToAi: "发送选中代码到 AI",
+ shortcutSqlIntentionActions: "SQL 意图操作(展开 * / 限定标识符)",
+ intentionExpandWildcard: "展开 * 为列名列表",
+ intentionQualifyIdentifier: "限定标识符",
+ intentionUnqualifyIdentifier: "取消限定",
+ intentionBatchQualifyIdentifiers: "批量限定标识符",
shortcutToggleFold: "切换折叠",
shortcutScopeGlobal: "全局",
shortcutScopeEditor: "SQL 编辑器",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 7e55e0b1ab..5d7673528c 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -4696,6 +4696,11 @@ export default withEnglishFallback({
shortcutOpenDataInNewTab: "在新資料分頁中開啟(滑鼠點擊)",
shortcutViewTableDdl: "檢視資料表 DDL",
shortcutSendSelectionToAi: "傳送選取程式碼至 AI",
+ shortcutSqlIntentionActions: "SQL 意圖操作(展開 * / 限定識別碼)",
+ intentionExpandWildcard: "展開 * 為欄位清單",
+ intentionQualifyIdentifier: "限定識別碼",
+ intentionUnqualifyIdentifier: "取消限定",
+ intentionBatchQualifyIdentifiers: "批量限定識別碼",
shortcutToggleFold: "切換折疊",
shortcutScopeGlobal: "全域",
shortcutScopeEditor: "SQL 編輯器",
diff --git a/apps/desktop/src/lib/__tests__/sql/sqlIntentionActions.spec.ts b/apps/desktop/src/lib/__tests__/sql/sqlIntentionActions.spec.ts
new file mode 100644
index 0000000000..93d4bf8b21
--- /dev/null
+++ b/apps/desktop/src/lib/__tests__/sql/sqlIntentionActions.spec.ts
@@ -0,0 +1,278 @@
+import { describe, expect, it } from "vitest";
+import { analyzeIntentionActions, type IntentionAction } from "@/lib/editor/sqlIntentionActions";
+import { sqlFixtureCursor } from "@/lib/sql/semantic/fixtures";
+
+// ==================== Helpers ====================
+
+/** 用 | 标记光标位置,返回第一个 action(或 null) */
+function actionAtCursor(input: string, databaseType?: string): IntentionAction | null {
+ const { sql, cursor } = sqlFixtureCursor(input);
+ const actions = analyzeIntentionActions({ sql, cursor, databaseType: databaseType as never });
+ return actions[0] ?? null;
+}
+
+/** 用 | 标记光标位置,返回所有 actions */
+function actionsAtCursor(input: string, databaseType?: string): IntentionAction[] {
+ const { sql, cursor } = sqlFixtureCursor(input);
+ return analyzeIntentionActions({ sql, cursor, databaseType: databaseType as never });
+}
+
+// ==================== Tests ====================
+
+describe("sqlIntentionActions - qualify/unqualify identifier", () => {
+ // ---- Bug 8: 已限定标识符不应被错误地再次限定 ----
+
+ describe("已限定标识符(Bug 8 修复)", () => {
+ it("MySQL 反引号限定: `su`.`user_id` 光标在 user_id 上 → 提供取消限定", () => {
+ const action = actionAtCursor("SELECT `su`.`user_id|` FROM sys_user AS su", "mysql");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("unqualify_identifier");
+ expect(action!.replacement).toBe("`user_id`");
+ });
+
+ it("MySQL 反引号限定: `su`.`user_id` 光标在 user_id 上 → span 覆盖完整限定标识符", () => {
+ const action = actionAtCursor("SELECT `su`.`user_id|` FROM sys_user AS su", "mysql");
+ expect(action).not.toBeNull();
+ const sql = "SELECT `su`.`user_id` FROM sys_user AS su";
+ const coveredText = sql.slice(action!.span.start, action!.span.end);
+ expect(coveredText).toContain("su");
+ expect(coveredText).toContain("user_id");
+ });
+
+ it('PostgreSQL 双引号限定: "su"."user_id" 光标在 user_id 上 → 提供取消限定', () => {
+ const action = actionAtCursor('SELECT "su"."user_id|" FROM sys_user AS su', "postgres");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("unqualify_identifier");
+ expect(action!.replacement).toBe('"user_id"');
+ });
+
+ it("无引号限定: su.user_id 光标在 user_id 上 → 提供取消限定", () => {
+ const action = actionAtCursor("SELECT su.user_id| FROM sys_user AS su");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("unqualify_identifier");
+ expect(action!.replacement).toBe("user_id");
+ });
+
+ it("不应生成 `su`.`su`.su 这样的无效 SQL", () => {
+ const action = actionAtCursor("SELECT `su`.`user_id|` FROM sys_user AS su", "mysql");
+ expect(action).not.toBeNull();
+ expect(action!.replacement).not.toBe("`su`.su");
+ expect(action!.replacement).not.toContain("`su`.`su`");
+ });
+ });
+
+ // ---- 表别名不应被限定 ----
+
+ describe("表别名跳过", () => {
+ it("光标在 FROM 子句的表别名 su 上 → 不提供限定", () => {
+ const action = actionAtCursor("SELECT user_id FROM sys_user AS su WHERE su|", "mysql");
+ expect(action).toBeNull();
+ });
+
+ it("光标在 JOIN 的表别名 sup 上 → 不提供限定", () => {
+ const action = actionAtCursor("SELECT * FROM sys_user su JOIN sys_user_post sup| ON su.user_id = sup.user_id");
+ expect(action).toBeNull();
+ });
+ });
+
+ // ---- 未限定标识符 → 提供限定 ----
+
+ describe("未限定标识符 → 提供限定", () => {
+ it("单表有别名: user_id → 添加别名限定", () => {
+ const action = actionAtCursor("SELECT user_id| FROM sys_user AS su", "mysql");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("qualify_identifier");
+ expect(action!.replacement).toContain("su");
+ expect(action!.replacement).toContain("user_id");
+ });
+
+ it("MySQL 反引号包裹列名: `user_id` → 限定为 `su`.`user_id`", () => {
+ const action = actionAtCursor("SELECT `user_id|` FROM sys_user AS su", "mysql");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("qualify_identifier");
+ expect(action!.replacement).toContain("su");
+ });
+ });
+
+ // ---- Projection 别名跳过 ----
+
+ describe("projection 别名跳过", () => {
+ it("光标在列别名 n 上 → 不提供限定", () => {
+ const action = actionAtCursor("SELECT user_name AS n| FROM sys_user su");
+ expect(action).toBeNull();
+ });
+ });
+
+ // ---- 多表 JOIN 场景 ----
+
+ describe("多表 JOIN", () => {
+ it("双表 JOIN 中仅出现在一个表的列 → 提供取消限定", () => {
+ // user_name 只在 su 上引用,不产生歧义
+ const action = actionAtCursor("SELECT su.user_name| FROM sys_user su JOIN sys_user_post sup ON su.user_id = sup.user_id");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("unqualify_identifier");
+ expect(action!.replacement).toBe("user_name");
+ });
+
+ it("双表 JOIN 中同名列(两个限定符都引用) → 不提供取消限定(歧义检测)", () => {
+ // user_id 同时被 su 和 sup 引用,取消限定会产生歧义
+ const action = actionAtCursor("SELECT su.user_id| FROM sys_user su JOIN sys_user_post sup ON su.user_id = sup.user_id");
+ expect(action).toBeNull();
+ });
+
+ it("双表 JOIN 中同名列(仅一个限定符引用) → 仍提供取消限定", () => {
+ // user_id 只被 su 引用(ON 条件用了 sup.user_id,但 SELECT 中只有 su.user_name)
+ const action = actionAtCursor("SELECT su.user_name| FROM sys_user su JOIN sys_user_post sup ON su.user_id = sup.user_id");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("unqualify_identifier");
+ });
+
+ it("双表 JOIN 中未限定列(ON 中用 1 个限定符引用)→ 提供限定", () => {
+ // user_id 在 ON 中被 su 引用 → 可推断属于 sys_user
+ const action = actionAtCursor("SELECT user_id| FROM sys_user su JOIN sys_user_post sup ON su.user_id = sup.post_id");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("qualify_identifier");
+ expect(action!.replacement).toContain("su");
+ });
+
+ it("双表 JOIN 中未限定列(两个限定符都引用)→ 提供所有候选表限定选项", () => {
+ // user_id 同时被 su 和 sup 引用 → 歧义,但提供所有候选让用户选择
+ const actions = actionsAtCursor("SELECT user_id| FROM sys_user su JOIN sys_user_post sup ON su.user_id = sup.user_id");
+ expect(actions.length).toBe(2);
+ expect(actions[0].kind).toBe("qualify_identifier");
+ expect(actions[1].kind).toBe("qualify_identifier");
+ const labels = actions.map((a) => a.label).sort();
+ expect(labels).toEqual(["su.user_id", "sup.user_id"]);
+ });
+
+ it("双表 JOIN 中未限定列(未在任何限定符中引用)→ 提供所有候选表限定选项", () => {
+ // unique_col 未在 SQL 中被任何限定符引用 → 无法自动推断,提供所有候选让用户选择
+ const actions = actionsAtCursor("SELECT unique_col| FROM sys_user su JOIN sys_user_post sup ON su.user_id = sup.user_id");
+ expect(actions.length).toBe(2);
+ expect(actions[0].kind).toBe("qualify_identifier");
+ const labels = actions.map((a) => a.label).sort();
+ expect(labels).toEqual(["su.unique_col", "sup.unique_col"]);
+ });
+ });
+
+ // ---- WHERE / ON 子句中的列 ----
+
+ describe("WHERE / ON 子句", () => {
+ it("WHERE 中未限定列 → 提供限定", () => {
+ const action = actionAtCursor("SELECT * FROM sys_user su WHERE user_id|", "mysql");
+ if (action) {
+ expect(action.kind).toBe("qualify_identifier");
+ expect(action.replacement).toContain("su");
+ }
+ });
+
+ it("ON 条件中已限定列 → 提供取消限定", () => {
+ const action = actionAtCursor("SELECT * FROM sys_user su JOIN sys_user_post sup ON su.user_id| = sup.user_id");
+ if (action) {
+ expect(action.kind).toBe("unqualify_identifier");
+ expect(action.replacement).toBe("user_id");
+ }
+ });
+ });
+
+ // ---- 不应提供操作的场景 ----
+
+ describe("不应提供操作", () => {
+ it("光标在字符串字面量中 → 不提供操作", () => {
+ const action = actionAtCursor("SELECT 'user|_id' FROM sys_user su");
+ expect(action).toBeNull();
+ });
+ });
+
+ // ---- 回归测试: 确保原有功能不受影响 ----
+
+ describe("回归测试", () => {
+ it("无引号单表未限定列 → 正常限定", () => {
+ const action = actionAtCursor("SELECT name| FROM users u");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("qualify_identifier");
+ expect(action!.replacement).toContain("u");
+ expect(action!.replacement).toContain("name");
+ });
+
+ it("无引号单表已限定列 → 正常取消限定", () => {
+ const action = actionAtCursor("SELECT u.name| FROM users u");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("unqualify_identifier");
+ expect(action!.replacement).toBe("name");
+ });
+ });
+
+ // ---- 引号标识符保留(PR Review 阻塞项 2)----
+
+ describe("引号标识符保留", () => {
+ it("MySQL 反引号保留字 qualify → 保留引号", () => {
+ const action = actionAtCursor("SELECT `order`| FROM users u", "mysql");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("qualify_identifier");
+ expect(action!.replacement).toBe("`u`.`order`");
+ });
+
+ it("MySQL 反引号空格列名 qualify → 保留引号", () => {
+ const action = actionAtCursor("SELECT `user id`| FROM users u", "mysql");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("qualify_identifier");
+ expect(action!.replacement).toBe("`u`.`user id`");
+ });
+
+ it("PG 双引号大小写敏感列名 qualify → 保留引号", () => {
+ const action = actionAtCursor('SELECT "UserName"| FROM users u', "postgres");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("qualify_identifier");
+ expect(action!.replacement).toBe('"u"."UserName"');
+ });
+
+ it("MySQL 反引号保留字 unqualify → 保留引号", () => {
+ const action = actionAtCursor("SELECT `u`.`order`| FROM users u", "mysql");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("unqualify_identifier");
+ expect(action!.replacement).toBe("`order`");
+ });
+
+ it("PG 双引号大小写敏感列名 unqualify → 保留引号", () => {
+ const action = actionAtCursor('SELECT "u"."UserName"| FROM users u', "postgres");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("unqualify_identifier");
+ expect(action!.replacement).toBe('"UserName"');
+ });
+ });
+
+ // ---- schema.table.column 三段式标识符(PR Review 阻塞项 3)----
+
+ describe("schema.table.column 三段式标识符", () => {
+ it("三段式 unqualify → 替换为裸列名(保留引号)", () => {
+ const action = actionAtCursor("SELECT dbo.users.user_id| FROM dbo.users", "sqlserver");
+ expect(action).not.toBeNull();
+ expect(action!.kind).toBe("unqualify_identifier");
+ expect(action!.replacement).toBe("[user_id]");
+ });
+
+ it("三段式同名列歧义检测 → 不提供 unqualify", () => {
+ // dbo.users.user_id 和 dbo.orders.user_id 都是 3 段式
+ const sql = "SELECT dbo.users.user_id| FROM dbo.users JOIN dbo.orders ON dbo.users.user_id = dbo.orders.user_id";
+ const action = actionAtCursor(sql, "sqlserver");
+ expect(action).toBeNull();
+ });
+ });
+
+ // ---- 引号标识符歧义检测(PR Review 阻塞项 3)----
+
+ describe("引号标识符歧义检测", () => {
+ it("MySQL 反引号同名列歧义 → 不提供 unqualify", () => {
+ const sql = "SELECT `su`.`user_id`| FROM sys_user `su` JOIN sys_user_post `sup` ON `su`.`user_id` = `sup`.`user_id`";
+ const action = actionAtCursor(sql, "mysql");
+ expect(action).toBeNull();
+ });
+
+ it("PG 双引号同名列歧义 → 不提供 unqualify", () => {
+ const sql = 'SELECT "su"."user_id"| FROM sys_user "su" JOIN sys_user_post "sup" ON "su"."user_id" = "sup"."user_id"';
+ const action = actionAtCursor(sql, "postgres");
+ expect(action).toBeNull();
+ });
+ });
+});
diff --git a/apps/desktop/src/lib/editor/shortcutRegistry.ts b/apps/desktop/src/lib/editor/shortcutRegistry.ts
index a40eab167f..e744809457 100644
--- a/apps/desktop/src/lib/editor/shortcutRegistry.ts
+++ b/apps/desktop/src/lib/editor/shortcutRegistry.ts
@@ -57,7 +57,8 @@ export type ShortcutActionId =
| "editSidebarConnection"
| "openDataInNewTab"
| "viewTableDdl"
- | "sendSelectionToAi";
+ | "sendSelectionToAi"
+ | "sqlIntentionActions";
export type ShortcutScope = "global" | "editor" | "grid" | "search" | "sidebar";
@@ -429,6 +430,12 @@ export const SHORTCUT_DEFINITIONS: ShortcutDefinition[] = [
scope: "editor",
defaultShortcut: "Mod+Shift+A",
},
+ {
+ id: "sqlIntentionActions",
+ labelKey: "settings.shortcutSqlIntentionActions",
+ scope: "editor",
+ defaultShortcut: "Shift+Mod+Enter",
+ },
];
export const DEFAULT_SHORTCUT_SETTINGS: ShortcutSettings = Object.fromEntries(SHORTCUT_DEFINITIONS.map((definition) => [definition.id, definition.defaultShortcut])) as ShortcutSettings;
diff --git a/apps/desktop/src/lib/editor/sqlIntentionActions.ts b/apps/desktop/src/lib/editor/sqlIntentionActions.ts
new file mode 100644
index 0000000000..7ac2f7c3c1
--- /dev/null
+++ b/apps/desktop/src/lib/editor/sqlIntentionActions.ts
@@ -0,0 +1,820 @@
+import type { DatabaseType } from "@/types/database";
+import { buildSqlSemanticModel } from "@/lib/sql/semantic/model";
+import { resolveSqlSemanticNavigationTarget } from "@/lib/sql/semantic/references";
+import type { SqlSemanticModel, SqlSemanticRowSource, SqlSemanticCursorIntent, SqlSemanticScope, SqlSemanticToken } from "@/lib/sql/semantic/types";
+import { unquoteSqlSemanticIdentifier, tokenIsIdentifier } from "@/lib/sql/semantic/tokens";
+import { quoteTableIdentifier } from "@/lib/table/tableSelectSql";
+import { supportsColumnNameQuoting } from "@/lib/dataGrid/dataGridColumnNameCopy";
+
+// ==================== Types ====================
+
+export interface IntentionAction {
+ kind: "expand_wildcard" | "qualify_identifier" | "unqualify_identifier" | "batch_qualify_identifiers";
+ span: { start: number; end: number };
+ replacement: string;
+ /** batch_qualify_identifiers 专用:每个标识符的独立替换 */
+ replacements?: Array<{ span: { start: number; end: number }; replacement: string }>;
+ /** 自定义标签(多表限定场景显示 "Qualify with su" 等) */
+ label?: string;
+}
+
+export interface IntentionActionContext {
+ sql: string;
+ cursor: number;
+ databaseType?: DatabaseType;
+ dialect?: "mysql" | "postgres" | "sqlserver";
+ /** 选择区间,非空时优先走批量限定逻辑 */
+ selection?: { from: number; to: number };
+}
+
+// SQL 关键字集合(小写),用于批量限定时跳过
+const SQL_KEYWORDS = new Set([
+ "select",
+ "from",
+ "where",
+ "and",
+ "or",
+ "not",
+ "in",
+ "exists",
+ "between",
+ "like",
+ "is",
+ "null",
+ "as",
+ "on",
+ "join",
+ "inner",
+ "left",
+ "right",
+ "full",
+ "outer",
+ "cross",
+ "group",
+ "by",
+ "order",
+ "having",
+ "limit",
+ "offset",
+ "union",
+ "all",
+ "distinct",
+ "case",
+ "when",
+ "then",
+ "else",
+ "end",
+ "asc",
+ "desc",
+ "insert",
+ "into",
+ "values",
+ "update",
+ "set",
+ "delete",
+ "create",
+ "table",
+ "drop",
+ "alter",
+ "add",
+ "column",
+ "primary",
+ "key",
+ "foreign",
+ "references",
+ "default",
+ "constraint",
+ "unique",
+ "index",
+ "with",
+ "recursive",
+ "returning",
+ "intersect",
+ "except",
+ "using",
+ "natural",
+ "lateral",
+ "window",
+ "over",
+ "partition",
+]);
+
+// 热循环中使用的正则常量,避免重复编译
+const WHITESPACE_RE = /\s/;
+const IDENT_START_RE = /[a-zA-Z_]/;
+const IDENT_PART_RE = /[a-zA-Z0-9_$]/;
+
+// ==================== Entry Point ====================
+
+export function analyzeIntentionActions(ctx: IntentionActionContext): IntentionAction[] {
+ // P0: 选中区间优先 → 批量限定
+ if (ctx.selection && ctx.selection.from < ctx.selection.to) {
+ return buildBatchQualifyActions(ctx);
+ }
+
+ const model = buildSqlSemanticModel(ctx.sql, ctx.cursor, {
+ databaseType: ctx.databaseType,
+ dialect: ctx.dialect,
+ });
+
+ const { cursorIntent } = model;
+
+ switch (cursorIntent.kind) {
+ case "star":
+ return buildExpandWildcardActions(model, cursorIntent);
+
+ case "column":
+ case "alias_column":
+ case "update_column":
+ case "insert_column":
+ case "join_condition":
+ return buildQualifierActions(model, cursorIntent, ctx.sql, ctx.databaseType);
+
+ case "keyword":
+ if (cursorIntent.qualifierParts.length > 0 || cursorIntent.replacementRange.start < cursorIntent.replacementRange.end) {
+ return buildQualifierActions(model, cursorIntent, ctx.sql, ctx.databaseType);
+ }
+ return [];
+
+ default:
+ return [];
+ }
+}
+
+// ==================== Expand Wildcard ====================
+
+/**
+ * 查找光标所在的 SELECT scope(用于通配符展开和上下文准备)。
+ */
+function findSelectScopeForCursor(model: SqlSemanticModel, cursorIntent: SqlSemanticCursorIntent) {
+ return model.scopes.find((s) => {
+ if (!s.clauseSpans.select) return false;
+ const selectStart = s.clauseSpans.select.start;
+ const nextClause = s.clauseSpans.from ?? s.clauseSpans.where ?? s.clauseSpans.having ?? s.clauseSpans.groupBy ?? s.clauseSpans.orderBy ?? s.clauseSpans.limit;
+ const selectEnd = nextClause?.start ?? Infinity;
+ return cursorIntent.replacementRange.start >= selectStart && cursorIntent.replacementRange.start < selectEnd;
+ });
+}
+
+function buildExpandWildcardActions(model: SqlSemanticModel, cursorIntent: SqlSemanticCursorIntent): IntentionAction[] {
+ const scope = findSelectScopeForCursor(model, cursorIntent);
+ if (!scope || scope.rowSources.length === 0) return [];
+
+ const rowSources = scope.rowSources.filter((rs) => rs.kind === "table" || rs.kind === "cte");
+
+ if (rowSources.length === 0) return [];
+
+ return [
+ {
+ kind: "expand_wildcard" as const,
+ span: cursorIntent.replacementRange,
+ replacement: "",
+ },
+ ];
+}
+
+export async function buildExpandWildcardReplacement(databaseType: DatabaseType | undefined, rowSources: SqlSemanticRowSource[], fetchColumns: (source: SqlSemanticRowSource) => Promise<string[]>): Promise<string> {
+ const quote = supportsColumnNameQuoting(databaseType);
+ const allColumns: string[] = [];
+
+ for (const source of rowSources) {
+ const columns = await fetchColumns(source);
+ const rawName = source.alias ?? source.name;
+ const qualifier = quote ? quoteTableIdentifier(databaseType, rawName) : rawName;
+
+ for (const col of columns) {
+ const quoted = quote ? quoteTableIdentifier(databaseType, col) : col;
+ allColumns.push(rowSources.length > 1 ? `${qualifier}.${quoted}` : quoted);
+ }
+ }
+
+ return allColumns.join(", ");
+}
+
+// ==================== Batch Qualify (P0) ====================
+
+/**
+ * 在选中区间内扫描独立标识符,为未限定的标识符批量添加表前缀。
+ */
+function buildBatchQualifyActions(ctx: IntentionActionContext): IntentionAction[] {
+ const { sql, selection, databaseType, dialect } = ctx;
+ if (!selection) return [];
+
+ // 用选中区间起点构建语义模型
+ const model = buildSqlSemanticModel(sql, selection.from, {
+ databaseType,
+ dialect,
+ });
+
+ // 检查是否为多表场景
+ const scope = model.scopes.find((s) => s.rowSources.length > 0);
+ const tableSources = scope?.rowSources.filter((rs) => rs.kind === "table" || rs.kind === "cte") ?? [];
+ const isMultiTable = tableSources.length > 1;
+
+ // 单表场景:解析统一表源
+ let singleQualifier: string | null = null;
+ if (!isMultiTable) {
+ const tableTarget = resolveNavigationTarget(model, model.cursorIntent);
+ if (!tableTarget) return [];
+ const quote = supportsColumnNameQuoting(databaseType);
+ singleQualifier = quote ? quoteTableIdentifier(databaseType, tableTarget.alias ?? tableTarget.name) : (tableTarget.alias ?? tableTarget.name);
+ }
+
+ // 扫描选中区间内的标识符
+ const selectedText = sql.slice(selection.from, selection.to);
+ const tokens = tokenizeSelectionIdentifiers(selectedText, databaseType);
+ const replacements: NonNullable<IntentionAction["replacements"]> = [];
+ const offset = selection.from;
+
+ // 收集当前 scope 的 projection 别名,用于跳过
+ const aliasNames = collectProjectionAliasNames(model);
+ const quote = supportsColumnNameQuoting(databaseType);
+
+ // 多表场景:一次性构建 column → qualifiers 映射,避免 N 次重复扫描全量 token
+ const qualifierMap = isMultiTable ? buildColumnQualifierMap(model) : undefined;
+
+ for (const token of tokens) {
+ // 跳过已限定标识符
+ if (token.qualified) continue;
+ // 跳过 SQL 关键字
+ if (SQL_KEYWORDS.has(token.text.toLowerCase())) continue;
+ // 跳过 projection 别名(P1-2)
+ if (aliasNames.has(token.text.toLowerCase())) continue;
+
+ let qualifier: string;
+
+ if (isMultiTable) {
+ // 多表场景:为每个 token 独立解析表源(使用缓存的 qualifierMap)
+ const tokenModel = buildSqlSemanticModel(sql, offset + token.start, {
+ databaseType,
+ dialect,
+ });
+ const tokenTarget = resolveNavigationTarget(tokenModel, tokenModel.cursorIntent, qualifierMap);
+ if (!tokenTarget) continue; // 无法确定表源,跳过
+ qualifier = quote ? quoteTableIdentifier(databaseType, tokenTarget.alias ?? tokenTarget.name) : (tokenTarget.alias ?? tokenTarget.name);
+ } else {
+ qualifier = singleQualifier!;
+ }
+
+ const quotedColumn = quote ? quoteTableIdentifier(databaseType, token.text) : token.text;
+ replacements.push({
+ span: { start: offset + token.start, end: offset + token.end },
+ replacement: `${qualifier}.${quotedColumn}`,
+ });
+ }
+
+ if (replacements.length === 0) return [];
+
+ return [
+ {
+ kind: "batch_qualify_identifiers" as const,
+ span: { start: selection.from, end: selection.to },
+ replacement: "",
+ replacements,
+ },
+ ];
+}
+
+interface SelectionToken {
+ /** 在选中区间内的起始偏移 */
+ start: number;
+ /** 在选中区间内的结束偏移 */
+ end: number;
+ /** 剥离引号后的标识符文本 */
+ text: string;
+ /** 是否已限定(含 "." 分隔符) */
+ qualified: boolean;
+}
+
+/**
+ * 在选中文本中扫描独立标识符,处理各种引号包裹方式。
+ */
+function tokenizeSelectionIdentifiers(text: string, databaseType?: DatabaseType): SelectionToken[] {
+ const tokens: SelectionToken[] = [];
+ const doubleQuoteIsIdentifier = usesDoubleQuoteIdentifier(databaseType);
+ let i = 0;
+
+ while (i < text.length) {
+ const ch = text[i];
+
+ // 跳过单行注释 --
+ if (ch === "-" && text[i + 1] === "-") {
+ const nl = text.indexOf("\n", i);
+ i = nl === -1 ? text.length : nl + 1;
+ continue;
+ }
+
+ // 跳过多行注释 /* */
+ if (ch === "/" && text[i + 1] === "*") {
+ const end = text.indexOf("*/", i + 2);
+ i = end === -1 ? text.length : end + 2;
+ continue;
+ }
+
+ // 跳过字符串字面量(单引号包裹,支持 '' 转义)
+ if (ch === "'") {
+ i++;
+ while (i < text.length) {
+ if (text[i] === "'" && text[i + 1] === "'") {
+ i += 2;
+ continue;
+ }
+ if (text[i] === "'") {
+ i++;
+ break;
+ }
+ i++;
+ }
+ continue;
+ }
+
+ // 跳过双引号字符串字面量(当数据库不使用双引号作为标识符引用时)
+ if (ch === '"' && !doubleQuoteIsIdentifier) {
+ const end = text.indexOf('"', i + 1);
+ i = end === -1 ? text.length : end + 1;
+ continue;
+ }
+
+ // 跳过空白和标点(逗号、括号等)
+ if (WHITESPACE_RE.test(ch) || ch === "," || ch === "(" || ch === ")" || ch === ";" || ch === "*" || ch === "+" || ch === "-" || ch === "/" || ch === "=") {
+ i++;
+ continue;
+ }
+
+ // 标识符起始:字母、下划线、反引号、双引号、方括号
+ const identStart = i;
+ let parts: string[] = [];
+ let qualified = false;
+
+ // 循环读取 qualified.identifier 形式
+ while (i < text.length) {
+ const part = readIdentifierPart(text, i, databaseType, doubleQuoteIsIdentifier);
+ if (!part) break;
+
+ parts.push(part.text);
+ i = part.end;
+
+ // 检查后面是否紧跟 "."
+ if (text[i] === ".") {
+ qualified = true;
+ i++;
+ continue;
+ }
+ break;
+ }
+
+ if (parts.length > 0) {
+ // 取最后一个 part 作为列名(去掉引号后的文本)
+ const lastPart = parts[parts.length - 1];
+ if (lastPart.length > 0) {
+ tokens.push({
+ start: identStart,
+ end: i,
+ text: lastPart,
+ qualified,
+ });
+ }
+ } else {
+ i++;
+ }
+ }
+
+ return tokens;
+}
+
+/**
+ * 判断当前数据库是否使用双引号作为标识符引用。
+ * PostgreSQL/Oracle/DB2 等使用双引号,MySQL/SQL Server 中双引号是字符串字面量。
+ */
+function usesDoubleQuoteIdentifier(databaseType?: DatabaseType): boolean {
+ if (!databaseType) return true;
+ return quoteTableIdentifier(databaseType, "x").startsWith('"');
+}
+
+/**
+ * 读取一个标识符分段(可能被引号包裹),返回剥离引号后的文本和结束位置。
+ * `doubleQuoteIsIdentifier` 参数用于避免在热循环中重复调用 `usesDoubleQuoteIdentifier`。
+ */
+function readIdentifierPart(text: string, start: number, databaseType?: DatabaseType, doubleQuoteIsIdentifier?: boolean): { text: string; end: number } | null {
+ const ch = text[start];
+
+ // MySQL 反引号
+ if (ch === "`") {
+ const end = text.indexOf("`", start + 1);
+ if (end === -1) return null;
+ return { text: text.slice(start + 1, end), end: end + 1 };
+ }
+
+ // 双引号:仅在数据库使用双引号作为标识符引用时处理
+ const dqIsIdent = doubleQuoteIsIdentifier ?? usesDoubleQuoteIdentifier(databaseType);
+ if (ch === '"' && dqIsIdent) {
+ const end = text.indexOf('"', start + 1);
+ if (end === -1) return null;
+ return { text: text.slice(start + 1, end), end: end + 1 };
+ }
+
+ // SQL Server 方括号
+ if (ch === "[") {
+ const end = text.indexOf("]", start + 1);
+ if (end === -1) return null;
+ return { text: text.slice(start + 1, end), end: end + 1 };
+ }
+
+ // 普通标识符:字母、数字、下划线
+ if (IDENT_START_RE.test(ch)) {
+ let i = start;
+ while (i < text.length && IDENT_PART_RE.test(text[i])) i++;
+ return { text: text.slice(start, i), end: i };
+ }
+
+ return null;
+}
+
+/**
+ * 收集当前模型所有 scope 中的 projection 别名(小写),用于跳过别名列。
+ */
+function collectProjectionAliasNames(model: SqlSemanticModel): Set<string> {
+ const names = new Set<string>();
+ for (const scope of model.scopes) {
+ for (const proj of scope.projections) {
+ if (proj.alias) {
+ names.add(proj.alias.toLowerCase());
+ }
+ }
+ }
+ return names;
+}
+
+/**
+ * 收集所有行源的表名和别名(小写),用于跳过表别名。
+ * 表别名不是列名,不应提供限定操作。
+ */
+function collectTableAliasNames(model: SqlSemanticModel): Set<string> {
+ const names = new Set<string>();
+ for (const rs of model.rowSources) {
+ if (rs.alias) names.add(rs.alias.toLowerCase());
+ names.add(rs.name.toLowerCase());
+ }
+ return names;
+}
+
+/**
+ * 将 token 标准化为小写无引号文本,用于跨引号风格的统一比较。
+ */
+function normalizeIdentifierToken(token: SqlSemanticToken): string {
+ return unquoteSqlSemanticIdentifier(token).toLowerCase();
+}
+
+/**
+ * 提取 qualifier 的完整文本(处理 schema.table.column 三段式标识符)。
+ * 当 tokens[i] 前面还有 `schema.` 时,返回 `schema.table`,否则返回 `table`。
+ */
+function extractQualifier(tokens: readonly SqlSemanticToken[], i: number): string {
+ // 检查是否为 3-part: schema.table.column → qualifier = schema.table
+ if (i >= 2 && tokens[i - 1]?.text === "." && tokenIsIdentifier(tokens[i - 2])) {
+ return `${normalizeIdentifierToken(tokens[i - 2])}.${normalizeIdentifierToken(tokens[i])}`;
+ }
+ return normalizeIdentifierToken(tokens[i]);
+}
+
+/**
+ * 扫描 SQL 中的 `qualifier.column` 模式,收集引用指定列名的不同限定符。
+ * 支持 2-part (table.column) 和 3-part (schema.table.column) 标识符。
+ */
+function collectColumnQualifiers(model: SqlSemanticModel, columnName: string): Set<string> {
+ const target = columnName.toLowerCase();
+ const qualifiers = new Set<string>();
+ const tokens = model.tokens;
+ for (let i = 0; i < tokens.length - 2; i++) {
+ if (tokenIsIdentifier(tokens[i]) && tokens[i + 1]?.text === "." && tokenIsIdentifier(tokens[i + 2])) {
+ if (normalizeIdentifierToken(tokens[i + 2]) === target) {
+ qualifiers.add(extractQualifier(tokens, i));
+ }
+ }
+ }
+ return qualifiers;
+}
+
+/**
+ * 一次性构建 `column → qualifiers` 映射,避免批量场景中 N 次重复扫描全量 token。
+ * 支持 2-part (table.column) 和 3-part (schema.table.column) 标识符。
+ */
+function buildColumnQualifierMap(model: SqlSemanticModel): Map<string, Set<string>> {
+ const map = new Map<string, Set<string>>();
+ const tokens = model.tokens;
+ for (let i = 0; i < tokens.length - 2; i++) {
+ if (tokenIsIdentifier(tokens[i]) && tokens[i + 1]?.text === "." && tokenIsIdentifier(tokens[i + 2])) {
+ const col = normalizeIdentifierToken(tokens[i + 2]);
+ const qual = extractQualifier(tokens, i);
+ let set = map.get(col);
+ if (!set) {
+ set = new Set();
+ map.set(col, set);
+ }
+ set.add(qual);
+ }
+ }
+ return map;
+}
+
+/**
+ * 检查取消限定后列名是否会产生歧义。
+ * 1. 扫描 SQL 中的 qualifier.column 模式,检查同一列名是否被 2+ 个不同限定符引用
+ * 2. 检查 rowSources 的 columns(CTE/子查询场景),列名是否出现在 2+ 个行源中
+ */
+function isColumnAmbiguous(model: SqlSemanticModel, columnName: string): boolean {
+ const target = columnName.toLowerCase();
+
+ // 1. 检查 rowSources 的 columns(CTE/子查询有列信息时)
+ let sourcesWithColumn = 0;
+ for (const rs of model.rowSources) {
+ if (rs.columns?.some((c) => c.toLowerCase() === target)) {
+ sourcesWithColumn++;
+ }
+ }
+ if (sourcesWithColumn >= 2) return true;
+
+ // 2. 扫描 token 中的 qualifier.column 模式,收集不同限定符
+ const qualifiers = collectColumnQualifiers(model, columnName);
+ // 2+ 个不同限定符引用同一列名 → 取消限定后会产生歧义
+ return qualifiers.size >= 2;
+}
+
+// ==================== Qualify / Unqualify Identifier ====================
+
+/**
+ * 查找光标所在位置对应的完整标识符 token。
+ * trailingIdentifier 为自动补全设计,replacementRange 只到光标位置。
+ * 意图操作需要完整 token 的范围和文本。
+ */
+function findFullIdentifierToken(model: SqlSemanticModel, range: { start: number; end: number }): { prefix: string; replacementRange: { start: number; end: number } } | null {
+ for (const token of model.tokens) {
+ if (tokenIsIdentifier(token) && token.span.start === range.start && token.span.end > range.end) {
+ return {
+ prefix: unquoteSqlSemanticIdentifier(token),
+ replacementRange: { start: token.span.start, end: token.span.end },
+ };
+ }
+ }
+ return null;
+}
+
+function buildQualifierActions(model: SqlSemanticModel, cursorIntentIn: SqlSemanticCursorIntent, sql: string, databaseType?: DatabaseType): IntentionAction[] {
+ let cursorIntent = cursorIntentIn;
+
+ // 修复:当光标在标识符中间时,trailingIdentifier 返回的 replacementRange 只到光标位置。
+ // 扩展到完整 token 的范围和文本。
+ const fullToken = findFullIdentifierToken(model, cursorIntent.replacementRange);
+ if (fullToken) {
+ cursorIntent = {
+ ...cursorIntent,
+ prefix: fullToken.prefix,
+ replacementRange: fullToken.replacementRange,
+ };
+ }
+ // 组合 qualifierParts + prefix 形成完整标识符分段
+ // qualifierParts 仅含限定符(表别名),prefix 含列名
+ let parts = cursorIntent.qualifierParts;
+ if (cursorIntent.prefix) {
+ parts = [...parts, cursorIntent.prefix];
+ }
+
+ // fallback:无 prefix 且无 qualifierParts 时从 SQL 文本提取
+ if (parts.length === 0 && sql && cursorIntent.replacementRange.start < cursorIntent.replacementRange.end) {
+ const text = sql.slice(cursorIntent.replacementRange.start, cursorIntent.replacementRange.end);
+ if (text.length > 0) {
+ parts = splitQualifiedIdentifier(text, databaseType);
+ }
+ }
+
+ if (parts.length === 0) return [];
+
+ const actions: IntentionAction[] = [];
+ const lastPart = parts[parts.length - 1] ?? "";
+
+ // P1-2: 跳过 projection 别名
+ const aliasNames = collectProjectionAliasNames(model);
+ if (aliasNames.has(lastPart.toLowerCase())) return [];
+
+ // 跳过表别名(su 是别名不是列名,不应提供限定)
+ const tableAliasNames = collectTableAliasNames(model);
+ if (tableAliasNames.has(lastPart.toLowerCase())) return [];
+
+ // 判断是否已限定:qualifierParts 非空,或 fallback 提取出多段
+ const isQualified = cursorIntent.qualifierParts.length > 0 || parts.length > 1;
+
+ if (isQualified) {
+ // 检查取消限定后是否会产生歧义(多表 JOIN 同名列场景)
+ if (isColumnAmbiguous(model, lastPart)) {
+ return [];
+ }
+
+ // 已限定 → 提供取消限定
+ // 扩展 span 覆盖完整限定标识符(如 `su`.`user_id` 而非仅 `user_id`)
+ let span = cursorIntent.replacementRange;
+ if (cursorIntent.qualifierParts.length > 0) {
+ // 反向迭代查找 replacementRange 之前的 token(避免 filter 创建新数组)
+ let ti = model.tokens.length - 1;
+ while (ti >= 0) {
+ const t = model.tokens[ti];
+ if (t.span.end <= cursorIntent.replacementRange.start && t.kind !== "comment" && t.kind !== "string") break;
+ ti--;
+ }
+ // 检查 replacementRange 前是否紧跟 "."
+ if (ti >= 0 && model.tokens[ti].text === ".") {
+ ti--;
+ // 向前查找限定符标识符
+ while (ti >= 0) {
+ const token = model.tokens[ti];
+ // 跳过 comment/string token
+ if (token.kind === "comment" || token.kind === "string") {
+ ti--;
+ continue;
+ }
+ if (token.kind === "word" || token.kind === "quoted_identifier") {
+ span = { start: token.span.start, end: cursorIntent.replacementRange.end };
+ ti--;
+ // 继续向前查找 schema.table.column 模式
+ if (ti >= 0 && model.tokens[ti].text === ".") {
+ ti--;
+ continue;
+ }
+ }
+ break;
+ }
+ }
+ }
+ const quote = supportsColumnNameQuoting(databaseType);
+ const quotedColumn = quote ? quoteTableIdentifier(databaseType, lastPart) : lastPart;
+ actions.push({
+ kind: "unqualify_identifier",
+ span,
+ replacement: quotedColumn,
+ });
+ return actions;
+ }
+
+ // 未限定 → 提供限定
+ const target = resolveNavigationTarget(model, cursorIntent);
+ if (target) {
+ const quote = supportsColumnNameQuoting(databaseType);
+ const qualifier = quote ? quoteTableIdentifier(databaseType, target.alias ?? target.name) : (target.alias ?? target.name);
+ const quotedColumn = quote ? quoteTableIdentifier(databaseType, lastPart) : lastPart;
+ actions.push({
+ kind: "qualify_identifier" as const,
+ span: cursorIntent.replacementRange,
+ replacement: `${qualifier}.${quotedColumn}`,
+ });
+ return actions;
+ }
+
+ // 多表场景:无法自动推断所属表时,提供所有候选表的限定选项
+ const scope = findScopeContainingCursor(model, cursorIntent.replacementRange.start);
+ if (scope) {
+ const tableSources = scope.rowSources.filter((rs) => rs.kind === "table" || rs.kind === "cte");
+ if (tableSources.length > 1) {
+ const quote = supportsColumnNameQuoting(databaseType);
+ const quotedColumn = quote ? quoteTableIdentifier(databaseType, lastPart) : lastPart;
+ for (const source of tableSources) {
+ const qualifierName = source.alias ?? source.name;
+ const qualifier = quote ? quoteTableIdentifier(databaseType, qualifierName) : qualifierName;
+ actions.push({
+ kind: "qualify_identifier" as const,
+ span: cursorIntent.replacementRange,
+ replacement: `${qualifier}.${quotedColumn}`,
+ label: `${qualifierName}.${lastPart}`,
+ });
+ }
+ }
+ }
+
+ return actions;
+}
+
+/**
+ * 将 qualified identifier 文本拆分为分段,正确处理各种引号包裹方式。
+ * 例如: `su`.`user_id` → ["su", "user_id"]
+ * su.user_id → ["su", "user_id"]
+ * `user_id` → ["user_id"]
+ */
+function splitQualifiedIdentifier(text: string, databaseType?: DatabaseType): string[] {
+ const parts: string[] = [];
+ let i = 0;
+
+ while (i < text.length) {
+ const part = readIdentifierPart(text, i, databaseType);
+ if (!part) {
+ i++;
+ continue;
+ }
+ parts.push(part.text);
+ i = part.end;
+
+ // 跳过 "." 分隔符
+ if (text[i] === ".") {
+ i++;
+ continue;
+ }
+ break;
+ }
+
+ return parts.filter(Boolean);
+}
+
+/**
+ * 查找包含光标位置的最内层 scope。
+ *
+ * 注意:clauseSpans 中每个子句的 end 只到下一个 token 的 start(非常窄),
+ * 无法覆盖整个子句范围。因此优先使用 scope 的 statement span 判断光标归属,
+ * 仅在 statement span 不可用时回退到 clauseSpans。
+ */
+function findScopeContainingCursor(model: SqlSemanticModel, cursor: number) {
+ let best: SqlSemanticScope | undefined;
+ for (const s of model.scopes) {
+ if (s.rowSources.length === 0) continue;
+ // 优先使用 statement span(覆盖整条语句,cursor 必在其中)
+ if (cursor >= s.span.start && cursor <= s.span.end) {
+ best = s; // 取最后一个匹配的(最内层)
+ continue;
+ }
+ // 回退:检查 clauseSpans
+ const spans = [s.clauseSpans.select, s.clauseSpans.from, s.clauseSpans.where, s.clauseSpans.having, s.clauseSpans.groupBy, s.clauseSpans.orderBy, s.clauseSpans.limit].filter(Boolean) as { start: number; end: number }[];
+ if (spans.some((sp) => cursor >= sp.start && cursor <= sp.end)) {
+ best = s;
+ }
+ }
+ return best;
+}
+
+function resolveNavigationTarget(model: SqlSemanticModel, cursorIntent: SqlSemanticCursorIntent, qualifierMap?: Map<string, Set<string>>): { name: string; alias?: string } | null {
+ // 1. 优先使用 semantic 的 targetSourceId
+ if (cursorIntent.targetSourceId) {
+ const source = model.rowSources.find((rs) => rs.id === cursorIntent.targetSourceId);
+ if (source) return { name: source.name, alias: source.alias };
+ }
+
+ // 2. 尝试使用 resolveSqlSemanticNavigationTarget(适用于已限定标识符)
+ try {
+ const target = resolveSqlSemanticNavigationTarget(model, cursorIntent.qualifierParts);
+ if (target) return { name: target.name, alias: target.alias };
+ } catch {
+ // ignore
+ }
+
+ // 3. 降级策略 — 查找包含光标的 scope
+ const scope = findScopeContainingCursor(model, cursorIntent.replacementRange.start);
+ if (scope) {
+ const tableSources = scope.rowSources.filter((rs) => rs.kind === "table" || rs.kind === "cte");
+ // 3a. 单表场景 → 直接返回
+ if (tableSources.length === 1) {
+ return { name: tableSources[0].name, alias: tableSources[0].alias };
+ }
+
+ // 3b. 多表场景 → 扫描 SQL 中同一列名的限定符引用
+ // 如果列名在 SQL 中被恰好 1 个限定符引用,则可推断其所属表
+ if (cursorIntent.prefix && tableSources.length > 1) {
+ const qualifiers = qualifierMap?.get(cursorIntent.prefix.toLowerCase()) ?? collectColumnQualifiers(model, cursorIntent.prefix);
+ if (qualifiers.size === 1) {
+ const qualifier = [...qualifiers][0];
+ // 支持 schema.table 形式的限定符匹配
+ const source = tableSources.find((rs) => {
+ const alias = rs.alias?.toLowerCase();
+ const name = rs.name.toLowerCase();
+ if (alias === qualifier || name === qualifier) return true;
+ // 3-part: qualifier = "schema.table", match against metadataTarget
+ const dotIdx = qualifier.indexOf(".");
+ if (dotIdx > 0) {
+ const qualTable = qualifier.slice(dotIdx + 1);
+ return alias === qualTable || name === qualTable;
+ }
+ return false;
+ });
+ if (source) return { name: source.name, alias: source.alias };
+ }
+ }
+ }
+
+ return null;
+}
+
+// ==================== Expand Wildcard Context ====================
+
+export function prepareExpandWildcardContext(sql: string, cursor: number, databaseType?: DatabaseType, dialect?: "mysql" | "postgres" | "sqlserver"): { rowSources: SqlSemanticRowSource[]; starSpan: { start: number; end: number } } | null {
+ const model = buildSqlSemanticModel(sql, cursor, { databaseType, dialect });
+
+ if (model.cursorIntent.kind !== "star") return null;
+
+ const { cursorIntent } = model;
+
+ const scope = findSelectScopeForCursor(model, cursorIntent);
+
+ if (!scope) return null;
+
+ const rowSources = scope.rowSources.filter((rs) => rs.kind === "table" || rs.kind === "cte");
+
+ if (rowSources.length === 0) return null;
+
+ const starSpan = cursorIntent.replacementRange.start === cursorIntent.replacementRange.end ? { start: cursorIntent.replacementRange.start, end: cursorIntent.replacementRange.end + 1 } : cursorIntent.replacementRange;
+
+ return { rowSources, starSpan };
+}
diff --git a/apps/desktop/src/lib/sidebar/sidebarTreeMenuDescriptors.ts b/apps/desktop/src/lib/sidebar/sidebarTreeMenuDescriptors.ts
index f11a3752e3..cb8161bd68 100644
--- a/apps/desktop/src/lib/sidebar/sidebarTreeMenuDescriptors.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarTreeMenuDescriptors.ts
@@ -1,4 +1,4 @@
-import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
+import type { ContextMenuItem } from "@/components/ui/customContextMenuRegistry";
import type { DatabaseType, TreeNode, TreeNodeType } from "@/types/database";
import { createSidebarActionTarget, type SidebarActionTarget } from "./sidebarActionTarget";
diff --git a/apps/desktop/src/lib/sidebar/sidebarTreeRuntime.ts b/apps/desktop/src/lib/sidebar/sidebarTreeRuntime.ts
index 70c0ae57a5..227952ea57 100644
--- a/apps/desktop/src/lib/sidebar/sidebarTreeRuntime.ts
+++ b/apps/desktop/src/lib/sidebar/sidebarTreeRuntime.ts
@@ -1,5 +1,5 @@
import type { ComponentPublicInstance, InjectionKey } from "vue";
-import type { ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
+import type { ContextMenuItem } from "@/components/ui/customContextMenuRegistry";
import type { TreeNode } from "@/types/database";
import { createSidebarActionTarget, type SidebarActionTarget } from "./sidebarActionTarget";