feat(editor): preserve caret when formatting SQL

Closes #4632
This commit is contained in:
t8y2 committed 2026-10-03 20:19:02 +00:00
1 parent 01320286e8
commit fbd50acf00
4 files changed
+463 -4

No files matched your search

@@ -75,6 +75,7 @@ import { restoreSqlFromSourcePaste } from "@/lib/sql/sqlSourcePaste";
import { enabledSqlParameterSyntaxes, resolveSqlVariableSyntaxToggles } from "@/lib/sql/sqlVariableSyntax";
import { createQueryEditorExecutionViewportOwnership, isQueryEditorPositionVisible } from "@/lib/editor/queryEditorExecutionViewport";
import { mapQueryEditorFormatSelection } from "@/lib/editor/queryEditorFormatSelection";
import { joinQueryEditorLines } from "@/lib/editor/queryEditorJoinLines";
import { resolveSqlSingleQuoteKeyAction } from "@/lib/sql/sqlQuoteCaret";
@@ -1670,9 +1671,11 @@ async function formatCurrentSql() {
const to = formatsSelection ? selection.to : originalState.doc.length;
const source = originalState.sliceDoc(from, to);
if (!source.trim()) return;
const formatDialect = props.formatDialect ?? props.dialect ?? "generic";
try {
let formatted: string;
let formattedAsSql = false;
if (props.databaseType === "mongodb") {
formatted = formatMongoShellText(source, settingsStore.editorSettings.sqlFormatter);
} else {
@@ -1695,7 +1698,8 @@ async function formatCurrentSql() {
toast(t("toolbar.formatAutoDetectFailed"), 3000);
return;
} else {
formatted = await formatSqlForEditing(source, props.formatDialect ?? props.dialect ?? "generic", settingsStore.editorSettings.sqlFormatter);
formattedAsSql = true;
formatted = await formatSqlForEditing(source, formatDialect, settingsStore.editorSettings.sqlFormatter);
}
}
}
@@ -1703,9 +1707,13 @@ async function formatCurrentSql() {
return;
}
if (formatted === source) return;
// The semantic mapper's contract is SQL-only. Mongo shell, Elasticsearch,
// JSON, and XML keep the replacement selection behavior used before the
// SQL caret-preservation fix.
const replacementSelection = formattedAsSql ? mapQueryEditorFormatSelection(source, formatted, { anchor: selection.anchor - from, head: selection.head - from }, formatDialect) : formatsSelection ? { anchor: 0, head: formatted.length } : { anchor: formatted.length, head: formatted.length };
currentView.dispatch({
changes: { from, to, insert: formatted },
selection: formatsSelection ? { anchor: from, head: from + formatted.length } : { anchor: from + formatted.length },
selection: { anchor: from + replacementSelection.anchor, head: from + replacementSelection.head },
});
} catch (e: any) {
emit("formatError", String(e?.message || e));
@@ -1,6 +1,8 @@
// @vitest-environment happy-dom
import { createApp, defineComponent, h, nextTick, reactive } from "vue";
import { undo } from "@codemirror/commands";
import { EditorView } from "@codemirror/view";
import { createPinia, setActivePinia } from "pinia";
import { createI18n } from "vue-i18n";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -8,6 +10,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import QueryEditor from "@/components/editor/QueryEditor.vue";
import { compressSqlText, formatSqlForEditing } from "@/lib/sql/sqlFormatter";
import { DEFAULT_SQL_FORMATTER_SETTINGS } from "@/lib/sql/sqlFormatterConfig";
import type { DatabaseType } from "@/types/database";
// The request ids are per-kind global counters in App.vue, so ids keep
// increasing for the lifetime of the process. The module-scope replay cursor in
@@ -33,7 +36,7 @@ type EditorState = {
const WAIT = { timeout: 5000, interval: 20 };
function mountEditor(initial: { modelValue: string; tabId: string; formatRequestId?: number; compressRequestId?: number }) {
function mountEditor(initial: { modelValue: string; tabId: string; databaseType?: DatabaseType; formatRequestId?: number; compressRequestId?: number }) {
const pinia = createPinia();
setActivePinia(pinia);
const state = reactive<EditorState>({
@@ -48,7 +51,7 @@ function mountEditor(initial: { modelValue: string; tabId: string; formatRequest
h(QueryEditor, {
modelValue: state.modelValue,
tabId: state.tabId,
databaseType: "mysql",
databaseType: initial.databaseType ?? "mysql",
dialect: "mysql",
formatDialect: "mysql",
autoFocus: false,
@@ -158,4 +161,111 @@ describe("QueryEditor format/compress request replay", () => {
expect(second.emits).toEqual([]);
});
it("keeps the whole-document format caret on its original SQL token", async () => {
const { state, emits, host } = mountEditor({ modelValue: COMPRESSED_SQL, tabId: "tab-a" });
await waitForEditor(host);
const editorView = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
const caret = COMPRESSED_SQL.lastIndexOf("tenant_id") + 4;
editorView.dispatch({ selection: { anchor: caret } });
state.formatRequestId = 4;
await vi.waitFor(() => expect(emits.at(-1)).toBe(FORMATTED_SQL), WAIT);
expect(editorView.state.selection.main.head).toBe(FORMATTED_SQL.lastIndexOf("tenant_id") + 4);
expect(editorView.state.selection.main.head).toBeLessThan(editorView.state.doc.length);
expect(undo(editorView)).toBe(true);
expect(editorView.state.doc.toString()).toBe(COMPRESSED_SQL);
expect(editorView.state.selection.main.head).toBe(caret);
expect(undo(editorView)).toBe(false);
});
it("does not move the caret or dispatch a change when a parse failure returns the source", async () => {
const source = "SELECT 1 .";
const { state, emits, host } = mountEditor({ modelValue: source, tabId: "tab-a" });
await waitForEditor(host);
const editorView = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
const caret = source.indexOf("1");
editorView.dispatch({ selection: { anchor: caret } });
state.formatRequestId = 5;
await settle();
await settle();
expect(emits).toEqual([]);
expect(editorView.state.selection.main.head).toBe(caret);
});
it.each([
["forward", 0, COMPRESSED_SQL.length, 0, FORMATTED_SQL.length, 6],
["reverse", COMPRESSED_SQL.length, 0, FORMATTED_SQL.length, 0, 7],
] as const)("keeps a %s formatted SQL selection complete and in its original direction", async (_direction, anchor, head, expectedAnchor, expectedHead, requestId) => {
const { state, emits, host } = mountEditor({ modelValue: COMPRESSED_SQL, tabId: "tab-a" });
await waitForEditor(host);
const editorView = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
editorView.dispatch({ selection: { anchor, head } });
state.formatRequestId = requestId;
await vi.waitFor(() => expect(emits.at(-1)).toBe(FORMATTED_SQL), WAIT);
expect(editorView.state.selection.main.anchor).toBe(expectedAnchor);
expect(editorView.state.selection.main.head).toBe(expectedHead);
});
it.each([
{
name: "Mongo shell",
databaseType: "mongodb",
source: 'db.items.find({name:"Ada",age:42});',
formatted: 'db.items.find({\n name: "Ada",\n age: 42\n});',
requestId: 8,
},
{
name: "Elasticsearch request",
databaseType: "elasticsearch",
source: 'GET /items/_search {"query":{"match_all":{}}}',
formatted: 'GET /items/_search\n{\n "query": {\n "match_all": {}\n }\n}',
requestId: 9,
},
{
name: "JSON",
databaseType: "mysql",
source: '{"name":"Ada","items":[1,2]}',
formatted: '{\n "name": "Ada",\n "items": [\n 1,\n 2\n ]\n}',
requestId: 10,
},
{
name: "XML",
databaseType: "mysql",
source: '<root><item id="1"/><item id="2"/></root>',
formatted: '<root>\n <item id="1"/>\n <item id="2"/>\n</root>',
requestId: 11,
},
] as const)("keeps the existing whole-document caret behavior for $name formatting", async ({ databaseType, source, formatted, requestId }) => {
const { state, emits, host } = mountEditor({ modelValue: source, tabId: "tab-a", databaseType });
await waitForEditor(host);
const editorView = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
editorView.dispatch({ selection: { anchor: Math.floor(source.length / 2) } });
state.formatRequestId = requestId;
await vi.waitFor(() => expect(emits.at(-1)).toBe(formatted), WAIT);
expect(editorView.state.selection.main.anchor).toBe(formatted.length);
expect(editorView.state.selection.main.head).toBe(formatted.length);
});
it("keeps the existing forward full-range selection for non-SQL formatting", async () => {
const source = '{"name":"Ada","items":[1,2]}';
const formatted = '{\n "name": "Ada",\n "items": [\n 1,\n 2\n ]\n}';
const { state, emits, host } = mountEditor({ modelValue: source, tabId: "tab-a" });
await waitForEditor(host);
const editorView = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
editorView.dispatch({ selection: { anchor: source.length, head: 0 } });
state.formatRequestId = 12;
await vi.waitFor(() => expect(emits.at(-1)).toBe(formatted), WAIT);
expect(editorView.state.selection.main.anchor).toBe(0);
expect(editorView.state.selection.main.head).toBe(formatted.length);
});
});