feat(editor): restore SQL pasted from source code
This commit is contained in:
25 files changed
+889
-1
No files matched your search
@@ -697,6 +697,7 @@ const editDdlOpenMode = ref<EditorSettings["ddlOpenMode"]>(settingsStore.editorS
|
|||||||
const editVimModeEnabled = ref(settingsStore.editorSettings.vimModeEnabled);
|
const editVimModeEnabled = ref(settingsStore.editorSettings.vimModeEnabled);
|
||||||
const editDoubleClickStringSelectionMode = ref<EditorSettings["doubleClickStringSelectionMode"]>(settingsStore.editorSettings.doubleClickStringSelectionMode);
|
const editDoubleClickStringSelectionMode = ref<EditorSettings["doubleClickStringSelectionMode"]>(settingsStore.editorSettings.doubleClickStringSelectionMode);
|
||||||
const editAutoCloseBrackets = ref(settingsStore.editorSettings.autoCloseBrackets);
|
const editAutoCloseBrackets = ref(settingsStore.editorSettings.autoCloseBrackets);
|
||||||
|
const editRestoreSqlFromSourcePasteEnabled = ref(settingsStore.editorSettings.restoreSqlFromSourcePasteEnabled);
|
||||||
const editSqlSemanticDiagnosticsMode = ref<SqlSemanticDiagnosticsMode>(settingsStore.editorSettings.sqlSemanticDiagnosticsMode);
|
const editSqlSemanticDiagnosticsMode = ref<SqlSemanticDiagnosticsMode>(settingsStore.editorSettings.sqlSemanticDiagnosticsMode);
|
||||||
const editSqlSemanticDiagnosticsEnabled = ref(settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled);
|
const editSqlSemanticDiagnosticsEnabled = ref(settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled);
|
||||||
const editConfirmDangerousSqlExecution = ref(settingsStore.editorSettings.confirmDangerousSqlExecution);
|
const editConfirmDangerousSqlExecution = ref(settingsStore.editorSettings.confirmDangerousSqlExecution);
|
||||||
@@ -1062,6 +1063,7 @@ function currentEditorSettingsDraft(): EditorSettingsDraft {
|
|||||||
vimModeEnabled: editVimModeEnabled.value,
|
vimModeEnabled: editVimModeEnabled.value,
|
||||||
doubleClickStringSelectionMode: editDoubleClickStringSelectionMode.value,
|
doubleClickStringSelectionMode: editDoubleClickStringSelectionMode.value,
|
||||||
autoCloseBrackets: editAutoCloseBrackets.value,
|
autoCloseBrackets: editAutoCloseBrackets.value,
|
||||||
|
restoreSqlFromSourcePasteEnabled: editRestoreSqlFromSourcePasteEnabled.value,
|
||||||
sqlSemanticDiagnosticsMode: editSqlSemanticDiagnosticsMode.value,
|
sqlSemanticDiagnosticsMode: editSqlSemanticDiagnosticsMode.value,
|
||||||
confirmDangerousSqlExecution: editConfirmDangerousSqlExecution.value,
|
confirmDangerousSqlExecution: editConfirmDangerousSqlExecution.value,
|
||||||
continueOnErrorOnBatch: editContinueOnErrorOnBatch.value,
|
continueOnErrorOnBatch: editContinueOnErrorOnBatch.value,
|
||||||
@@ -1726,6 +1728,7 @@ function syncEditorSettingsDraftFromStore() {
|
|||||||
editVimModeEnabled.value = settingsStore.editorSettings.vimModeEnabled;
|
editVimModeEnabled.value = settingsStore.editorSettings.vimModeEnabled;
|
||||||
editDoubleClickStringSelectionMode.value = settingsStore.editorSettings.doubleClickStringSelectionMode;
|
editDoubleClickStringSelectionMode.value = settingsStore.editorSettings.doubleClickStringSelectionMode;
|
||||||
editAutoCloseBrackets.value = settingsStore.editorSettings.autoCloseBrackets;
|
editAutoCloseBrackets.value = settingsStore.editorSettings.autoCloseBrackets;
|
||||||
|
editRestoreSqlFromSourcePasteEnabled.value = settingsStore.editorSettings.restoreSqlFromSourcePasteEnabled;
|
||||||
editSqlSemanticDiagnosticsMode.value = settingsStore.editorSettings.sqlSemanticDiagnosticsMode;
|
editSqlSemanticDiagnosticsMode.value = settingsStore.editorSettings.sqlSemanticDiagnosticsMode;
|
||||||
editSqlSemanticDiagnosticsEnabled.value = settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled;
|
editSqlSemanticDiagnosticsEnabled.value = settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled;
|
||||||
editConfirmDangerousSqlExecution.value = settingsStore.editorSettings.confirmDangerousSqlExecution;
|
editConfirmDangerousSqlExecution.value = settingsStore.editorSettings.confirmDangerousSqlExecution;
|
||||||
@@ -1868,6 +1871,7 @@ const editorSettingsDraftRefs: EditorSettingsDraftRefMap = {
|
|||||||
vimModeEnabled: editVimModeEnabled,
|
vimModeEnabled: editVimModeEnabled,
|
||||||
doubleClickStringSelectionMode: editDoubleClickStringSelectionMode,
|
doubleClickStringSelectionMode: editDoubleClickStringSelectionMode,
|
||||||
autoCloseBrackets: editAutoCloseBrackets,
|
autoCloseBrackets: editAutoCloseBrackets,
|
||||||
|
restoreSqlFromSourcePasteEnabled: editRestoreSqlFromSourcePasteEnabled,
|
||||||
sqlSemanticDiagnosticsMode: editSqlSemanticDiagnosticsMode,
|
sqlSemanticDiagnosticsMode: editSqlSemanticDiagnosticsMode,
|
||||||
confirmDangerousSqlExecution: editConfirmDangerousSqlExecution,
|
confirmDangerousSqlExecution: editConfirmDangerousSqlExecution,
|
||||||
confirmUnsavedSqlClose: editConfirmUnsavedSqlClose,
|
confirmUnsavedSqlClose: editConfirmUnsavedSqlClose,
|
||||||
@@ -2362,6 +2366,7 @@ function resetDefaultsForTab(tab: SettingsCategory) {
|
|||||||
editVimModeEnabled.value = DEFAULT_EDITOR_SETTINGS.vimModeEnabled;
|
editVimModeEnabled.value = DEFAULT_EDITOR_SETTINGS.vimModeEnabled;
|
||||||
editDoubleClickStringSelectionMode.value = DEFAULT_EDITOR_SETTINGS.doubleClickStringSelectionMode;
|
editDoubleClickStringSelectionMode.value = DEFAULT_EDITOR_SETTINGS.doubleClickStringSelectionMode;
|
||||||
editAutoCloseBrackets.value = DEFAULT_EDITOR_SETTINGS.autoCloseBrackets;
|
editAutoCloseBrackets.value = DEFAULT_EDITOR_SETTINGS.autoCloseBrackets;
|
||||||
|
editRestoreSqlFromSourcePasteEnabled.value = DEFAULT_EDITOR_SETTINGS.restoreSqlFromSourcePasteEnabled;
|
||||||
editSqlSemanticDiagnosticsMode.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsMode;
|
editSqlSemanticDiagnosticsMode.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsMode;
|
||||||
editSqlSemanticDiagnosticsEnabled.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsEnabled;
|
editSqlSemanticDiagnosticsEnabled.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsEnabled;
|
||||||
editConfirmDangerousSqlExecution.value = DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution;
|
editConfirmDangerousSqlExecution.value = DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution;
|
||||||
@@ -2524,6 +2529,7 @@ function resetAllDefaults() {
|
|||||||
editVimModeEnabled.value = DEFAULT_EDITOR_SETTINGS.vimModeEnabled;
|
editVimModeEnabled.value = DEFAULT_EDITOR_SETTINGS.vimModeEnabled;
|
||||||
editDoubleClickStringSelectionMode.value = DEFAULT_EDITOR_SETTINGS.doubleClickStringSelectionMode;
|
editDoubleClickStringSelectionMode.value = DEFAULT_EDITOR_SETTINGS.doubleClickStringSelectionMode;
|
||||||
editAutoCloseBrackets.value = DEFAULT_EDITOR_SETTINGS.autoCloseBrackets;
|
editAutoCloseBrackets.value = DEFAULT_EDITOR_SETTINGS.autoCloseBrackets;
|
||||||
|
editRestoreSqlFromSourcePasteEnabled.value = DEFAULT_EDITOR_SETTINGS.restoreSqlFromSourcePasteEnabled;
|
||||||
editSqlSemanticDiagnosticsMode.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsMode;
|
editSqlSemanticDiagnosticsMode.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsMode;
|
||||||
editSqlSemanticDiagnosticsEnabled.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsEnabled;
|
editSqlSemanticDiagnosticsEnabled.value = DEFAULT_EDITOR_SETTINGS.sqlSemanticDiagnosticsEnabled;
|
||||||
editConfirmDangerousSqlExecution.value = DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution;
|
editConfirmDangerousSqlExecution.value = DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution;
|
||||||
@@ -6714,6 +6720,16 @@ onUnmounted(() => {
|
|||||||
<Switch id="editor-auto-close-brackets" v-model="editAutoCloseBrackets" class="mt-0.5" />
|
<Switch id="editor-auto-close-brackets" v-model="editAutoCloseBrackets" class="mt-0.5" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
|
||||||
|
<div class="space-y-1">
|
||||||
|
<Label for="editor-restore-sql-from-source-paste">{{ t("settings.restoreSqlFromSourcePaste") }}</Label>
|
||||||
|
<p class="text-xs text-muted-foreground">
|
||||||
|
{{ t("settings.restoreSqlFromSourcePasteDescription") }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Switch id="editor-restore-sql-from-source-paste" v-model="editRestoreSqlFromSourcePasteEnabled" class="mt-0.5" />
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
|
<div class="settings-item flex items-center justify-between gap-4 rounded-md border bg-muted/20 px-3 py-2">
|
||||||
<div class="space-y-1">
|
<div class="space-y-1">
|
||||||
<Label for="editor-insert-space-after-completion">{{ t("settings.insertSpaceAfterCompletion") }}</Label>
|
<Label for="editor-insert-space-after-completion">{{ t("settings.insertSpaceAfterCompletion") }}</Label>
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ import { looksLikeDmlStatement } from "@/lib/sql/dmlChangePreview";
|
|||||||
|
|
||||||
import { canFormatSqlForDatabaseType, formatSqlForEditing, compressSqlText } from "@/lib/sql/sqlFormatter";
|
import { canFormatSqlForDatabaseType, formatSqlForEditing, compressSqlText } from "@/lib/sql/sqlFormatter";
|
||||||
import { detectAndFormatStructured } from "@/lib/sql/autoFormat";
|
import { detectAndFormatStructured } from "@/lib/sql/autoFormat";
|
||||||
|
import { restoreSqlFromSourcePaste } from "@/lib/sql/sqlSourcePaste";
|
||||||
import { enabledSqlParameterSyntaxes, resolveSqlVariableSyntaxToggles } from "@/lib/sql/sqlVariableSyntax";
|
import { enabledSqlParameterSyntaxes, resolveSqlVariableSyntaxToggles } from "@/lib/sql/sqlVariableSyntax";
|
||||||
|
|
||||||
import { createQueryEditorExecutionViewportOwnership, isQueryEditorPositionVisible } from "@/lib/editor/queryEditorExecutionViewport";
|
import { createQueryEditorExecutionViewportOwnership, isQueryEditorPositionVisible } from "@/lib/editor/queryEditorExecutionViewport";
|
||||||
@@ -281,6 +282,7 @@ const {
|
|||||||
copySelectedSqlAsRichTextFromContextMenu,
|
copySelectedSqlAsRichTextFromContextMenu,
|
||||||
cutSelectedSqlFromContextMenu,
|
cutSelectedSqlFromContextMenu,
|
||||||
pasteClipboardSqlFromContextMenu,
|
pasteClipboardSqlFromContextMenu,
|
||||||
|
pasteClipboardSqlRestoringSource,
|
||||||
toggleCommentFromContextMenu,
|
toggleCommentFromContextMenu,
|
||||||
toggleBlockCommentFromContextMenu,
|
toggleBlockCommentFromContextMenu,
|
||||||
selectAllSqlFromContextMenu,
|
selectAllSqlFromContextMenu,
|
||||||
@@ -1038,6 +1040,34 @@ function resyncCaretAfterPaste(view: EditorViewType) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 粘贴时尝试把「源码里的字符串拼接 SQL」(Java/JS/Python 等)还原为普通 SQL。
|
||||||
|
* 命中后自行插入并阻止默认粘贴;未命中返回 false,交给原有粘贴流程处理。
|
||||||
|
*/
|
||||||
|
function tryRestoreSqlFromSourcePaste(event: ClipboardEvent, currentView: EditorViewType): boolean {
|
||||||
|
if (props.readOnly || !settingsStore.editorSettings.restoreSqlFromSourcePasteEnabled) return false;
|
||||||
|
if (currentView.state.selection.ranges.length !== 1) return false;
|
||||||
|
const eventText = event.clipboardData?.getData("text/plain") ?? "";
|
||||||
|
if (!eventText) return false;
|
||||||
|
// Tauri 下超长文本会被 WebView 截断、之后异步补写后半段,这里不参与还原以免破坏片段边界
|
||||||
|
if (shouldRecoverLargeTauriPaste(eventText, isTauriRuntime())) return false;
|
||||||
|
|
||||||
|
const restored = restoreSqlFromSourcePaste(eventText);
|
||||||
|
if (!restored.changed) return false;
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
const selection = currentView.state.selection.main;
|
||||||
|
const insertedText = normalizeQueryEditorPasteText(restored.sql);
|
||||||
|
currentView.dispatch({
|
||||||
|
changes: { from: selection.from, to: selection.to, insert: insertedText },
|
||||||
|
selection: { anchor: selection.from + insertedText.length },
|
||||||
|
scrollIntoView: true,
|
||||||
|
userEvent: "input.paste",
|
||||||
|
});
|
||||||
|
toast(t("editor.sqlSourcePasteRestored"), 2000);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
function recoverLargeTauriPaste(event: ClipboardEvent, currentView: EditorViewType): boolean {
|
function recoverLargeTauriPaste(event: ClipboardEvent, currentView: EditorViewType): boolean {
|
||||||
const eventText = event.clipboardData?.getData("text/plain") ?? "";
|
const eventText = event.clipboardData?.getData("text/plain") ?? "";
|
||||||
if (props.readOnly || currentView.state.selection.ranges.length !== 1 || !shouldRecoverLargeTauriPaste(eventText, isTauriRuntime())) return false;
|
if (props.readOnly || currentView.state.selection.ranges.length !== 1 || !shouldRecoverLargeTauriPaste(eventText, isTauriRuntime())) return false;
|
||||||
@@ -1166,6 +1196,7 @@ const contextMenuActions: QueryEditorContextMenuActions = {
|
|||||||
copySelectedSqlAsRichTextFromContextMenu,
|
copySelectedSqlAsRichTextFromContextMenu,
|
||||||
cutSelectedSqlFromContextMenu,
|
cutSelectedSqlFromContextMenu,
|
||||||
pasteClipboardSqlFromContextMenu,
|
pasteClipboardSqlFromContextMenu,
|
||||||
|
pasteClipboardSqlRestoringSource,
|
||||||
convertSelectedSqlCase,
|
convertSelectedSqlCase,
|
||||||
convertSelectedNamingStyle,
|
convertSelectedNamingStyle,
|
||||||
openDelimitedListDialog,
|
openDelimitedListDialog,
|
||||||
@@ -2055,6 +2086,7 @@ const codeMirrorLifecycle = useQueryEditorCodeMirror({
|
|||||||
),
|
),
|
||||||
EditorView.domEventHandlers({
|
EditorView.domEventHandlers({
|
||||||
paste(event, currentView) {
|
paste(event, currentView) {
|
||||||
|
if (tryRestoreSqlFromSourcePaste(event, currentView)) return true;
|
||||||
return recoverLargeTauriPaste(event, currentView);
|
return recoverLargeTauriPaste(event, currentView);
|
||||||
},
|
},
|
||||||
dragover(event) {
|
dragover(event) {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed } from "vue";
|
import { computed } from "vue";
|
||||||
import { useI18n } from "vue-i18n";
|
import { useI18n } from "vue-i18n";
|
||||||
import { AlignLeft, Camera, CaseLower, CaseSensitive, CaseUpper, ClipboardPaste, Code2, Columns3, Download, Eye, FileCode, Highlighter, MessageSquareText, Minimize2, Pencil, PencilRuler, Play, Copy, List, Scissors, Search, Sparkles, Table2, TextSelect, Trash2 } from "@lucide/vue";
|
import { AlignLeft, Camera, CaseLower, CaseSensitive, CaseUpper, ClipboardPaste, Code2, Columns3, Download, Eye, FileCode, Highlighter, MessageSquareText, Minimize2, Pencil, PencilRuler, Play, Copy, List, Scissors, Search, Sparkles, Table2, TextSelect, Trash2, WandSparkles } from "@lucide/vue";
|
||||||
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
|
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";
|
||||||
import { canFormatSqlForDatabaseType } from "@/lib/sql/sqlFormatter";
|
import { canFormatSqlForDatabaseType } from "@/lib/sql/sqlFormatter";
|
||||||
import { supportsQueryEditorBlockComments } from "@/lib/database/databaseFeatureSupport";
|
import { supportsQueryEditorBlockComments } from "@/lib/database/databaseFeatureSupport";
|
||||||
@@ -35,6 +35,7 @@ export interface QueryEditorContextMenuActions {
|
|||||||
copySelectedSqlAsRichTextFromContextMenu: () => void;
|
copySelectedSqlAsRichTextFromContextMenu: () => void;
|
||||||
cutSelectedSqlFromContextMenu: () => void;
|
cutSelectedSqlFromContextMenu: () => void;
|
||||||
pasteClipboardSqlFromContextMenu: () => void;
|
pasteClipboardSqlFromContextMenu: () => void;
|
||||||
|
pasteClipboardSqlRestoringSource: () => void;
|
||||||
convertSelectedSqlCase: (mode: "upper" | "lower") => void;
|
convertSelectedSqlCase: (mode: "upper" | "lower") => void;
|
||||||
convertSelectedNamingStyle: () => void;
|
convertSelectedNamingStyle: () => void;
|
||||||
openDelimitedListDialog: () => void;
|
openDelimitedListDialog: () => void;
|
||||||
@@ -215,6 +216,13 @@ const contextMenuItems = computed<ContextMenuItem[]>(() => {
|
|||||||
icon: ClipboardPaste,
|
icon: ClipboardPaste,
|
||||||
shortcut: "Mod+V",
|
shortcut: "Mod+V",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// 显式入口:即使关闭了「粘贴时自动还原源码 SQL」设置也能使用
|
||||||
|
label: t("editor.contextMenu.pasteRestoringSourceSql"),
|
||||||
|
action: actions.pasteClipboardSqlRestoringSource,
|
||||||
|
disabled: state.readOnly,
|
||||||
|
icon: WandSparkles,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
label: t("editor.contextMenu.sendToAi"),
|
label: t("editor.contextMenu.sendToAi"),
|
||||||
action: () => {
|
action: () => {
|
||||||
|
|||||||
+122
@@ -0,0 +1,122 @@
|
|||||||
|
// @vitest-environment happy-dom
|
||||||
|
|
||||||
|
import { createApp, h, nextTick, reactive, shallowRef } from "vue";
|
||||||
|
import { createPinia, setActivePinia } from "pinia";
|
||||||
|
import { createI18n } from "vue-i18n";
|
||||||
|
import { EditorView } from "@codemirror/view";
|
||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import QueryEditor from "../QueryEditor.vue";
|
||||||
|
import { useSettingsStore } from "@/stores/settingsStore";
|
||||||
|
import { useConnectionStore } from "@/stores/connectionStore";
|
||||||
|
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||||
|
|
||||||
|
vi.mock("@/lib/common/clipboard", () => ({
|
||||||
|
copyToClipboard: vi.fn().mockResolvedValue(undefined),
|
||||||
|
readTextFromClipboard: vi.fn().mockResolvedValue(""),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Java 风格:字符串拼接 + 源码层 `\n` 转义
|
||||||
|
const SOURCE_SQL = '"SELECT * " +\n"FROM users \\n " +\n"WHERE id = 1"';
|
||||||
|
const RESTORED_SQL = "SELECT * FROM users \n WHERE id = 1";
|
||||||
|
const PLAIN_SQL = "SELECT * FROM users WHERE id = 1";
|
||||||
|
|
||||||
|
const cleanups: Array<() => void> = [];
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function mountEditor(overrides: Partial<QueryEditorProps> = {}) {
|
||||||
|
const pinia = createPinia();
|
||||||
|
setActivePinia(pinia);
|
||||||
|
const settingsStore = useSettingsStore();
|
||||||
|
useConnectionStore();
|
||||||
|
const props = reactive<QueryEditorProps>({ modelValue: "", tabId: "source-paste", databaseType: "mysql", dialect: "mysql", autoFocus: false, ...overrides });
|
||||||
|
const editor = shallowRef<InstanceType<typeof QueryEditor>>();
|
||||||
|
const host = document.createElement("div");
|
||||||
|
document.body.append(host);
|
||||||
|
const app = createApp({
|
||||||
|
render: () =>
|
||||||
|
h(QueryEditor, {
|
||||||
|
...props,
|
||||||
|
ref: editor,
|
||||||
|
"onUpdate:modelValue": (value: string) => {
|
||||||
|
props.modelValue = value;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
app.use(pinia);
|
||||||
|
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
|
||||||
|
app.mount(host);
|
||||||
|
cleanups.push(() => {
|
||||||
|
app.unmount();
|
||||||
|
host.remove();
|
||||||
|
});
|
||||||
|
await vi.waitFor(() => expect(host.querySelector(".cm-editor")).not.toBeNull(), { timeout: 5000 });
|
||||||
|
const view = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
|
||||||
|
return { view, props, settingsStore };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 构造带纯文本剪贴板内容的 paste 事件(happy-dom 没有 ClipboardEvent 实现) */
|
||||||
|
function pasteEvent(text: string): Event {
|
||||||
|
const event = new Event("paste", { bubbles: true, cancelable: true });
|
||||||
|
Object.defineProperty(event, "clipboardData", { value: { getData: (type: string) => (type === "text/plain" ? text : "") } });
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pasteInto(view: EditorView, text: string): Promise<Event> {
|
||||||
|
const event = pasteEvent(text);
|
||||||
|
view.contentDOM.dispatchEvent(event);
|
||||||
|
await nextTick();
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("QueryEditor source-code SQL paste", () => {
|
||||||
|
it("restores concatenated source SQL when the setting is enabled", async () => {
|
||||||
|
const { view, settingsStore } = await mountEditor();
|
||||||
|
expect(settingsStore.editorSettings.restoreSqlFromSourcePasteEnabled).toBe(true);
|
||||||
|
|
||||||
|
await pasteInto(view, SOURCE_SQL);
|
||||||
|
expect(view.state.doc.toString()).toBe(RESTORED_SQL);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("claims the paste event when it restores the SQL", async () => {
|
||||||
|
const { view } = await mountEditor();
|
||||||
|
|
||||||
|
// 还原路径自己完成插入并阻止默认粘贴,保证只写入一次
|
||||||
|
const event = await pasteInto(view, SOURCE_SQL);
|
||||||
|
expect(event.defaultPrevented).toBe(true);
|
||||||
|
expect(view.state.doc.toString()).toBe(RESTORED_SQL);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the pasted text untouched when the setting is disabled", async () => {
|
||||||
|
const { view, settingsStore } = await mountEditor();
|
||||||
|
settingsStore.editorSettings.restoreSqlFromSourcePasteEnabled = false;
|
||||||
|
|
||||||
|
await pasteInto(view, SOURCE_SQL);
|
||||||
|
expect(view.state.doc.toString()).not.toBe(RESTORED_SQL);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the pasted text untouched when the editor is read-only", async () => {
|
||||||
|
const { view } = await mountEditor({ readOnly: true });
|
||||||
|
|
||||||
|
await pasteInto(view, SOURCE_SQL);
|
||||||
|
expect(view.state.doc.toString()).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("replaces the current selection with the restored SQL as one undoable edit", async () => {
|
||||||
|
const { view } = await mountEditor({ modelValue: "SELECT 0" });
|
||||||
|
view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } });
|
||||||
|
|
||||||
|
await pasteInto(view, SOURCE_SQL);
|
||||||
|
expect(view.state.doc.toString()).toBe(RESTORED_SQL);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves plain SQL paste to the default editor behavior", async () => {
|
||||||
|
const { view } = await mountEditor();
|
||||||
|
|
||||||
|
await pasteInto(view, PLAIN_SQL);
|
||||||
|
expect(view.state.doc.toString()).not.toBe(RESTORED_SQL);
|
||||||
|
});
|
||||||
|
});
|
||||||
+16
@@ -133,6 +133,22 @@ describe("QueryEditor extracted text actions", () => {
|
|||||||
expect(clipboard.readTextFromClipboard).toHaveBeenCalledTimes(1);
|
expect(clipboard.readTextFromClipboard).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("restores source-code SQL through the explicit paste action", async () => {
|
||||||
|
clipboard.readTextFromClipboard.mockResolvedValue('"SELECT * " +\n"FROM users \\n " +\n"WHERE id = 1"');
|
||||||
|
const { actions, editorView } = mountActions("");
|
||||||
|
await actions.pasteClipboardSqlRestoringSource();
|
||||||
|
expect(editorView.state.doc.toString()).toBe("SELECT * FROM users \n WHERE id = 1");
|
||||||
|
expect(undo(editorView)).toBe(true);
|
||||||
|
expect(editorView.state.doc.toString()).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("pastes the original text when the clipboard is not a source-code SQL concatenation", async () => {
|
||||||
|
clipboard.readTextFromClipboard.mockResolvedValue("SELECT * FROM users");
|
||||||
|
const { actions, editorView } = mountActions("");
|
||||||
|
await actions.pasteClipboardSqlRestoringSource();
|
||||||
|
expect(editorView.state.doc.toString()).toBe("SELECT * FROM users");
|
||||||
|
});
|
||||||
|
|
||||||
it("preserves multi-range case conversion and selects each replacement", () => {
|
it("preserves multi-range case conversion and selects each replacement", () => {
|
||||||
const { actions, editorView } = mountActions("select id, name from users");
|
const { actions, editorView } = mountActions("select id, name from users");
|
||||||
editorView.dispatch({ selection: EditorSelection.create([EditorSelection.range(0, 6), EditorSelection.range(16, 20)]) });
|
editorView.dispatch({ selection: EditorSelection.create([EditorSelection.range(0, 6), EditorSelection.range(16, 20)]) });
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { copyToClipboard, readTextFromClipboard } from "@/lib/common/clipboard";
|
|||||||
import { blankLineDeletionChanges, replaceSelectedEditorText } from "@/lib/editor/queryEditorTextEdits";
|
import { blankLineDeletionChanges, replaceSelectedEditorText } from "@/lib/editor/queryEditorTextEdits";
|
||||||
import { queryEditorClipboardPasteChange } from "@/lib/editor/queryEditorClipboardPaste";
|
import { queryEditorClipboardPasteChange } from "@/lib/editor/queryEditorClipboardPaste";
|
||||||
import { buildSqlInConditionFromPasteSource, insertTextForSqlInCondition } from "@/lib/sql/sqlInListPaste";
|
import { buildSqlInConditionFromPasteSource, insertTextForSqlInCondition } from "@/lib/sql/sqlInListPaste";
|
||||||
|
import { restoreSqlFromSourcePaste } from "@/lib/sql/sqlSourcePaste";
|
||||||
import { convertSqlSelectionCase, type SqlSelectionCaseMode } from "@/lib/sql/sqlSelectionCase";
|
import { convertSqlSelectionCase, type SqlSelectionCaseMode } from "@/lib/sql/sqlSelectionCase";
|
||||||
import { convertToNextNamingStyle } from "@/lib/naming/namingStyleConverter";
|
import { convertToNextNamingStyle } from "@/lib/naming/namingStyleConverter";
|
||||||
import { copySqlAsRichText } from "@/lib/sql/sqlRichText";
|
import { copySqlAsRichText } from "@/lib/sql/sqlRichText";
|
||||||
@@ -125,6 +126,29 @@ export function useQueryEditorTextActions(options: QueryEditorTextActionsOptions
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 粘贴并还原源码 SQL:显式入口,即使「粘贴时自动还原」开关关闭也可以使用
|
||||||
|
async function pasteClipboardSqlRestoringSource() {
|
||||||
|
if (props.readOnly) return;
|
||||||
|
const currentView = view.value;
|
||||||
|
if (!currentView) return;
|
||||||
|
try {
|
||||||
|
const text = await readTextFromClipboard();
|
||||||
|
if (!text) return;
|
||||||
|
const result = restoreSqlFromSourcePaste(text);
|
||||||
|
const selection = currentView.state.selection.main;
|
||||||
|
currentView.dispatch({
|
||||||
|
...queryEditorClipboardPasteChange(result.sql, selection.from, selection.to),
|
||||||
|
scrollIntoView: true,
|
||||||
|
userEvent: "input.paste",
|
||||||
|
});
|
||||||
|
// 未识别时也照常插入原文,但要提示用户没有发生还原
|
||||||
|
toast(result.changed ? t("editor.sqlSourcePasteRestored") : t("editor.sqlSourcePasteNotDetected"), result.changed ? 2000 : 3000);
|
||||||
|
focusEditor();
|
||||||
|
} catch (e: any) {
|
||||||
|
toast(t("editor.contextMenu.pasteClipboardReadFailed", { message: e?.message || String(e) }), 5000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function toggleCommentFromContextMenu() {
|
function toggleCommentFromContextMenu() {
|
||||||
const currentView = view.value;
|
const currentView = view.value;
|
||||||
if (!currentView || props.readOnly) return;
|
if (!currentView || props.readOnly) return;
|
||||||
@@ -291,6 +315,7 @@ export function useQueryEditorTextActions(options: QueryEditorTextActionsOptions
|
|||||||
copySelectedSqlAsRichTextFromContextMenu,
|
copySelectedSqlAsRichTextFromContextMenu,
|
||||||
cutSelectedSqlFromContextMenu,
|
cutSelectedSqlFromContextMenu,
|
||||||
pasteClipboardSqlFromContextMenu,
|
pasteClipboardSqlFromContextMenu,
|
||||||
|
pasteClipboardSqlRestoringSource,
|
||||||
toggleCommentFromContextMenu,
|
toggleCommentFromContextMenu,
|
||||||
toggleBlockCommentFromContextMenu,
|
toggleBlockCommentFromContextMenu,
|
||||||
selectAllSqlFromContextMenu,
|
selectAllSqlFromContextMenu,
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import az from "../locales/az";
|
||||||
|
import en from "../locales/en";
|
||||||
|
import es from "../locales/es";
|
||||||
|
import it_ from "../locales/it";
|
||||||
|
import ja from "../locales/ja";
|
||||||
|
import ko from "../locales/ko";
|
||||||
|
import ptBR from "../locales/pt-BR";
|
||||||
|
import ru from "../locales/ru";
|
||||||
|
import tr from "../locales/tr";
|
||||||
|
import zhCN from "../locales/zh-CN";
|
||||||
|
import zhTW from "../locales/zh-TW";
|
||||||
|
|
||||||
|
// 「粘贴源码 SQL 自动还原」相关文案需要所有语言齐全,避免回落到英文
|
||||||
|
const SETTINGS_KEYS = ["restoreSqlFromSourcePaste", "restoreSqlFromSourcePasteDescription"] as const;
|
||||||
|
const EDITOR_KEYS = ["sqlSourcePasteRestored", "sqlSourcePasteNotDetected"] as const;
|
||||||
|
const CONTEXT_MENU_KEYS = ["pasteRestoringSourceSql"] as const;
|
||||||
|
|
||||||
|
const locales: Array<[string, Record<string, unknown>]> = [
|
||||||
|
["en", en as Record<string, unknown>],
|
||||||
|
["az", az as Record<string, unknown>],
|
||||||
|
["es", es],
|
||||||
|
["it", it_],
|
||||||
|
["ja", ja],
|
||||||
|
["ko", ko],
|
||||||
|
["pt-BR", ptBR],
|
||||||
|
["ru", ru],
|
||||||
|
["tr", tr],
|
||||||
|
["zh-CN", zhCN],
|
||||||
|
["zh-TW", zhTW],
|
||||||
|
];
|
||||||
|
|
||||||
|
function nested(locale: Record<string, unknown>, path: string[]): Record<string, unknown> | undefined {
|
||||||
|
let scope: unknown = locale;
|
||||||
|
for (const segment of path) {
|
||||||
|
if (!scope || typeof scope !== "object") return undefined;
|
||||||
|
scope = (scope as Record<string, unknown>)[segment];
|
||||||
|
}
|
||||||
|
return scope && typeof scope === "object" ? (scope as Record<string, unknown>) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function settingsText(locale: Record<string, unknown>, key: string): unknown {
|
||||||
|
return nested(locale, ["settings"])?.[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
function editorText(locale: Record<string, unknown>, key: string): unknown {
|
||||||
|
return nested(locale, ["editor"])?.[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
function contextMenuText(locale: Record<string, unknown>, key: string): unknown {
|
||||||
|
return nested(locale, ["editor", "contextMenu"])?.[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
const english = en as Record<string, unknown>;
|
||||||
|
|
||||||
|
describe("source-code SQL paste i18n messages", () => {
|
||||||
|
it.each(SETTINGS_KEYS)("en resolves settings.%s to text", (key) => {
|
||||||
|
expect(settingsText(english, key), `settings.${key} missing from locales/en.ts`).toBeTypeOf("string");
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(EDITOR_KEYS)("en resolves editor.%s to text", (key) => {
|
||||||
|
expect(editorText(english, key), `editor.${key} missing from locales/en.ts`).toBeTypeOf("string");
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(CONTEXT_MENU_KEYS)("en resolves editor.contextMenu.%s to text", (key) => {
|
||||||
|
expect(contextMenuText(english, key), `editor.contextMenu.${key} missing from locales/en.ts`).toBeTypeOf("string");
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(locales.slice(1))("%s translates the source-code SQL paste labels instead of using the English fallback", (_name, locale) => {
|
||||||
|
for (const key of SETTINGS_KEYS) {
|
||||||
|
expect(settingsText(locale, key), `${_name} settings.${key}`).toBeTypeOf("string");
|
||||||
|
expect(settingsText(locale, key), `${_name} settings.${key} should not reuse the English text`).not.toBe(settingsText(english, key));
|
||||||
|
}
|
||||||
|
for (const key of EDITOR_KEYS) {
|
||||||
|
expect(editorText(locale, key), `${_name} editor.${key}`).toBeTypeOf("string");
|
||||||
|
expect(editorText(locale, key), `${_name} editor.${key} should not reuse the English text`).not.toBe(editorText(english, key));
|
||||||
|
}
|
||||||
|
for (const key of CONTEXT_MENU_KEYS) {
|
||||||
|
expect(contextMenuText(locale, key), `${_name} editor.contextMenu.${key}`).toBeTypeOf("string");
|
||||||
|
expect(contextMenuText(locale, key), `${_name} editor.contextMenu.${key} should not reuse the English text`).not.toBe(contextMenuText(english, key));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1451,6 +1451,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "Dəyər sayı çoxdur. Dəstəklənən maksimum say {limit}.",
|
exPasteTooManyValues: "Dəyər sayı çoxdur. Dəstəklənən maksimum say {limit}.",
|
||||||
exPasteClipboardReadFailed: "Mübadilə buferini oxumaq mümkün olmadı: {message}",
|
exPasteClipboardReadFailed: "Mübadilə buferini oxumaq mümkün olmadı: {message}",
|
||||||
exPastePasted: "IN şərti üçün {count} dəyər yerləşdirildi",
|
exPastePasted: "IN şərti üçün {count} dəyər yerləşdirildi",
|
||||||
|
sqlSourcePasteRestored: "SQL mənbə koddan bərpa edildi (əvvəlki mətn üçün geri alın)",
|
||||||
|
sqlSourcePasteNotDetected: "Birləşdirilmiş SQL aşkar olunmadı; orijinal mətn yapışdırıldı",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "NULL dəyəri",
|
nullValue: "NULL dəyəri",
|
||||||
isNull: "NULL olub-olmadığını yoxla",
|
isNull: "NULL olub-olmadığını yoxla",
|
||||||
@@ -1560,6 +1562,7 @@ export default withEnglishFallback({
|
|||||||
compressSelectionSql: "Seçilmiş SQL-i sıxlaşdır",
|
compressSelectionSql: "Seçilmiş SQL-i sıxlaşdır",
|
||||||
cutSelection: "Seçimi kəs",
|
cutSelection: "Seçimi kəs",
|
||||||
pasteFromClipboard: "Yerləşdir",
|
pasteFromClipboard: "Yerləşdir",
|
||||||
|
pasteRestoringSourceSql: "Yapışdır və mənbə SQL-i bərpa et",
|
||||||
pasteClipboardReadFailed: "Mübadilə buferini oxumaq mümkün olmadı: {message}",
|
pasteClipboardReadFailed: "Mübadilə buferini oxumaq mümkün olmadı: {message}",
|
||||||
sendToAi: "Süni intellektə göndər",
|
sendToAi: "Süni intellektə göndər",
|
||||||
uppercaseSelection: "Böyük hərflərə çevir",
|
uppercaseSelection: "Böyük hərflərə çevir",
|
||||||
@@ -7725,6 +7728,8 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Vim rejimi",
|
vimMode: "Vim rejimi",
|
||||||
vimModeDescription: "SQL redaktorunda Vim üslublu modal redaktədən istifadə et",
|
vimModeDescription: "SQL redaktorunda Vim üslublu modal redaktədən istifadə et",
|
||||||
autoCloseBrackets: "Mötərizələri avtomatik bağla",
|
autoCloseBrackets: "Mötərizələri avtomatik bağla",
|
||||||
|
restoreSqlFromSourcePaste: "Mənbə koddan yapışdırılan SQL-i bərpa et",
|
||||||
|
restoreSqlFromSourcePasteDescription: "Java, JavaScript, Python və bənzər mənbələrdən kopyalanan sətir birləşdirməli SQL (dırnaqlar, plus işarələri və escape sətir keçidləri) yapışdırılarkən adi SQL-ə bərpa olunur. Yalnız aydın birləşdirmələr çevrilir, digər məzmun olduğu kimi yapışdırılır.",
|
||||||
autoCloseBracketsDescription: "Açılış mötərizəsi və ya dırnaq yazılarkən bağlanış işarəsini avtomatik daxil et",
|
autoCloseBracketsDescription: "Açılış mötərizəsi və ya dırnaq yazılarkən bağlanış işarəsini avtomatik daxil et",
|
||||||
sqlCompletionSection: "SQL tamamlaması",
|
sqlCompletionSection: "SQL tamamlaması",
|
||||||
insertSpaceAfterCompletion: "Tamamlamadan sonra boşluq daxil et",
|
insertSpaceAfterCompletion: "Tamamlamadan sonra boşluq daxil et",
|
||||||
|
|||||||
@@ -1758,6 +1758,8 @@ export default {
|
|||||||
exPasteTooManyValues: "Too many values. Maximum supported count is {limit}.",
|
exPasteTooManyValues: "Too many values. Maximum supported count is {limit}.",
|
||||||
exPasteClipboardReadFailed: "Failed to read clipboard: {message}",
|
exPasteClipboardReadFailed: "Failed to read clipboard: {message}",
|
||||||
exPastePasted: "Pasted {count} IN condition values",
|
exPastePasted: "Pasted {count} IN condition values",
|
||||||
|
sqlSourcePasteRestored: "Restored SQL from source code (undo to get the original text)",
|
||||||
|
sqlSourcePasteNotDetected: "No concatenated SQL detected; pasted the original text",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "NULL value",
|
nullValue: "NULL value",
|
||||||
isNull: "Check if NULL",
|
isNull: "Check if NULL",
|
||||||
@@ -1867,6 +1869,7 @@ export default {
|
|||||||
compressSelectionSql: "Compress selected SQL",
|
compressSelectionSql: "Compress selected SQL",
|
||||||
cutSelection: "Cut selection",
|
cutSelection: "Cut selection",
|
||||||
pasteFromClipboard: "Paste",
|
pasteFromClipboard: "Paste",
|
||||||
|
pasteRestoringSourceSql: "Paste and restore source SQL",
|
||||||
pasteClipboardReadFailed: "Failed to read clipboard: {message}",
|
pasteClipboardReadFailed: "Failed to read clipboard: {message}",
|
||||||
sendToAi: "Send to AI",
|
sendToAi: "Send to AI",
|
||||||
uppercaseSelection: "Convert to uppercase",
|
uppercaseSelection: "Convert to uppercase",
|
||||||
@@ -8557,6 +8560,8 @@ export default {
|
|||||||
vimMode: "Vim mode",
|
vimMode: "Vim mode",
|
||||||
vimModeDescription: "Use Vim-style modal editing in the SQL editor",
|
vimModeDescription: "Use Vim-style modal editing in the SQL editor",
|
||||||
autoCloseBrackets: "Auto-close brackets",
|
autoCloseBrackets: "Auto-close brackets",
|
||||||
|
restoreSqlFromSourcePaste: "Restore SQL pasted from source code",
|
||||||
|
restoreSqlFromSourcePasteDescription: "When pasting SQL assembled from string literals in Java, JavaScript, Python or similar source files (quotes, plus signs, escaped newlines), restore it to plain SQL. Only clear concatenations are rewritten; anything else is pasted as-is.",
|
||||||
autoCloseBracketsDescription: "Automatically insert closing brackets and quotes when typing an opening one",
|
autoCloseBracketsDescription: "Automatically insert closing brackets and quotes when typing an opening one",
|
||||||
sqlCompletionSection: "SQL completion",
|
sqlCompletionSection: "SQL completion",
|
||||||
insertSpaceAfterCompletion: "Insert a space after completion",
|
insertSpaceAfterCompletion: "Insert a space after completion",
|
||||||
|
|||||||
@@ -1722,6 +1722,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "Demasiados valores. Máximo {limit}.",
|
exPasteTooManyValues: "Demasiados valores. Máximo {limit}.",
|
||||||
exPasteClipboardReadFailed: "No se pudo leer el portapapeles: {message}",
|
exPasteClipboardReadFailed: "No se pudo leer el portapapeles: {message}",
|
||||||
exPastePasted: "Se pegaron {count} valores de condición IN",
|
exPastePasted: "Se pegaron {count} valores de condición IN",
|
||||||
|
sqlSourcePasteRestored: "SQL restaurado desde el código fuente (deshaz para recuperar el texto original)",
|
||||||
|
sqlSourcePasteNotDetected: "No se detectó SQL concatenado; se pegó el texto original",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "Valor NULL",
|
nullValue: "Valor NULL",
|
||||||
isNull: "Comprobar si es NULL",
|
isNull: "Comprobar si es NULL",
|
||||||
@@ -1838,6 +1840,7 @@ export default withEnglishFallback({
|
|||||||
deleteEmptyLines: "Eliminar líneas vacías",
|
deleteEmptyLines: "Eliminar líneas vacías",
|
||||||
cutSelection: "Cortar selección",
|
cutSelection: "Cortar selección",
|
||||||
pasteFromClipboard: "Pegar",
|
pasteFromClipboard: "Pegar",
|
||||||
|
pasteRestoringSourceSql: "Pegar y restaurar SQL de origen",
|
||||||
pasteClipboardReadFailed: "Error al leer el portapapeles: {message}",
|
pasteClipboardReadFailed: "Error al leer el portapapeles: {message}",
|
||||||
convertNamingStyle: "Cambiar estilo de nomenclatura",
|
convertNamingStyle: "Cambiar estilo de nomenclatura",
|
||||||
},
|
},
|
||||||
@@ -7775,6 +7778,8 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Modo Vim",
|
vimMode: "Modo Vim",
|
||||||
vimModeDescription: "Usar edición modal estilo Vim en el editor SQL",
|
vimModeDescription: "Usar edición modal estilo Vim en el editor SQL",
|
||||||
autoCloseBrackets: "Cerrar paréntesis automáticamente",
|
autoCloseBrackets: "Cerrar paréntesis automáticamente",
|
||||||
|
restoreSqlFromSourcePaste: "Restaurar SQL pegado desde código fuente",
|
||||||
|
restoreSqlFromSourcePasteDescription: "Al pegar SQL construido con literales de cadena en Java, JavaScript, Python y similares (comillas, signos más y saltos de línea escapados), se restaura como SQL normal. Solo se reescriben las concatenaciones claras; el resto se pega tal cual.",
|
||||||
autoCloseBracketsDescription: "Insertar automáticamente paréntesis y comillas de cierre al escribir los de apertura",
|
autoCloseBracketsDescription: "Insertar automáticamente paréntesis y comillas de cierre al escribir los de apertura",
|
||||||
sqlCompletionSection: "Autocompletado SQL",
|
sqlCompletionSection: "Autocompletado SQL",
|
||||||
selectFirstCompletionOnOpen: "Seleccionar automáticamente la primera sugerencia",
|
selectFirstCompletionOnOpen: "Seleccionar automáticamente la primera sugerencia",
|
||||||
|
|||||||
@@ -1656,6 +1656,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "Troppi valori. Massimo {limit}.",
|
exPasteTooManyValues: "Troppi valori. Massimo {limit}.",
|
||||||
exPasteClipboardReadFailed: "Impossibile leggere gli appunti: {message}",
|
exPasteClipboardReadFailed: "Impossibile leggere gli appunti: {message}",
|
||||||
exPastePasted: "Incollati {count} valori per la condizione IN",
|
exPastePasted: "Incollati {count} valori per la condizione IN",
|
||||||
|
sqlSourcePasteRestored: "SQL ripristinato dal codice sorgente (annulla per riavere il testo originale)",
|
||||||
|
sqlSourcePasteNotDetected: "Nessun SQL concatenato rilevato; incollato il testo originale",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "Valore NULL",
|
nullValue: "Valore NULL",
|
||||||
isNull: "Verifica se NULL",
|
isNull: "Verifica se NULL",
|
||||||
@@ -1772,6 +1774,7 @@ export default withEnglishFallback({
|
|||||||
deleteEmptyLines: "Elimina righe vuote",
|
deleteEmptyLines: "Elimina righe vuote",
|
||||||
cutSelection: "Taglia selezione",
|
cutSelection: "Taglia selezione",
|
||||||
pasteFromClipboard: "Incolla",
|
pasteFromClipboard: "Incolla",
|
||||||
|
pasteRestoringSourceSql: "Incolla e ripristina SQL sorgente",
|
||||||
pasteClipboardReadFailed: "Impossibile leggere gli appunti: {message}",
|
pasteClipboardReadFailed: "Impossibile leggere gli appunti: {message}",
|
||||||
convertNamingStyle: "Cambia stile di denominazione",
|
convertNamingStyle: "Cambia stile di denominazione",
|
||||||
},
|
},
|
||||||
@@ -7699,6 +7702,9 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Modalita Vim",
|
vimMode: "Modalita Vim",
|
||||||
vimModeDescription: "Usa la modifica modale in stile Vim nell'editor SQL",
|
vimModeDescription: "Usa la modifica modale in stile Vim nell'editor SQL",
|
||||||
autoCloseBrackets: "Chiusura automatica parentesi",
|
autoCloseBrackets: "Chiusura automatica parentesi",
|
||||||
|
restoreSqlFromSourcePaste: "Ripristina l'SQL incollato dal codice sorgente",
|
||||||
|
restoreSqlFromSourcePasteDescription:
|
||||||
|
"Quando incolli SQL costruito con letterali di stringa in Java, JavaScript, Python e simili (virgolette, segni più e a capo di escape), viene ripristinato come SQL normale. Solo le concatenazioni evidenti vengono riscritte; il resto viene incollato così com'è.",
|
||||||
autoCloseBracketsDescription: "Inserisci automaticamente parentesi e virgolette di chiusura quando digiti quelle di apertura",
|
autoCloseBracketsDescription: "Inserisci automaticamente parentesi e virgolette di chiusura quando digiti quelle di apertura",
|
||||||
sqlCompletionSection: "Completamento SQL",
|
sqlCompletionSection: "Completamento SQL",
|
||||||
selectFirstCompletionOnOpen: "Seleziona automaticamente il primo suggerimento",
|
selectFirstCompletionOnOpen: "Seleziona automaticamente il primo suggerimento",
|
||||||
|
|||||||
@@ -1676,6 +1676,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "値が多すぎます。最大 {limit} 件まで対応しています。",
|
exPasteTooManyValues: "値が多すぎます。最大 {limit} 件まで対応しています。",
|
||||||
exPasteClipboardReadFailed: "クリップボードの読み取りに失敗しました: {message}",
|
exPasteClipboardReadFailed: "クリップボードの読み取りに失敗しました: {message}",
|
||||||
exPastePasted: "{count} 件のIN条件値を貼り付けました",
|
exPastePasted: "{count} 件のIN条件値を貼り付けました",
|
||||||
|
sqlSourcePasteRestored: "ソースコードの SQL を復元しました(元に戻すと原文に戻ります)",
|
||||||
|
sqlSourcePasteNotDetected: "連結された SQL を認識できなかったため、原文のまま貼り付けました",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "NULL値",
|
nullValue: "NULL値",
|
||||||
isNull: "NULLかどうか",
|
isNull: "NULLかどうか",
|
||||||
@@ -1792,6 +1794,7 @@ export default withEnglishFallback({
|
|||||||
deleteEmptyLines: "空行を削除",
|
deleteEmptyLines: "空行を削除",
|
||||||
cutSelection: "選択内容を切り取る",
|
cutSelection: "選択内容を切り取る",
|
||||||
pasteFromClipboard: "貼り付け",
|
pasteFromClipboard: "貼り付け",
|
||||||
|
pasteRestoringSourceSql: "貼り付けてソース SQL を復元",
|
||||||
pasteClipboardReadFailed: "クリップボードの読み取りに失敗しました:{message}",
|
pasteClipboardReadFailed: "クリップボードの読み取りに失敗しました:{message}",
|
||||||
convertNamingStyle: "命名スタイルの切り替え",
|
convertNamingStyle: "命名スタイルの切り替え",
|
||||||
},
|
},
|
||||||
@@ -7716,6 +7719,8 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Vimモード",
|
vimMode: "Vimモード",
|
||||||
vimModeDescription: "SQLエディタでVim形式のモーダル編集を使用します",
|
vimModeDescription: "SQLエディタでVim形式のモーダル編集を使用します",
|
||||||
autoCloseBrackets: "自動括弧補完",
|
autoCloseBrackets: "自動括弧補完",
|
||||||
|
restoreSqlFromSourcePaste: "貼り付け時にソースコードの SQL を復元",
|
||||||
|
restoreSqlFromSourcePasteDescription: "Java、JavaScript、Python などのソースからコピーした文字列連結の SQL(引用符・プラス記号・エスケープ改行を含む)を、貼り付け時に通常の SQL へ復元します。明確な連結のみを対象とし、それ以外はそのまま貼り付けます。",
|
||||||
autoCloseBracketsDescription: "左括弧や左引用符を入力すると、対応する右括弧や右引用符を自動的に挿入します",
|
autoCloseBracketsDescription: "左括弧や左引用符を入力すると、対応する右括弧や右引用符を自動的に挿入します",
|
||||||
sqlSemanticDiagnosticsEnabled: "SQLセマンティック診断",
|
sqlSemanticDiagnosticsEnabled: "SQLセマンティック診断",
|
||||||
sqlSemanticDiagnosticsEnabledDescription: "有効時、エディタは不明なテーブルや列などの意味的な問題を表示します。大きなSQLの解析とメタデータ確認の負荷を減らすには無効にします。",
|
sqlSemanticDiagnosticsEnabledDescription: "有効時、エディタは不明なテーブルや列などの意味的な問題を表示します。大きなSQLの解析とメタデータ確認の負荷を減らすには無効にします。",
|
||||||
|
|||||||
@@ -1576,6 +1576,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "값이 너무 많습니다. 지원되는 최대 개수는 {limit}개입니다.",
|
exPasteTooManyValues: "값이 너무 많습니다. 지원되는 최대 개수는 {limit}개입니다.",
|
||||||
exPasteClipboardReadFailed: "클립보드 읽기에 실패했습니다: {message}",
|
exPasteClipboardReadFailed: "클립보드 읽기에 실패했습니다: {message}",
|
||||||
exPastePasted: "IN 조건 값 {count}개를 붙여넣었습니다",
|
exPastePasted: "IN 조건 값 {count}개를 붙여넣었습니다",
|
||||||
|
sqlSourcePasteRestored: "소스 코드 SQL을 복원했습니다(실행 취소하면 원문으로 돌아갑니다)",
|
||||||
|
sqlSourcePasteNotDetected: "연결된 SQL을 인식하지 못해 원문 그대로 붙여넣었습니다",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "NULL 값",
|
nullValue: "NULL 값",
|
||||||
isNull: "NULL인지 확인",
|
isNull: "NULL인지 확인",
|
||||||
@@ -1681,6 +1683,7 @@ export default withEnglishFallback({
|
|||||||
compressSelectionSql: "선택한 SQL 압축",
|
compressSelectionSql: "선택한 SQL 압축",
|
||||||
cutSelection: "선택 영역 잘라내기",
|
cutSelection: "선택 영역 잘라내기",
|
||||||
pasteFromClipboard: "붙여넣기",
|
pasteFromClipboard: "붙여넣기",
|
||||||
|
pasteRestoringSourceSql: "붙여넣고 소스 SQL 복원",
|
||||||
pasteClipboardReadFailed: "클립보드 읽기 실패: {message}",
|
pasteClipboardReadFailed: "클립보드 읽기 실패: {message}",
|
||||||
sendToAi: "AI로 보내기",
|
sendToAi: "AI로 보내기",
|
||||||
uppercaseSelection: "대문자로 변환",
|
uppercaseSelection: "대문자로 변환",
|
||||||
@@ -7490,6 +7493,8 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Vim 모드",
|
vimMode: "Vim 모드",
|
||||||
vimModeDescription: "SQL 편집기에서 Vim 스타일의 모달 편집을 사용합니다",
|
vimModeDescription: "SQL 편집기에서 Vim 스타일의 모달 편집을 사용합니다",
|
||||||
autoCloseBrackets: "괄호 자동 닫기",
|
autoCloseBrackets: "괄호 자동 닫기",
|
||||||
|
restoreSqlFromSourcePaste: "붙여넣기 시 소스 코드 SQL 복원",
|
||||||
|
restoreSqlFromSourcePasteDescription: "Java, JavaScript, Python 등 소스에서 복사한 문자열 연결 SQL(따옴표, 더하기 기호, 이스케이프 줄바꿈 포함)을 붙여넣을 때 일반 SQL로 복원합니다. 명확한 연결만 변환하며 그 외에는 원문 그대로 붙여넣습니다.",
|
||||||
autoCloseBracketsDescription: "여는 괄호나 따옴표를 입력할 때 닫는 괄호와 따옴표를 자동으로 삽입합니다",
|
autoCloseBracketsDescription: "여는 괄호나 따옴표를 입력할 때 닫는 괄호와 따옴표를 자동으로 삽입합니다",
|
||||||
sqlCompletionSection: "SQL 자동 완성",
|
sqlCompletionSection: "SQL 자동 완성",
|
||||||
insertSpaceAfterCompletion: "완성 후 공백 삽입",
|
insertSpaceAfterCompletion: "완성 후 공백 삽입",
|
||||||
|
|||||||
@@ -1657,6 +1657,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "Valores demais. Máximo de {limit}.",
|
exPasteTooManyValues: "Valores demais. Máximo de {limit}.",
|
||||||
exPasteClipboardReadFailed: "Falha ao ler a área de transferência: {message}",
|
exPasteClipboardReadFailed: "Falha ao ler a área de transferência: {message}",
|
||||||
exPastePasted: "{count} valores de condição IN colados",
|
exPastePasted: "{count} valores de condição IN colados",
|
||||||
|
sqlSourcePasteRestored: "SQL restaurado a partir do código-fonte (desfaça para recuperar o texto original)",
|
||||||
|
sqlSourcePasteNotDetected: "Nenhum SQL concatenado detectado; o texto original foi colado",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "Valor NULL",
|
nullValue: "Valor NULL",
|
||||||
isNull: "Verificar se é NULL",
|
isNull: "Verificar se é NULL",
|
||||||
@@ -1773,6 +1775,7 @@ export default withEnglishFallback({
|
|||||||
deleteEmptyLines: "Excluir linhas vazias",
|
deleteEmptyLines: "Excluir linhas vazias",
|
||||||
cutSelection: "Recortar seleção",
|
cutSelection: "Recortar seleção",
|
||||||
pasteFromClipboard: "Colar",
|
pasteFromClipboard: "Colar",
|
||||||
|
pasteRestoringSourceSql: "Colar e restaurar SQL de origem",
|
||||||
pasteClipboardReadFailed: "Falha ao ler a área de transferência: {message}",
|
pasteClipboardReadFailed: "Falha ao ler a área de transferência: {message}",
|
||||||
convertNamingStyle: "Alternar estilo de nomenclatura",
|
convertNamingStyle: "Alternar estilo de nomenclatura",
|
||||||
},
|
},
|
||||||
@@ -7701,6 +7704,8 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Modo Vim",
|
vimMode: "Modo Vim",
|
||||||
vimModeDescription: "Usar edição modal no estilo Vim no editor SQL",
|
vimModeDescription: "Usar edição modal no estilo Vim no editor SQL",
|
||||||
autoCloseBrackets: "Fechar parênteses automaticamente",
|
autoCloseBrackets: "Fechar parênteses automaticamente",
|
||||||
|
restoreSqlFromSourcePaste: "Restaurar SQL colado do código-fonte",
|
||||||
|
restoreSqlFromSourcePasteDescription: "Ao colar SQL montado com literais de string em Java, JavaScript, Python e afins (aspas, sinais de mais e quebras de linha escapadas), ele é restaurado como SQL normal. Apenas concatenações claras são reescritas; o restante é colado como está.",
|
||||||
autoCloseBracketsDescription: "Inserir automaticamente parênteses e aspas de fechamento ao digitar os de abertura",
|
autoCloseBracketsDescription: "Inserir automaticamente parênteses e aspas de fechamento ao digitar os de abertura",
|
||||||
sqlCompletionSection: "Preenchimento de SQL",
|
sqlCompletionSection: "Preenchimento de SQL",
|
||||||
selectFirstCompletionOnOpen: "Selecionar automaticamente a primeira sugestão",
|
selectFirstCompletionOnOpen: "Selecionar automaticamente a primeira sugestão",
|
||||||
|
|||||||
@@ -1640,6 +1640,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "Слишком много значений. Максимальное поддерживаемое количество — {limit}.",
|
exPasteTooManyValues: "Слишком много значений. Максимальное поддерживаемое количество — {limit}.",
|
||||||
exPasteClipboardReadFailed: "Не удалось прочитать буфер обмена: {message}",
|
exPasteClipboardReadFailed: "Не удалось прочитать буфер обмена: {message}",
|
||||||
exPastePasted: "Вставлено значений условия IN: {count}",
|
exPastePasted: "Вставлено значений условия IN: {count}",
|
||||||
|
sqlSourcePasteRestored: "SQL восстановлен из исходного кода (отмените, чтобы вернуть исходный текст)",
|
||||||
|
sqlSourcePasteNotDetected: "Конкатенация SQL не распознана; вставлен исходный текст",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "Значение NULL",
|
nullValue: "Значение NULL",
|
||||||
isNull: "Проверить на NULL",
|
isNull: "Проверить на NULL",
|
||||||
@@ -1749,6 +1751,7 @@ export default withEnglishFallback({
|
|||||||
compressSelectionSql: "Сжать выделенный SQL",
|
compressSelectionSql: "Сжать выделенный SQL",
|
||||||
cutSelection: "Вырезать выделенное",
|
cutSelection: "Вырезать выделенное",
|
||||||
pasteFromClipboard: "Вставить",
|
pasteFromClipboard: "Вставить",
|
||||||
|
pasteRestoringSourceSql: "Вставить и восстановить SQL из кода",
|
||||||
pasteClipboardReadFailed: "Не удалось прочитать буфер обмена: {message}",
|
pasteClipboardReadFailed: "Не удалось прочитать буфер обмена: {message}",
|
||||||
sendToAi: "Отправить в AI",
|
sendToAi: "Отправить в AI",
|
||||||
uppercaseSelection: "Преобразовать в верхний регистр",
|
uppercaseSelection: "Преобразовать в верхний регистр",
|
||||||
@@ -8952,6 +8955,9 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Режим Vim",
|
vimMode: "Режим Vim",
|
||||||
vimModeDescription: "Использовать модальное редактирование в стиле Vim в SQL-редакторе",
|
vimModeDescription: "Использовать модальное редактирование в стиле Vim в SQL-редакторе",
|
||||||
autoCloseBrackets: "Автозакрытие скобок",
|
autoCloseBrackets: "Автозакрытие скобок",
|
||||||
|
restoreSqlFromSourcePaste: "Восстанавливать SQL, вставленный из кода",
|
||||||
|
restoreSqlFromSourcePasteDescription:
|
||||||
|
"При вставке SQL, собранного из строковых литералов в Java, JavaScript, Python и подобных исходниках (кавычки, знаки плюс, экранированные переводы строк), он восстанавливается в обычный SQL. Переписываются только явные конкатенации, остальное вставляется как есть.",
|
||||||
autoCloseBracketsDescription: "Автоматически вставлять закрывающие скобки и кавычки при вводе открывающих",
|
autoCloseBracketsDescription: "Автоматически вставлять закрывающие скобки и кавычки при вводе открывающих",
|
||||||
doubleClickStringSelectionMode: "Двойной щелчок внутри строки",
|
doubleClickStringSelectionMode: "Двойной щелчок внутри строки",
|
||||||
doubleClickStringSelectionModeDescription: "Выберите, что выделять двойным щелчком внутри строкового литерала: всё значение целиком или только слово под курсором",
|
doubleClickStringSelectionModeDescription: "Выберите, что выделять двойным щелчком внутри строкового литерала: всё значение целиком или только слово под курсором",
|
||||||
|
|||||||
@@ -1453,6 +1453,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "Çok fazla değer. Desteklenen en fazla sayı {limit}.",
|
exPasteTooManyValues: "Çok fazla değer. Desteklenen en fazla sayı {limit}.",
|
||||||
exPasteClipboardReadFailed: "Pano okunamadı: {message}",
|
exPasteClipboardReadFailed: "Pano okunamadı: {message}",
|
||||||
exPastePasted: "{count} IN koşulu değeri yapıştırıldı",
|
exPastePasted: "{count} IN koşulu değeri yapıştırıldı",
|
||||||
|
sqlSourcePasteRestored: "SQL kaynak koddan geri yüklendi (özgün metin için geri alın)",
|
||||||
|
sqlSourcePasteNotDetected: "Birleştirilmiş SQL algılanamadı; özgün metin yapıştırıldı",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "NULL değer",
|
nullValue: "NULL değer",
|
||||||
isNull: "NULL mu diye denetle",
|
isNull: "NULL mu diye denetle",
|
||||||
@@ -1562,6 +1564,7 @@ export default withEnglishFallback({
|
|||||||
compressSelectionSql: "Seçili SQL'i sıkıştır",
|
compressSelectionSql: "Seçili SQL'i sıkıştır",
|
||||||
cutSelection: "Seçimi kes",
|
cutSelection: "Seçimi kes",
|
||||||
pasteFromClipboard: "Yapıştır",
|
pasteFromClipboard: "Yapıştır",
|
||||||
|
pasteRestoringSourceSql: "Yapıştır ve kaynak SQL'i geri yükle",
|
||||||
pasteClipboardReadFailed: "Pano okunamadı: {message}",
|
pasteClipboardReadFailed: "Pano okunamadı: {message}",
|
||||||
sendToAi: "Yapay Zekâya Gönder",
|
sendToAi: "Yapay Zekâya Gönder",
|
||||||
uppercaseSelection: "Büyük harfe dönüştür",
|
uppercaseSelection: "Büyük harfe dönüştür",
|
||||||
@@ -7621,6 +7624,9 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Vim modu",
|
vimMode: "Vim modu",
|
||||||
vimModeDescription: "SQL düzenleyicisinde Vim biçemli kipli düzenleme kullan",
|
vimModeDescription: "SQL düzenleyicisinde Vim biçemli kipli düzenleme kullan",
|
||||||
autoCloseBrackets: "Parantezleri otomatik kapat",
|
autoCloseBrackets: "Parantezleri otomatik kapat",
|
||||||
|
restoreSqlFromSourcePaste: "Kaynak koddan yapıştırılan SQL'i geri yükle",
|
||||||
|
restoreSqlFromSourcePasteDescription:
|
||||||
|
"Java, JavaScript, Python ve benzeri kaynaklardan kopyalanan dizge birleştirmeli SQL (tırnaklar, artı işaretleri ve kaçış satır sonları) yapıştırılırken normal SQL'e geri yüklenir. Yalnızca net birleştirmeler dönüştürülür, diğer içerik olduğu gibi yapıştırılır.",
|
||||||
autoCloseBracketsDescription: "Açılış karakteri yazıldığında kapanış parantezlerini ve tırnaklarını otomatik ekle",
|
autoCloseBracketsDescription: "Açılış karakteri yazıldığında kapanış parantezlerini ve tırnaklarını otomatik ekle",
|
||||||
sqlCompletionSection: "SQL tamamlama",
|
sqlCompletionSection: "SQL tamamlama",
|
||||||
insertSpaceAfterCompletion: "Tamamlamadan sonra boşluk ekle",
|
insertSpaceAfterCompletion: "Tamamlamadan sonra boşluk ekle",
|
||||||
|
|||||||
@@ -1672,6 +1672,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "值过多,最多支持 {limit} 个",
|
exPasteTooManyValues: "值过多,最多支持 {limit} 个",
|
||||||
exPasteClipboardReadFailed: "读取剪贴板失败:{message}",
|
exPasteClipboardReadFailed: "读取剪贴板失败:{message}",
|
||||||
exPastePasted: "已粘贴 {count} 个 IN 条件值",
|
exPastePasted: "已粘贴 {count} 个 IN 条件值",
|
||||||
|
sqlSourcePasteRestored: "已自动还原源码 SQL(可用撤销恢复原文)",
|
||||||
|
sqlSourcePasteNotDetected: "未识别为拼接 SQL,已按原文粘贴",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "空值",
|
nullValue: "空值",
|
||||||
isNull: "判断是否为 NULL",
|
isNull: "判断是否为 NULL",
|
||||||
@@ -1781,6 +1783,7 @@ export default withEnglishFallback({
|
|||||||
compressSelectionSql: "压缩选中SQL",
|
compressSelectionSql: "压缩选中SQL",
|
||||||
cutSelection: "剪切选中内容",
|
cutSelection: "剪切选中内容",
|
||||||
pasteFromClipboard: "粘贴",
|
pasteFromClipboard: "粘贴",
|
||||||
|
pasteRestoringSourceSql: "粘贴并还原源码 SQL",
|
||||||
pasteClipboardReadFailed: "读取剪贴板失败:{message}",
|
pasteClipboardReadFailed: "读取剪贴板失败:{message}",
|
||||||
sendToAi: "发送到 AI",
|
sendToAi: "发送到 AI",
|
||||||
uppercaseSelection: "转为大写",
|
uppercaseSelection: "转为大写",
|
||||||
@@ -8520,6 +8523,8 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Vim 模式",
|
vimMode: "Vim 模式",
|
||||||
vimModeDescription: "在 SQL 编辑器中使用 Vim 风格的模态编辑",
|
vimModeDescription: "在 SQL 编辑器中使用 Vim 风格的模态编辑",
|
||||||
autoCloseBrackets: "自动成对补全",
|
autoCloseBrackets: "自动成对补全",
|
||||||
|
restoreSqlFromSourcePaste: "粘贴时自动还原源码 SQL",
|
||||||
|
restoreSqlFromSourcePasteDescription: "粘贴从 Java、JavaScript、Python 等源码复制的字符串拼接 SQL(含引号、加号与转义换行)时,自动还原为普通 SQL;只识别明确的拼接写法,其余内容原样粘贴。",
|
||||||
autoCloseBracketsDescription: "输入左括号或左引号时自动补全对应的右括号或右引号",
|
autoCloseBracketsDescription: "输入左括号或左引号时自动补全对应的右括号或右引号",
|
||||||
sqlCompletionSection: "SQL 补全",
|
sqlCompletionSection: "SQL 补全",
|
||||||
insertSpaceAfterCompletion: "补全后自动添加空格",
|
insertSpaceAfterCompletion: "补全后自动添加空格",
|
||||||
|
|||||||
@@ -1658,6 +1658,8 @@ export default withEnglishFallback({
|
|||||||
exPasteTooManyValues: "值過多,最多支援 {limit} 個",
|
exPasteTooManyValues: "值過多,最多支援 {limit} 個",
|
||||||
exPasteClipboardReadFailed: "讀取剪貼簿失敗:{message}",
|
exPasteClipboardReadFailed: "讀取剪貼簿失敗:{message}",
|
||||||
exPastePasted: "已貼上 {count} 個 IN 條件值",
|
exPastePasted: "已貼上 {count} 個 IN 條件值",
|
||||||
|
sqlSourcePasteRestored: "已自動還原來源 SQL(可用復原回復原文)",
|
||||||
|
sqlSourcePasteNotDetected: "未辨識為拼接 SQL,已按原文貼上",
|
||||||
completion: {
|
completion: {
|
||||||
nullValue: "空值",
|
nullValue: "空值",
|
||||||
isNull: "判斷是否為 NULL",
|
isNull: "判斷是否為 NULL",
|
||||||
@@ -1774,6 +1776,7 @@ export default withEnglishFallback({
|
|||||||
deleteEmptyLines: "刪除空行",
|
deleteEmptyLines: "刪除空行",
|
||||||
cutSelection: "剪下選取內容",
|
cutSelection: "剪下選取內容",
|
||||||
pasteFromClipboard: "貼上",
|
pasteFromClipboard: "貼上",
|
||||||
|
pasteRestoringSourceSql: "貼上並還原來源 SQL",
|
||||||
pasteClipboardReadFailed: "讀取剪貼簿失敗:{message}",
|
pasteClipboardReadFailed: "讀取剪貼簿失敗:{message}",
|
||||||
convertNamingStyle: "切換命名風格",
|
convertNamingStyle: "切換命名風格",
|
||||||
},
|
},
|
||||||
@@ -7016,6 +7019,8 @@ export default withEnglishFallback({
|
|||||||
vimMode: "Vim 模式",
|
vimMode: "Vim 模式",
|
||||||
vimModeDescription: "在 SQL 編輯器中使用 Vim 風格的模態編輯",
|
vimModeDescription: "在 SQL 編輯器中使用 Vim 風格的模態編輯",
|
||||||
autoCloseBrackets: "自動成對補全",
|
autoCloseBrackets: "自動成對補全",
|
||||||
|
restoreSqlFromSourcePaste: "貼上時自動還原來源 SQL",
|
||||||
|
restoreSqlFromSourcePasteDescription: "貼上從 Java、JavaScript、Python 等原始碼複製的字串拼接 SQL(含引號、加號與轉義換行)時,自動還原為一般 SQL;只辨識明確的拼接寫法,其餘內容原樣貼上。",
|
||||||
autoCloseBracketsDescription: "輸入左括號或左引號時自動補全對應的右括號或右引號",
|
autoCloseBracketsDescription: "輸入左括號或左引號時自動補全對應的右括號或右引號",
|
||||||
sqlCompletionSection: "SQL 補全",
|
sqlCompletionSection: "SQL 補全",
|
||||||
selectFirstCompletionOnOpen: "自動選取第一個補全候選",
|
selectFirstCompletionOnOpen: "自動選取第一個補全候選",
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { restoreSqlFromSourcePaste, SQL_SOURCE_PASTE_MAX_LENGTH } from "@/lib/sql/sqlSourcePaste";
|
||||||
|
|
||||||
|
describe("restoreSqlFromSourcePaste", () => {
|
||||||
|
it("restores the Java string concatenation from the issue example", () => {
|
||||||
|
const source = ['"SELECT * " +', '"FROM users \\n " +', '"WHERE id = 1"'].join("\n");
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({
|
||||||
|
sql: "SELECT * FROM users \n WHERE id = 1",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops the optional assignment prefix and trailing statement terminator", () => {
|
||||||
|
const source = ['String sql = "SELECT id, name " +', ' "FROM users " +', ' "WHERE id = ?";'].join("\n");
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({
|
||||||
|
sql: "SELECT id, name FROM users WHERE id = ?",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves bare single-literal assignments that only contain a keyword untouched", () => {
|
||||||
|
expect(restoreSqlFromSourcePaste("status = 'DELETE'")).toEqual({ sql: "status = 'DELETE'", changed: false });
|
||||||
|
expect(restoreSqlFromSourcePaste("users.name = 'DESC'")).toEqual({ sql: "users.name = 'DESC'", changed: false });
|
||||||
|
expect(restoreSqlFromSourcePaste("label = 'select'")).toEqual({ sql: "label = 'select'", changed: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("restores bare assignments only when multiple literals are concatenated", () => {
|
||||||
|
const source = 'sql = "SELECT * " +\n "FROM users"';
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({
|
||||||
|
sql: "SELECT * FROM users",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("restores Go short-declaration assignments with a single literal", () => {
|
||||||
|
expect(restoreSqlFromSourcePaste('query := "SELECT 1"')).toEqual({
|
||||||
|
sql: "SELECT 1",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps unknown escape sequences intact for LIKE patterns", () => {
|
||||||
|
const source = "\"SELECT * FROM t WHERE name LIKE '100\\%'\"";
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({
|
||||||
|
sql: "SELECT * FROM t WHERE name LIKE '100\\%'",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("joins implicitly concatenated Python literals", () => {
|
||||||
|
const source = ['sql = ("SELECT * "', ' "FROM users "', ' "WHERE id = 1")'].join("\n");
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({
|
||||||
|
sql: "SELECT * FROM users WHERE id = 1",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("joins PHP dotted concatenation", () => {
|
||||||
|
expect(restoreSqlFromSourcePaste('"SELECT * " . "FROM users"')).toEqual({
|
||||||
|
sql: "SELECT * FROM users",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("unquotes a single literal that covers the whole clipboard", () => {
|
||||||
|
expect(restoreSqlFromSourcePaste('"SELECT id FROM users"')).toEqual({
|
||||||
|
sql: "SELECT id FROM users",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("restores escaped quotes and tabs", () => {
|
||||||
|
const source = '"SELECT * FROM users " +\n\'WHERE name = \\"Bob\\"\' + "\\tAND id = 1"';
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({
|
||||||
|
sql: 'SELECT * FROM users WHERE name = "Bob"\tAND id = 1',
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps JS template literal interpolations verbatim", () => {
|
||||||
|
const source = ["`SELECT * FROM ${table}` +", "` WHERE id = ${id}`"].join("\n");
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({
|
||||||
|
sql: "SELECT * FROM ${table} WHERE id = ${id}",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("restores Java text blocks", () => {
|
||||||
|
const source = 'String sql = """\n SELECT *\n FROM users\n WHERE id = 1\n """;';
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({
|
||||||
|
sql: "SELECT *\n FROM users\n WHERE id = 1",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps backslashes inside Python raw strings", () => {
|
||||||
|
expect(restoreSqlFromSourcePaste('r"SELECT * FROM users WHERE path = C:\\tmp"')).toEqual({
|
||||||
|
sql: "SELECT * FROM users WHERE path = C:\\tmp",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("unescapes doubled quotes in C# verbatim strings", () => {
|
||||||
|
expect(restoreSqlFromSourcePaste('@"SELECT * FROM users WHERE name = ""Bob"""')).toEqual({
|
||||||
|
sql: 'SELECT * FROM users WHERE name = "Bob"',
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps leading SQL comments in the restored statement", () => {
|
||||||
|
expect(restoreSqlFromSourcePaste('"/* hint */ " + "SELECT 1"')).toEqual({
|
||||||
|
sql: "/* hint */ SELECT 1",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves plain SQL untouched", () => {
|
||||||
|
const source = "SELECT * FROM users WHERE name = 'Bob'";
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({ sql: source, changed: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves source strings that are not SQL untouched", () => {
|
||||||
|
const source = '"hello " +\n"world"';
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({ sql: source, changed: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves SQL string concatenation with || untouched", () => {
|
||||||
|
const source = "'SELECT * ' || 'FROM users'";
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({ sql: source, changed: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves concatenations with non-literal operands untouched", () => {
|
||||||
|
const source = 'query = "SELECT * FROM users WHERE id = " + userId';
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({ sql: source, changed: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves multiple statements on separate lines untouched", () => {
|
||||||
|
const source = '"SELECT 1";\n"SELECT 2";';
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({ sql: source, changed: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves unterminated literals untouched", () => {
|
||||||
|
const source = '"SELECT * FROM users';
|
||||||
|
expect(restoreSqlFromSourcePaste(source)).toEqual({ sql: source, changed: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores empty and whitespace-only input", () => {
|
||||||
|
expect(restoreSqlFromSourcePaste("")).toEqual({ sql: "", changed: false });
|
||||||
|
expect(restoreSqlFromSourcePaste(" \n ")).toEqual({ sql: " \n ", changed: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores input longer than the configured limit", () => {
|
||||||
|
const source = `"SELECT * FROM users"`;
|
||||||
|
expect(restoreSqlFromSourcePaste(source, 4)).toEqual({ sql: source, changed: false });
|
||||||
|
expect(SQL_SOURCE_PASTE_MAX_LENGTH).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips empty literals when joining", () => {
|
||||||
|
expect(restoreSqlFromSourcePaste('"SELECT * " + "" + "FROM users"')).toEqual({
|
||||||
|
sql: "SELECT * FROM users",
|
||||||
|
changed: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -38,6 +38,7 @@ export const EDITOR_SETTINGS_DRAFT_KEYS = [
|
|||||||
"vimModeEnabled",
|
"vimModeEnabled",
|
||||||
"doubleClickStringSelectionMode",
|
"doubleClickStringSelectionMode",
|
||||||
"autoCloseBrackets",
|
"autoCloseBrackets",
|
||||||
|
"restoreSqlFromSourcePasteEnabled",
|
||||||
"sqlSemanticDiagnosticsMode",
|
"sqlSemanticDiagnosticsMode",
|
||||||
"confirmDangerousSqlExecution",
|
"confirmDangerousSqlExecution",
|
||||||
"confirmUnsavedSqlClose",
|
"confirmUnsavedSqlClose",
|
||||||
|
|||||||
@@ -142,6 +142,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
|
|||||||
{ id: "editor-word-wrap", category: "editor", titleKey: "settings.wordWrap", descriptionKey: "settings.wordWrapDescription", targetId: "editor" },
|
{ id: "editor-word-wrap", category: "editor", titleKey: "settings.wordWrap", descriptionKey: "settings.wordWrapDescription", targetId: "editor" },
|
||||||
{ id: "editor-vim", category: "editor", titleKey: "settings.vimMode", descriptionKey: "settings.vimModeDescription", targetId: "editor" },
|
{ id: "editor-vim", category: "editor", titleKey: "settings.vimMode", descriptionKey: "settings.vimModeDescription", targetId: "editor" },
|
||||||
{ id: "editor-brackets", category: "editor", titleKey: "settings.autoCloseBrackets", descriptionKey: "settings.autoCloseBracketsDescription", targetId: "editor" },
|
{ id: "editor-brackets", category: "editor", titleKey: "settings.autoCloseBrackets", descriptionKey: "settings.autoCloseBracketsDescription", targetId: "editor" },
|
||||||
|
{ id: "editor-source-paste-restore", category: "editor", titleKey: "settings.restoreSqlFromSourcePaste", descriptionKey: "settings.restoreSqlFromSourcePasteDescription", targetId: "editor" },
|
||||||
{ id: "editor-double-click-string", category: "editor", titleKey: "settings.doubleClickStringSelectionMode", descriptionKey: "settings.doubleClickStringSelectionModeDescription", targetId: "editor" },
|
{ id: "editor-double-click-string", category: "editor", titleKey: "settings.doubleClickStringSelectionMode", descriptionKey: "settings.doubleClickStringSelectionModeDescription", targetId: "editor" },
|
||||||
{ id: "editor-completion-spacing", category: "editor", titleKey: "settings.insertSpaceAfterCompletion", descriptionKey: "settings.insertSpaceAfterCompletionDescription", targetId: "editor" },
|
{ id: "editor-completion-spacing", category: "editor", titleKey: "settings.insertSpaceAfterCompletion", descriptionKey: "settings.insertSpaceAfterCompletionDescription", targetId: "editor" },
|
||||||
{ id: "editor-sqlserver-space-completion", category: "editor", titleKey: "settings.sqlServerSpaceConfirmsCompletion", descriptionKey: "settings.sqlServerSpaceConfirmsCompletionDescription", targetId: "editor", visible: sqlServerSpaceCompletionVisible },
|
{ id: "editor-sqlserver-space-completion", category: "editor", titleKey: "settings.sqlServerSpaceConfirmsCompletion", descriptionKey: "settings.sqlServerSpaceConfirmsCompletionDescription", targetId: "editor", visible: sqlServerSpaceCompletionVisible },
|
||||||
|
|||||||
@@ -94,6 +94,7 @@ const SETTINGS_TRANSFER_CATEGORY_KEYS: Record<SettingsTransferCategoryId, readon
|
|||||||
"vimModeEnabled",
|
"vimModeEnabled",
|
||||||
"doubleClickStringSelectionMode",
|
"doubleClickStringSelectionMode",
|
||||||
"autoCloseBrackets",
|
"autoCloseBrackets",
|
||||||
|
"restoreSqlFromSourcePasteEnabled",
|
||||||
"sqlSemanticDiagnosticsMode",
|
"sqlSemanticDiagnosticsMode",
|
||||||
"confirmDangerousSqlExecution",
|
"confirmDangerousSqlExecution",
|
||||||
"continueOnErrorOnBatch",
|
"continueOnErrorOnBatch",
|
||||||
|
|||||||
@@ -0,0 +1,348 @@
|
|||||||
|
/**
|
||||||
|
* 从源代码里复制出来的「字符串拼接 SQL」还原工具。
|
||||||
|
*
|
||||||
|
* 使用场景:用户从 Java / JS / TS / Python / Go / C# / Kotlin / PHP 等源码里复制
|
||||||
|
* 形如
|
||||||
|
*
|
||||||
|
* "SELECT * " +
|
||||||
|
* "FROM users \n " +
|
||||||
|
* "WHERE id = 1"
|
||||||
|
*
|
||||||
|
* 的拼接 SQL,粘贴进 SQL 编辑器时希望自动去掉字符串引号、`+` 连接符与 `\n`
|
||||||
|
* 转义,还原成可直接执行的普通 SQL。
|
||||||
|
*
|
||||||
|
* 设计原则(宁可「不转换」,也绝不改坏用户内容):
|
||||||
|
* 1. 只有当整段文本完全由「字符串字面量 + 合法连接符(空白/+/.)」构成时才尝试还原;
|
||||||
|
* 2. 还原结果必须命中 SQL 语句起始关键字,否则视为误判、原样返回;
|
||||||
|
* 3. 任何解析失败、超长输入都原样返回,且函数不抛异常。
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** 超过该长度直接放弃解析,避免对超大文本做逐字符扫描 */
|
||||||
|
export const SQL_SOURCE_PASTE_MAX_LENGTH = 256 * 1024;
|
||||||
|
|
||||||
|
/** 还原结果:changed 为 false 时 sql 与输入完全一致,调用方应保持原样粘贴 */
|
||||||
|
export interface SqlSourcePasteResult {
|
||||||
|
/** 还原后的 SQL;未识别时等于输入原文 */
|
||||||
|
sql: string;
|
||||||
|
/** 是否发生了还原 */
|
||||||
|
changed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 还原结果必须命中 SQL 语句起始关键字,用于排除「误把普通源码字符串当 SQL」的情况。
|
||||||
|
* 允许前置空白、行注释与块注释。
|
||||||
|
*/
|
||||||
|
const SQL_STATEMENT_START_RE =
|
||||||
|
/^(?:\s|--[^\n]*\n|\/\*[\s\S]*?\*\/)*(?:SELECT|WITH|INSERT|UPDATE|DELETE|MERGE|REPLACE|UPSERT|CREATE|ALTER|DROP|TRUNCATE|RENAME|CALL|EXEC|EXECUTE|EXPLAIN|SHOW|DESC|DESCRIBE|SET|USE|GRANT|REVOKE|VACUUM|ANALYZE|PRAGMA|BEGIN|START|COMMIT|ROLLBACK|SAVEPOINT|DECLARE|LOCK|UNLOCK)\b/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 允许出现在第一个字面量之前的「赋值前缀」,例如:
|
||||||
|
* `sql = `、`String sql = `、`final String SQL = `、`query := `、`const q = `。
|
||||||
|
* 末尾允许一个左括号(覆盖 `sql = ("..." "..." )` 这种写法)。
|
||||||
|
* 前缀里不允许出现引号,因此不会吞掉字面量本身。
|
||||||
|
* 捕获组 1 为 `=` 之前的前缀文本、捕获组 2 为赋值操作符,用于区分
|
||||||
|
* 声明性赋值与裸标识符赋值(见 DECLARATION_KEYWORD_RE)。
|
||||||
|
*/
|
||||||
|
const ASSIGNMENT_PREFIX_RE = /^([A-Za-z0-9_$.[\]<>,:\s]*?)(:?=)\s*\(?\s*/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判定赋值前缀是否「声明性」:出现声明关键字(Java/Kotlin/JS/TS/Go 的
|
||||||
|
* 类型或 var/const/let/final/val 等)。`:=`(Go 短声明)也视为声明。
|
||||||
|
* 裸标识符赋值(如 `status = 'DELETE'`)不算声明:单个字面量不足以证明
|
||||||
|
* 这是「从源码复制的 SQL」,只有出现两个字面量以上的拼接时才还原,
|
||||||
|
* 避免把条件片段里的单个 SQL 关键字字符串误改写。
|
||||||
|
*/
|
||||||
|
const DECLARATION_KEYWORD_RE = /(?:^|[^A-Za-z0-9_$])(?:string|const|let|var|final|val|def|dim|static)(?:[^A-Za-z0-9_$]|$)/i;
|
||||||
|
|
||||||
|
/** 结尾允许出现的收尾字符:空白、行继续符、闭合括号与语句结束分号 */
|
||||||
|
const TRAILING_TAIL_RE = /^[\s\\]*\)*[\s\\]*;?[\s\\]*$/;
|
||||||
|
|
||||||
|
/** 可出现在引号前、用于修饰字符串语义的字母(Python 的 r/b/f/u、C# 的 @/$ 等) */
|
||||||
|
const LITERAL_PREFIX_CHARS = new Set(["r", "R", "b", "B", "u", "U", "f", "F", "@", "$"]);
|
||||||
|
|
||||||
|
/** 两个字面量之间允许的连接符:Java/JS/Go/Python 的 `+`,PHP/Ruby 的 `.` */
|
||||||
|
const CONNECTOR_CHARS = new Set(["+", "."]);
|
||||||
|
|
||||||
|
interface StringLiteralToken {
|
||||||
|
/** 已按源码语义还原转义后的内容 */
|
||||||
|
content: string;
|
||||||
|
/** 字面量结束后的位置(即下一个待解析字符的下标) */
|
||||||
|
end: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 跳过空白与行继续符(`\` + 换行),返回新的位置。
|
||||||
|
*/
|
||||||
|
function skipBlank(source: string, from: number): number {
|
||||||
|
let pos = from;
|
||||||
|
while (pos < source.length) {
|
||||||
|
const ch = source[pos];
|
||||||
|
if (/\s/.test(ch)) {
|
||||||
|
pos += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 行继续符:反斜杠后面紧跟换行,视为空白
|
||||||
|
if (ch === "\\" && pos + 1 < source.length && /[\r\n]/.test(source[pos + 1])) {
|
||||||
|
pos += 2;
|
||||||
|
if (source[pos - 1] === "\r" && source[pos] === "\n") pos += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 反解「转义字符串」里的转义序列(Java/JS/Python 等非 raw 字面量通用规则)。
|
||||||
|
* 未知转义保留反斜杠本身(JS/Python 语义),避免改写 LIKE 模式等内容。
|
||||||
|
*/
|
||||||
|
function unescapeLiteralContent(raw: string): string {
|
||||||
|
let out = "";
|
||||||
|
for (let index = 0; index < raw.length; index += 1) {
|
||||||
|
const ch = raw[index];
|
||||||
|
if (ch !== "\\") {
|
||||||
|
out += ch;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const next = raw[index + 1];
|
||||||
|
if (next === undefined) {
|
||||||
|
out += "\\";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
index += 1;
|
||||||
|
switch (next) {
|
||||||
|
case "n":
|
||||||
|
out += "\n";
|
||||||
|
break;
|
||||||
|
case "r":
|
||||||
|
out += "\r";
|
||||||
|
break;
|
||||||
|
case "t":
|
||||||
|
out += "\t";
|
||||||
|
break;
|
||||||
|
case "b":
|
||||||
|
out += "\b";
|
||||||
|
break;
|
||||||
|
case "f":
|
||||||
|
out += "\f";
|
||||||
|
break;
|
||||||
|
case "v":
|
||||||
|
out += "\v";
|
||||||
|
break;
|
||||||
|
case "0":
|
||||||
|
out += "\0";
|
||||||
|
break;
|
||||||
|
case "\n":
|
||||||
|
// 行继续符:反斜杠 + 换行不产生任何输出
|
||||||
|
break;
|
||||||
|
case "u": {
|
||||||
|
const hex = raw.slice(index + 1, index + 5);
|
||||||
|
if (/^[0-9a-fA-F]{4}$/.test(hex)) {
|
||||||
|
out += String.fromCharCode(Number.parseInt(hex, 16));
|
||||||
|
index += 4;
|
||||||
|
} else {
|
||||||
|
out += "u";
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "x": {
|
||||||
|
const hex = raw.slice(index + 1, index + 3);
|
||||||
|
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
||||||
|
out += String.fromCharCode(Number.parseInt(hex, 16));
|
||||||
|
index += 2;
|
||||||
|
} else {
|
||||||
|
out += "x";
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "'":
|
||||||
|
case '"':
|
||||||
|
case "`":
|
||||||
|
case "\\":
|
||||||
|
case "/":
|
||||||
|
// 引号/反斜杠/斜杠的恒等转义:去掉反斜杠本身
|
||||||
|
out += next;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
// 未知转义:JS/Python 语义是保留反斜杠(如 LIKE '100\%'),
|
||||||
|
// Java 里未知转义本就是编译错误,保留反斜杠更贴近用户原文
|
||||||
|
out += "\\" + next;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** C# 逐字字符串(@"...")里用 `""` 表示一个双引号,反斜杠不转义 */
|
||||||
|
function unescapeVerbatimContent(raw: string): string {
|
||||||
|
return raw.replace(/""/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断引号前是否存在语义前缀(如 `r"` / `f"` / `@$"`),返回前缀起始下标。
|
||||||
|
* 只有紧贴引号、且长度不超过 3、且前面不是标识符字符时才算前缀,
|
||||||
|
* 避免把 `name"x"` 这类内容误判。
|
||||||
|
*/
|
||||||
|
function literalPrefixStart(source: string, quotePos: number): number {
|
||||||
|
let start = quotePos;
|
||||||
|
while (start > 0 && quotePos - start < 3 && LITERAL_PREFIX_CHARS.has(source[start - 1])) {
|
||||||
|
const before = start - 2;
|
||||||
|
if (before >= 0 && /[\w$]/.test(source[before])) break;
|
||||||
|
start -= 1;
|
||||||
|
}
|
||||||
|
return start;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断 cursor 处是否是「前缀字母 + 引号」的写法(`r"` / `f"` / `b'` / `@$"` 等),
|
||||||
|
* 是则返回引号所在下标;否则返回 null。
|
||||||
|
*/
|
||||||
|
function quoteAfterLiteralPrefix(source: string, cursor: number): number | null {
|
||||||
|
let pos = cursor;
|
||||||
|
while (pos < source.length && pos - cursor < 3 && LITERAL_PREFIX_CHARS.has(source[pos])) pos += 1;
|
||||||
|
if (pos === cursor || pos >= source.length) return null;
|
||||||
|
return source[pos] === '"' || source[pos] === "'" || source[pos] === "`" ? pos : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 cursor 处读取一个字面量,兼容前面带有修饰字母的写法(`r"..."` / `@"..."`)。
|
||||||
|
*/
|
||||||
|
function readLiteralAtCursor(source: string, cursor: number): StringLiteralToken | null {
|
||||||
|
const directQuote = source[cursor];
|
||||||
|
const quotePos = directQuote === '"' || directQuote === "'" || directQuote === "`" ? cursor : quoteAfterLiteralPrefix(source, cursor);
|
||||||
|
if (quotePos === null) return null;
|
||||||
|
return readStringLiteral(source, quotePos);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 quotePos 处读取一个字符串字面量。支持:
|
||||||
|
* - 单引号 / 双引号 / 反引号(JS 模板字符串,`${}` 原样保留);
|
||||||
|
* - 三引号文本块(Java、Python 的 `"""` / `'''`);
|
||||||
|
* - raw 前缀(Python `r""`)与 C# 逐字字符串(`@"..."`)。
|
||||||
|
* 未闭合或不是字面量时返回 null。
|
||||||
|
*/
|
||||||
|
function readStringLiteral(source: string, quotePos: number): StringLiteralToken | null {
|
||||||
|
const quote = source[quotePos];
|
||||||
|
if (quote !== '"' && quote !== "'" && quote !== "`") return null;
|
||||||
|
|
||||||
|
const prefixStart = literalPrefixStart(source, quotePos);
|
||||||
|
const prefix = source.slice(prefixStart, quotePos);
|
||||||
|
const isRaw = /[rR]/.test(prefix) || prefix.includes("@");
|
||||||
|
const isVerbatim = prefix.includes("@");
|
||||||
|
const isTriple = source.startsWith(quote.repeat(3), quotePos);
|
||||||
|
const openLength = isTriple ? 3 : 1;
|
||||||
|
|
||||||
|
let pos = quotePos + openLength;
|
||||||
|
let rawContent = "";
|
||||||
|
while (pos < source.length) {
|
||||||
|
const ch = source[pos];
|
||||||
|
if (!isRaw && ch === "\\") {
|
||||||
|
// 转义序列整体交给反解函数处理,这里只负责不要把它当成结束引号
|
||||||
|
rawContent += ch;
|
||||||
|
if (pos + 1 < source.length) rawContent += source[pos + 1];
|
||||||
|
pos += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isRaw && ch === "\\" && !isVerbatim) {
|
||||||
|
// Python raw 字符串:反斜杠不转义,但保留「反斜杠 + 引号」以免提前截断
|
||||||
|
rawContent += ch;
|
||||||
|
if (pos + 1 < source.length) rawContent += source[pos + 1];
|
||||||
|
pos += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isVerbatim && ch === quote && source[pos + 1] === quote) {
|
||||||
|
// C# 逐字字符串里 `""` 表示一个双引号,不能当作结束引号
|
||||||
|
rawContent += quote + quote;
|
||||||
|
pos += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (isTriple ? source.startsWith(quote.repeat(3), pos) : ch === quote) {
|
||||||
|
const end = pos + openLength;
|
||||||
|
const content = isVerbatim ? unescapeVerbatimContent(rawContent) : isRaw ? rawContent : unescapeLiteralContent(rawContent);
|
||||||
|
return { content, end };
|
||||||
|
}
|
||||||
|
rawContent += ch;
|
||||||
|
pos += 1;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断两个字面量之间(between 为其原文)是否为合法拼接:
|
||||||
|
* - 隐式拼接(Python/Kotlin):中间只有空白,且确实有空白分隔;
|
||||||
|
* - 显式拼接:中间为空白 + `+` 或 `.` + 空白。
|
||||||
|
* 其他情况(如 `||`、`,`、函数参数)一律判定为「不是源码拼接」,放弃还原。
|
||||||
|
*/
|
||||||
|
function isLiteralSeparator(between: string, sawConnector: boolean): boolean {
|
||||||
|
const compact = between.replace(/\\\s/g, "");
|
||||||
|
if (sawConnector) return /^\s*[+.]\s*$/.test(compact);
|
||||||
|
return compact.length > 0 && /^\s+$/.test(compact);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析整段「源码拼接 SQL」,成功时返回按顺序拼接好的字面量内容列表。
|
||||||
|
* 只要出现无法解释的内容就返回 null(调用方据此保持原文粘贴)。
|
||||||
|
*/
|
||||||
|
function parseSourceSqlLiterals(source: string): string[] | null {
|
||||||
|
let pos = 0;
|
||||||
|
const prefixMatch = source.match(ASSIGNMENT_PREFIX_RE);
|
||||||
|
let bareAssignment = false;
|
||||||
|
if (prefixMatch) {
|
||||||
|
// 裸标识符赋值(无声明关键字且不是 :=):只有多字面量拼接才算源码 SQL
|
||||||
|
bareAssignment = prefixMatch[2] !== ":=" && !DECLARATION_KEYWORD_RE.test(prefixMatch[1]);
|
||||||
|
pos = prefixMatch[0].length;
|
||||||
|
}
|
||||||
|
pos = skipBlank(source, pos);
|
||||||
|
|
||||||
|
const first = readLiteralAtCursor(source, pos);
|
||||||
|
if (!first) return null;
|
||||||
|
const fragments = [first.content];
|
||||||
|
pos = first.end;
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
const gapStart = pos;
|
||||||
|
let cursor = skipBlank(source, pos);
|
||||||
|
let sawConnector = false;
|
||||||
|
if (cursor < source.length && CONNECTOR_CHARS.has(source[cursor])) {
|
||||||
|
sawConnector = true;
|
||||||
|
cursor = skipBlank(source, cursor + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const next = readLiteralAtCursor(source, cursor);
|
||||||
|
if (!next) {
|
||||||
|
// 没有更多字面量:只允许「空白 + 可选右括号/分号」收尾
|
||||||
|
if (!TRAILING_TAIL_RE.test(source.slice(gapStart))) return null;
|
||||||
|
if (bareAssignment && fragments.length < 2) return null;
|
||||||
|
return fragments;
|
||||||
|
}
|
||||||
|
if (!isLiteralSeparator(source.slice(gapStart, cursor), sawConnector)) return null;
|
||||||
|
fragments.push(next.content);
|
||||||
|
pos = next.end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把从源码复制的拼接 SQL 还原为普通 SQL。
|
||||||
|
*
|
||||||
|
* @param source 剪贴板里的原文
|
||||||
|
* @param maxLength 解析长度上限,超过则原样返回
|
||||||
|
* @returns 还原结果;changed 为 false 表示未识别,调用方应原样粘贴
|
||||||
|
*/
|
||||||
|
export function restoreSqlFromSourcePaste(source: string, maxLength: number = SQL_SOURCE_PASTE_MAX_LENGTH): SqlSourcePasteResult {
|
||||||
|
const unchanged: SqlSourcePasteResult = { sql: source, changed: false };
|
||||||
|
if (typeof source !== "string" || source.length === 0 || source.length > maxLength) return unchanged;
|
||||||
|
|
||||||
|
const trimmed = source.trim();
|
||||||
|
if (!trimmed) return unchanged;
|
||||||
|
|
||||||
|
const fragments = parseSourceSqlLiterals(trimmed);
|
||||||
|
if (!fragments || fragments.length === 0) return unchanged;
|
||||||
|
|
||||||
|
const joined = fragments.join("").trim();
|
||||||
|
// 拼接结果为空或与原文完全相同(例如本来就不是字面量拼接)时不改写
|
||||||
|
if (!joined || joined === trimmed) return unchanged;
|
||||||
|
// 还原结果必须像一条 SQL 语句,否则视为误判
|
||||||
|
if (!SQL_STATEMENT_START_RE.test(joined)) return unchanged;
|
||||||
|
|
||||||
|
return { sql: joined, changed: true };
|
||||||
|
}
|
||||||
@@ -68,6 +68,14 @@ describe("normalizeEditorSettings", () => {
|
|||||||
expect(normalizeEditorSettings({ sqlVariableSubstitutionEnabled: null } as any).sqlVariableSubstitutionEnabled).toBe(true);
|
expect(normalizeEditorSettings({ sqlVariableSubstitutionEnabled: null } as any).sqlVariableSubstitutionEnabled).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("enables source-code SQL restore on paste by default and only preserves booleans", () => {
|
||||||
|
expect(DEFAULT_EDITOR_SETTINGS.restoreSqlFromSourcePasteEnabled).toBe(true);
|
||||||
|
expect(normalizeEditorSettings({}).restoreSqlFromSourcePasteEnabled).toBe(true);
|
||||||
|
expect(normalizeEditorSettings({ restoreSqlFromSourcePasteEnabled: false }).restoreSqlFromSourcePasteEnabled).toBe(false);
|
||||||
|
expect(normalizeEditorSettings({ restoreSqlFromSourcePasteEnabled: "false" } as any).restoreSqlFromSourcePasteEnabled).toBe(true);
|
||||||
|
expect(normalizeEditorSettings({ restoreSqlFromSourcePasteEnabled: null } as any).restoreSqlFromSourcePasteEnabled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
it("keeps the quick filter view by default and preserves fixed filter views", () => {
|
it("keeps the quick filter view by default and preserves fixed filter views", () => {
|
||||||
expect(normalizeEditorSettings({}).dataGridFilterEditorView).toBe("quick");
|
expect(normalizeEditorSettings({}).dataGridFilterEditorView).toBe("quick");
|
||||||
expect(normalizeEditorSettings({ dataGridFilterEditorView: "conditions" }).dataGridFilterEditorView).toBe("conditions");
|
expect(normalizeEditorSettings({ dataGridFilterEditorView: "conditions" }).dataGridFilterEditorView).toBe("conditions");
|
||||||
|
|||||||
@@ -872,6 +872,8 @@ export interface EditorSettings {
|
|||||||
/** Double click inside a string literal selects the whole value ("content") or a single word ("word"). */
|
/** Double click inside a string literal selects the whole value ("content") or a single word ("word"). */
|
||||||
doubleClickStringSelectionMode: DoubleClickStringSelectionMode;
|
doubleClickStringSelectionMode: DoubleClickStringSelectionMode;
|
||||||
autoCloseBrackets: boolean;
|
autoCloseBrackets: boolean;
|
||||||
|
/** 粘贴从 Java/JS/Python 等源码里复制的字符串拼接 SQL 时,自动还原为普通 SQL。 */
|
||||||
|
restoreSqlFromSourcePasteEnabled: boolean;
|
||||||
sqlSemanticDiagnosticsMode: SqlSemanticDiagnosticsMode;
|
sqlSemanticDiagnosticsMode: SqlSemanticDiagnosticsMode;
|
||||||
sqlSemanticDiagnosticsEnabled: boolean;
|
sqlSemanticDiagnosticsEnabled: boolean;
|
||||||
confirmDangerousSqlExecution: boolean;
|
confirmDangerousSqlExecution: boolean;
|
||||||
@@ -1163,6 +1165,7 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {
|
|||||||
vimModeEnabled: false,
|
vimModeEnabled: false,
|
||||||
doubleClickStringSelectionMode: "content",
|
doubleClickStringSelectionMode: "content",
|
||||||
autoCloseBrackets: true,
|
autoCloseBrackets: true,
|
||||||
|
restoreSqlFromSourcePasteEnabled: true,
|
||||||
sqlSemanticDiagnosticsMode: "auto",
|
sqlSemanticDiagnosticsMode: "auto",
|
||||||
sqlSemanticDiagnosticsEnabled: SQL_SEMANTIC_DIAGNOSTICS_AUTO_ENABLED,
|
sqlSemanticDiagnosticsEnabled: SQL_SEMANTIC_DIAGNOSTICS_AUTO_ENABLED,
|
||||||
confirmDangerousSqlExecution: true,
|
confirmDangerousSqlExecution: true,
|
||||||
@@ -1736,6 +1739,7 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
|
|||||||
vimModeEnabled: typeof settings.vimModeEnabled === "boolean" ? settings.vimModeEnabled : DEFAULT_EDITOR_SETTINGS.vimModeEnabled,
|
vimModeEnabled: typeof settings.vimModeEnabled === "boolean" ? settings.vimModeEnabled : DEFAULT_EDITOR_SETTINGS.vimModeEnabled,
|
||||||
doubleClickStringSelectionMode: normalizeDoubleClickStringSelectionMode(settings.doubleClickStringSelectionMode),
|
doubleClickStringSelectionMode: normalizeDoubleClickStringSelectionMode(settings.doubleClickStringSelectionMode),
|
||||||
autoCloseBrackets: typeof settings.autoCloseBrackets === "boolean" ? settings.autoCloseBrackets : DEFAULT_EDITOR_SETTINGS.autoCloseBrackets,
|
autoCloseBrackets: typeof settings.autoCloseBrackets === "boolean" ? settings.autoCloseBrackets : DEFAULT_EDITOR_SETTINGS.autoCloseBrackets,
|
||||||
|
restoreSqlFromSourcePasteEnabled: typeof settings.restoreSqlFromSourcePasteEnabled === "boolean" ? settings.restoreSqlFromSourcePasteEnabled : DEFAULT_EDITOR_SETTINGS.restoreSqlFromSourcePasteEnabled,
|
||||||
sqlSemanticDiagnosticsMode,
|
sqlSemanticDiagnosticsMode,
|
||||||
sqlSemanticDiagnosticsEnabled: sqlSemanticDiagnosticsEnabledForMode(sqlSemanticDiagnosticsMode),
|
sqlSemanticDiagnosticsEnabled: sqlSemanticDiagnosticsEnabledForMode(sqlSemanticDiagnosticsMode),
|
||||||
confirmDangerousSqlExecution: settings.confirmDangerousSqlExecution ?? DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution,
|
confirmDangerousSqlExecution: settings.confirmDangerousSqlExecution ?? DEFAULT_EDITOR_SETTINGS.confirmDangerousSqlExecution,
|
||||||
@@ -2572,6 +2576,7 @@ export const useSettingsStore = defineStore("settings", () => {
|
|||||||
if (partial.vimModeEnabled !== undefined) editorSettings.value.vimModeEnabled = partial.vimModeEnabled === true;
|
if (partial.vimModeEnabled !== undefined) editorSettings.value.vimModeEnabled = partial.vimModeEnabled === true;
|
||||||
if (partial.doubleClickStringSelectionMode !== undefined) editorSettings.value.doubleClickStringSelectionMode = normalizeDoubleClickStringSelectionMode(partial.doubleClickStringSelectionMode);
|
if (partial.doubleClickStringSelectionMode !== undefined) editorSettings.value.doubleClickStringSelectionMode = normalizeDoubleClickStringSelectionMode(partial.doubleClickStringSelectionMode);
|
||||||
if (partial.autoCloseBrackets !== undefined) editorSettings.value.autoCloseBrackets = partial.autoCloseBrackets === true;
|
if (partial.autoCloseBrackets !== undefined) editorSettings.value.autoCloseBrackets = partial.autoCloseBrackets === true;
|
||||||
|
if (partial.restoreSqlFromSourcePasteEnabled !== undefined) editorSettings.value.restoreSqlFromSourcePasteEnabled = partial.restoreSqlFromSourcePasteEnabled === true;
|
||||||
if (partial.sqlSemanticDiagnosticsMode !== undefined || partial.sqlSemanticDiagnosticsEnabled !== undefined) {
|
if (partial.sqlSemanticDiagnosticsMode !== undefined || partial.sqlSemanticDiagnosticsEnabled !== undefined) {
|
||||||
const nextMode = normalizeSqlSemanticDiagnosticsMode(partial.sqlSemanticDiagnosticsMode, partial.sqlSemanticDiagnosticsEnabled);
|
const nextMode = normalizeSqlSemanticDiagnosticsMode(partial.sqlSemanticDiagnosticsMode, partial.sqlSemanticDiagnosticsEnabled);
|
||||||
editorSettings.value.sqlSemanticDiagnosticsMode = nextMode;
|
editorSettings.value.sqlSemanticDiagnosticsMode = nextMode;
|
||||||
|
|||||||
Reference in new issue
Block a user