diff --git a/src/features/database/console.tsx b/src/features/database/console.tsx index 92ad838e0b..0c11216c48 100644 --- a/src/features/database/console.tsx +++ b/src/features/database/console.tsx @@ -57,7 +57,7 @@ import { type SqlCandidate, type SqlCatalog, } from "./sql/complete"; -import { sqlSupport } from "./sqlSupport"; +import { WHOLE_FILE, sqlSupport, type SqlText } from "./sqlSupport"; import { snowflakeLanguage } from "./sql/snowflakeHighlight"; import { bindConsole, @@ -729,7 +729,7 @@ function docNode(text: string): Node { return pre; } -function applyCandidate(c: SqlCandidate, driver: DbDriver) { +function applyCandidate(c: SqlCandidate, driver: DbDriver, sql: SqlText) { return (view: EditorView, completion: Completion, from: number, to: number) => { // A selected template placeholder is replaced, as CodeMirror's own string completions do. const sel = view.state.selection.main; @@ -752,7 +752,7 @@ function applyCandidate(c: SqlCandidate, driver: DbDriver) { } const changes: Array<{ from: number; to?: number; insert: string }> = [{ from, to, insert: text }]; // Re-read the statement as it is now: the user may have typed on since the popup opened. - const a = analyze(view.state.doc.toString(), to, driver); + const a = analyze(sql.text(view.state), to, driver); if (a.fromInsert !== null) { const clause = ` ${a.lowerKeywords ? "from" : "FROM"} ${c.addFrom}`; if (a.fromInsert <= to) changes[0]!.insert += clause; @@ -853,8 +853,10 @@ async function loadQualified(id: string, qualifier: readonly string[]): Promise< if (schema && !useDatabase.getState().tables[tablesKey(target, schema)]) await loadTables(target, schema); } -function completionSource(path: string): CompletionSource { +/** SQL completion in `path`, where `sql` says the SQL is (the whole file, or a mapper's statements). */ +export function completionSource(path: string, sql: SqlText = WHOLE_FILE): CompletionSource { return async (ctx: CompletionContext): Promise => { + if (sql.at && !sql.at(ctx.state, ctx.pos)) return null; const id = consoleSource(path); const current = id ? databaseRequest(id) : projectRequest(); const source = sourceById(id); @@ -867,7 +869,7 @@ function completionSource(path: string): CompletionSource { // A selected template placeholder (`alias`) is about to be replaced: analyze without it. const sel = ctx.state.selection.main; const placeholder = !sel.empty && (ctx.pos === sel.from || ctx.pos === sel.to); - const doc = ctx.state.doc.toString(); + const doc = sql.text(ctx.state); const analysis = placeholder ? analyze(doc.slice(0, sel.from) + doc.slice(sel.to), sel.from, driver) : analyze(doc, ctx.pos, driver); @@ -895,7 +897,7 @@ function completionSource(path: string): CompletionSource { type: c.kind === "keyword" ? "keyword" : c.kind, boost: Math.max(-99, Math.min(99, c.boost)), info: c.doc ? () => docNode(c.doc!) : undefined, - apply: applyCandidate(c, driver), + apply: applyCandidate(c, driver, sql), })), validFor: /^[\p{L}\p{N}_$]*$/u, }; diff --git a/src/features/database/index.ts b/src/features/database/index.ts index 9f6a742b5e..c399cc8c24 100644 --- a/src/features/database/index.ts +++ b/src/features/database/index.ts @@ -124,6 +124,14 @@ export function activate(): () => void { () => import("./console").then((m) => m.consoleExtension), ), }), + registerEditorContribution({ + id: "database.mybatis", + order: 58, + extensions: lazyEditorExtension( + (ctx) => /\.xml$/i.test(ctx.path) && !ctx.virtual, + () => import("./mybatis").then((m) => m.mapperExtension), + ), + }), // A reopened project starts with a fresh backend: forget the old one's state. useProject.subscribe((s, prev) => { if (s.project?.root === prev.project?.root) return; diff --git a/src/features/database/mybatis.test.ts b/src/features/database/mybatis.test.ts new file mode 100644 index 0000000000..fc0372b707 --- /dev/null +++ b/src/features/database/mybatis.test.ts @@ -0,0 +1,112 @@ +import { CompletionContext, type CompletionResult, type CompletionSource } from "@codemirror/autocomplete"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { CONTRIBUTED_HOVER, type ContributedHover } from "@/editor/api"; +import { useProject } from "@/platform/project"; +import { mapperExtension } from "./mybatis"; +import { useDatabase } from "./store"; + +const published = vi.hoisted(() => new Map>()); +vi.mock("@/editor/lsp/diagnostics", () => ({ + setFileDiagnostics: (path: string, _source: string, items: Array<{ message: string }>) => published.set(path, items), +})); + +const PATH = "/p/src/main/resources/mapper/UserMapper.xml"; +const DOC = ` + + + + + +`; + +let view: EditorView | null = null; + +beforeEach(() => { + vi.useFakeTimers(); + published.clear(); + useProject.setState({ + project: { name: "p", root: "/p", trusted: true } as never, + settings: { + database: { resolutionScopes: [{ path: "src/main/resources/mapper", dataSource: "pg", schema: "" }] }, + } as never, + }); + const column = (name: string) => ({ + name, + dataType: "text", + nullable: true, + primaryKey: name === "id", + hasDefault: false, + }); + useDatabase.setState({ + loaded: true, + sources: [ + { id: "pg", name: "Local", driver: "postgres" }, + { id: "other", name: "Other", driver: "postgres" }, + ], + consoles: {}, + consoleSchemas: {}, + completion: { + pg: { + defaultSchema: "public", + tables: [{ schema: "public", name: "users", kind: "table", columns: [column("id"), column("name")] }], + foreignKeys: [], + }, + }, + }); +}); + +afterEach(() => { + view?.destroy(); + view = null; + vi.useRealTimers(); +}); + +function open(doc: string) { + view = new EditorView({ + parent: document.body, + state: EditorState.create({ doc, extensions: mapperExtension({ path: PATH, language: "xml" } as never) }), + }); + return view; +} + +function completionAt(state: EditorState, pos: number): Promise { + const sources = state.languageDataAt("openideaCompletion", pos); + return Promise.resolve(sources[0]!(new CompletionContext(state, pos, true))); +} + +describe("SQL in MyBatis mappers", () => { + it("reports unresolved names of the statements against the scope's data source", () => { + open(DOC); + vi.advanceTimersByTime(1000); + const messages = (published.get(PATH) ?? []).map((d) => d.message); + expect(messages.some((m) => /nam\b/.test(m))).toBe(true); + expect(messages.some((m) => /orders/.test(m))).toBe(true); + expect(messages.some((m) => /users|\bid\b/.test(m))).toBe(false); + }); + + it("documents tables in the statements and nothing in the XML around them", () => { + const v = open(DOC); + const hover = v.state.languageDataAt(CONTRIBUTED_HOVER, 0)[0]!; + expect(hover(v.state, DOC.indexOf("users") + 2)?.markdown).toMatch(/users/); + expect(hover(v.state, DOC.indexOf("namespace") + 2)).toBeNull(); + }); + + it("completes columns inside a statement only", async () => { + const doc = DOC.replace("select id, nam from users", "select n from users"); + const v = open(doc); + const result = await completionAt(v.state, doc.indexOf("select n") + "select n".length); + expect(result?.options.map((o) => o.label)).toContain("name"); + expect(await completionAt(v.state, doc.indexOf("namespace") + 4)).toBeNull(); + }); + + it("leaves other XML files alone", () => { + const v = open(""); + vi.advanceTimersByTime(1000); + expect(published.get(PATH) ?? []).toEqual([]); + expect(v.dom.querySelectorAll("[class*=ͼ]").length).toBe(0); + }); +}); diff --git a/src/features/database/mybatis.ts b/src/features/database/mybatis.ts new file mode 100644 index 0000000000..2f4be8991e --- /dev/null +++ b/src/features/database/mybatis.ts @@ -0,0 +1,123 @@ +/** + * SQL in MyBatis mapper XML: the statements of ` + select id, name from users + + and name = #{name} + and id in + #{i} + + and age > 18 + + + + select last_insert_id() + insert into users (name) values (#{name}) + + + + update users name = #{a}, where id = #{id} +`; + +describe("MyBatis mapper SQL", () => { + it("recognises mapper files", () => { + expect(isMapper(MAPPER)).toBe(true); + expect(isMapper("")).toBe(false); + }); + + it("keeps the statements' SQL at its offsets and blanks the rest", () => { + const { text } = mapperSql(MAPPER); + expect(text).toHaveLength(MAPPER.length); + expect(text.split("\n")).toHaveLength(MAPPER.split("\n").length); + const sql = text.replace(/\s+/g, " ").trim(); + expect(sql).toBe( + "select id, name from users where name = ? and id in ( ? ) and age > 18 ; " + + "insert into users (name) values (? ) ; update users set name = ? where age < 3 ; " + + "update users set name = ? where id = ? ;", + ); + const at = MAPPER.indexOf("users"); + expect(text.slice(at, at + 5)).toBe("users"); + }); + + it("knows which offsets are SQL", () => { + const sql = mapperSql(MAPPER); + expect(inMapperSql(sql, MAPPER.indexOf("from users") + 2)).toBe(true); + expect(inMapperSql(sql, MAPPER.indexOf("resultMap="))).toBe(false); + expect(inMapperSql(sql, MAPPER.indexOf('test="name'))).toBe(false); + expect(inMapperSql(sql, MAPPER.indexOf("last_insert_id"))).toBe(false); + expect(inMapperSql(sql, MAPPER.indexOf("from old"))).toBe(false); + }); +}); diff --git a/src/features/database/sql/mapper.ts b/src/features/database/sql/mapper.ts new file mode 100644 index 0000000000..47e14ac728 --- /dev/null +++ b/src/features/database/sql/mapper.ts @@ -0,0 +1,154 @@ +/** + * The SQL of a MyBatis mapper XML file, as one text the SQL tools read: everything but the + * SQL of `