дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-16 14:45:40 +02:00
Порівняти коміти
1
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
a2f71a22d6 |
No files matched your search
@@ -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<CompletionResult | null> => {
|
||||
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,
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<string, Array<{ message: string }>>());
|
||||
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 = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.example.UserMapper">
|
||||
<select id="find">
|
||||
select id, nam from users where id = #{id}
|
||||
</select>
|
||||
<select id="other">select * from orders</select>
|
||||
</mapper>
|
||||
`;
|
||||
|
||||
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<CompletionResult | null> {
|
||||
const sources = state.languageDataAt<CompletionSource>("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<ContributedHover>(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("<beans><select>not sql</select></beans>");
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(published.get(PATH) ?? []).toEqual([]);
|
||||
expect(v.dom.querySelectorAll("[class*=ͼ]").length).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* SQL in MyBatis mapper XML: the statements of `<select>`, `<insert>`, `<update>`, `<delete>`
|
||||
* and `<sql>` are highlighted as SQL and get the SQL file's tools — completion, inspections,
|
||||
* Go to Declaration and Quick Documentation — against the file's data source (its SQL
|
||||
* resolution scope, or the project's only data source). See `sql/mapper` for what is SQL.
|
||||
*/
|
||||
import { MSSQL, MySQL, PLSQL, PostgreSQL, SQLite, StandardSQL, type SQLDialect } from "@codemirror/lang-sql";
|
||||
import { highlightingFor } from "@codemirror/language";
|
||||
import { EditorState, RangeSetBuilder, StateEffect, type Extension, type Text } from "@codemirror/state";
|
||||
import { Decoration, ViewPlugin, type DecorationSet, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { highlightTree } from "@lezer/highlight";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import type { DbDriver } from "@/platform/ipc";
|
||||
import { completionSource } from "./console";
|
||||
import { inMapperSql, isMapper, mapperSql, type MapperSql } from "./sql/mapper";
|
||||
import { sqlSupport, type SqlText } from "./sqlSupport";
|
||||
import { consoleSource, sourceById, useDatabase } from "./store";
|
||||
|
||||
const cache = new WeakMap<Text, MapperSql | null>();
|
||||
/** The file's data source (and so its dialect) changed: colour the statements again. */
|
||||
const recolour = StateEffect.define<null>();
|
||||
|
||||
/** The SQL of the mapper in `doc` (null when it is no mapper), computed once per document version. */
|
||||
function mapperOf(doc: Text): MapperSql | null {
|
||||
let sql = cache.get(doc);
|
||||
if (sql === undefined) {
|
||||
const text = doc.toString();
|
||||
sql = isMapper(text) ? mapperSql(text) : null;
|
||||
cache.set(doc, sql);
|
||||
}
|
||||
return sql;
|
||||
}
|
||||
|
||||
const MAPPER_SQL: SqlText = {
|
||||
text: (state) => mapperOf(state.doc)?.text ?? " ".repeat(state.doc.length),
|
||||
at: (state, pos) => {
|
||||
const sql = mapperOf(state.doc);
|
||||
return !!sql && inMapperSql(sql, pos);
|
||||
},
|
||||
};
|
||||
|
||||
function dialectOf(driver: DbDriver): SQLDialect {
|
||||
switch (driver) {
|
||||
case "postgres":
|
||||
return PostgreSQL;
|
||||
case "mysql":
|
||||
return MySQL;
|
||||
case "sqlite":
|
||||
return SQLite;
|
||||
case "sqlServer":
|
||||
return MSSQL;
|
||||
case "oracle":
|
||||
return PLSQL;
|
||||
default:
|
||||
return StandardSQL;
|
||||
}
|
||||
}
|
||||
|
||||
/** Syntax colours of the statements, in the bound data source's dialect, over the XML colours. */
|
||||
function sqlColours(path: string): Extension {
|
||||
const build = (view: EditorView): DecorationSet => {
|
||||
const sql = mapperOf(view.state.doc);
|
||||
if (!sql?.segments.length) return Decoration.none;
|
||||
const driver = sourceById(consoleSource(path))?.driver ?? "sqlite";
|
||||
const tree = dialectOf(driver).language.parser.parse(sql.text);
|
||||
const builder = new RangeSetBuilder<Decoration>();
|
||||
const marks = new Map<string, Decoration>();
|
||||
const style = { style: (tags: Parameters<typeof highlightingFor>[1]) => highlightingFor(view.state, tags) };
|
||||
let segment = 0;
|
||||
for (const { from, to } of view.visibleRanges)
|
||||
highlightTree(
|
||||
tree,
|
||||
style,
|
||||
(a, b, cls) => {
|
||||
// Only the file's own SQL text: the words standing in for tags are not shown.
|
||||
while (segment < sql.segments.length && sql.segments[segment]!.to <= a) segment++;
|
||||
for (let i = segment; i < sql.segments.length && sql.segments[i]!.from < b; i++) {
|
||||
const s = sql.segments[i]!;
|
||||
const f = Math.max(a, s.from);
|
||||
const t = Math.min(b, s.to);
|
||||
if (f >= t) continue;
|
||||
let mark = marks.get(cls);
|
||||
if (!mark) marks.set(cls, (mark = Decoration.mark({ class: cls })));
|
||||
builder.add(f, t, mark);
|
||||
}
|
||||
},
|
||||
from,
|
||||
to,
|
||||
);
|
||||
return builder.finish();
|
||||
};
|
||||
return ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet;
|
||||
private stop: () => void;
|
||||
constructor(readonly view: EditorView) {
|
||||
this.decorations = build(view);
|
||||
// Another data source may mean another dialect.
|
||||
this.stop = useDatabase.subscribe((s, prev) => {
|
||||
if (s.sources !== prev.sources || s.consoles !== prev.consoles)
|
||||
queueMicrotask(() => view.dispatch({ effects: recolour.of(null) }));
|
||||
});
|
||||
}
|
||||
update(u: ViewUpdate) {
|
||||
if (u.docChanged || u.viewportChanged || u.transactions.some((tr) => tr.effects.some((e) => e.is(recolour))))
|
||||
this.decorations = build(u.view);
|
||||
}
|
||||
destroy() {
|
||||
this.stop();
|
||||
}
|
||||
},
|
||||
{ decorations: (v) => v.decorations },
|
||||
);
|
||||
}
|
||||
|
||||
/** The SQL support of MyBatis mapper `ctx.path` (inert in other XML files). */
|
||||
export function mapperExtension(ctx: EditorDocContext): Extension {
|
||||
return [
|
||||
sqlColours(ctx.path),
|
||||
EditorState.languageData.of(() => [{ openideaCompletion: completionSource(ctx.path, MAPPER_SQL) }]),
|
||||
sqlSupport(ctx.path, MAPPER_SQL),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { inMapperSql, isMapper, mapperSql } from "./mapper";
|
||||
|
||||
const MAPPER = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.example.UserMapper">
|
||||
<resultMap id="user" type="User"><id column="id" property="id"/></resultMap>
|
||||
<select id="find" resultMap="user">
|
||||
select id, name from users
|
||||
<where>
|
||||
<if test="name != null">and name = #{name}</if>
|
||||
<if test="ids != null">and id in
|
||||
<foreach collection="ids" item="i" open="(" separator="," close=")">#{i}</foreach>
|
||||
</if>
|
||||
and age > 18
|
||||
</where>
|
||||
</select>
|
||||
<insert id="add">
|
||||
<selectKey keyProperty="id" resultType="int">select last_insert_id()</selectKey>
|
||||
insert into users (name) values (#{name})
|
||||
</insert>
|
||||
<!-- <select id="old">select * from old</select> -->
|
||||
<update id="rename"><![CDATA[update users set name = #{name} where age < 3]]></update>
|
||||
<update id="touch">update users <set><if test="a">name = #{a},</if></set> where id = #{id}</update>
|
||||
</mapper>`;
|
||||
|
||||
describe("MyBatis mapper SQL", () => {
|
||||
it("recognises mapper files", () => {
|
||||
expect(isMapper(MAPPER)).toBe(true);
|
||||
expect(isMapper("<beans><bean id='a'/></beans>")).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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* The SQL of a MyBatis mapper XML file, as one text the SQL tools read: everything but the
|
||||
* SQL of `<select>` / `<insert>` / `<update>` / `<delete>` / `<sql>` is blanked out with
|
||||
* spaces (line breaks kept), so offsets are the file's own. Parameters (`#{id}`, `${col}`)
|
||||
* read as `?`, entities as their character, dynamic tags as nothing — except `<where>`,
|
||||
* `<set>`, `<trim prefix>` and `<foreach open / close>`, which read as what they add — and
|
||||
* each statement ends with a `;`.
|
||||
*/
|
||||
|
||||
const STATEMENTS = new Set(["select", "insert", "update", "delete", "sql"]);
|
||||
/** Their content is not part of the statement's SQL. */
|
||||
const SKIPPED = new Set(["selectKey"]);
|
||||
const ENTITIES: Record<string, string> = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'" };
|
||||
|
||||
export interface MapperSql {
|
||||
/** The file's text with only SQL left (same length). */
|
||||
text: string;
|
||||
/** The SQL text taken from the file, as ranges of offsets: the positions the SQL tools apply to. */
|
||||
segments: Array<{ from: number; to: number }>;
|
||||
}
|
||||
|
||||
/** Whether `text` is a MyBatis (or iBatis) mapper. */
|
||||
export function isMapper(text: string): boolean {
|
||||
const head = text.slice(0, 4000);
|
||||
return /<mapper[\s>]/.test(head) && /mybatis|ibatis|<mapper[^>]*\snamespace\s*=/i.test(head);
|
||||
}
|
||||
|
||||
const TAG = /<!--[\s\S]*?(?:-->|$)|<!\[CDATA\[|\]\]>|<(\/?)([A-Za-z_][\w.:-]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
|
||||
|
||||
function attr(attrs: string, name: string): string | null {
|
||||
const m = new RegExp(`(?:^|\\s)${name}\\s*=\\s*("([^"]*)"|'([^']*)')`).exec(attrs);
|
||||
return m ? (m[2] ?? m[3] ?? "") : null;
|
||||
}
|
||||
|
||||
export function mapperSql(doc: string): MapperSql {
|
||||
const out = doc.replace(/[^\n]/g, " ").split("");
|
||||
const segments: MapperSql["segments"] = [];
|
||||
/** Writes `what` at `at`, as far as `room` characters allow. */
|
||||
const put = (at: number, what: string, room: number) => {
|
||||
if (what.length > room) return;
|
||||
for (let i = 0; i < what.length; i++) out[at + i] = what[i]!;
|
||||
};
|
||||
const copy = (from: number, to: number) => {
|
||||
if (to <= from) return;
|
||||
let at = from;
|
||||
const text = doc.slice(from, to);
|
||||
// Parameters and entities inside the SQL text.
|
||||
const special = /#\{[^}]*\}?|\$\{[^}]*\}?|&(lt|gt|amp|quot|apos);/g;
|
||||
for (let m = special.exec(text); m; m = special.exec(text)) {
|
||||
const start = from + m.index;
|
||||
for (let i = at; i < start; i++) out[i] = doc[i]!;
|
||||
if (m[1]) put(start, ENTITIES[m[1]]!, m[0].length);
|
||||
else put(start, "?", m[0].length);
|
||||
at = start + m[0].length;
|
||||
}
|
||||
for (let i = at; i < to; i++) out[i] = doc[i]!;
|
||||
const last = segments.at(-1);
|
||||
if (last && last.to === from) last.to = to;
|
||||
else segments.push({ from, to });
|
||||
};
|
||||
|
||||
/** Inside a statement: its depth of nested tags, the `close` text of open `<foreach>` / `<trim>`. */
|
||||
let statement: { name: string; depth: number } | null = null;
|
||||
const closes: Array<{ text: string | null; trailingComma: boolean }> = [];
|
||||
/** Where `<where>` / `<trim prefixOverrides>` drop a leading AND / OR, `<set>` a trailing comma. */
|
||||
const leading: number[] = [];
|
||||
const trailing: number[] = [];
|
||||
let skipping = 0;
|
||||
let textFrom = 0;
|
||||
TAG.lastIndex = 0;
|
||||
for (let m = TAG.exec(doc); m; m = TAG.exec(doc)) {
|
||||
const at = m.index;
|
||||
const end = at + m[0].length;
|
||||
if (statement && !skipping) copy(textFrom, at);
|
||||
textFrom = end;
|
||||
const [whole, closing, name, attrs = "", selfClosing] = m;
|
||||
// CDATA content is SQL text as written, markup characters included.
|
||||
if (whole === "<![CDATA[") {
|
||||
const close = doc.indexOf("]]>", end);
|
||||
const stop = close < 0 ? doc.length : close;
|
||||
if (statement && !skipping) copy(end, stop);
|
||||
textFrom = TAG.lastIndex = Math.min(doc.length, stop + 3);
|
||||
continue;
|
||||
}
|
||||
// Comments (and a stray `]]>`) are blank.
|
||||
if (!name) continue;
|
||||
if (!statement) {
|
||||
if (!closing && !selfClosing && STATEMENTS.has(name)) statement = { name, depth: 0 };
|
||||
continue;
|
||||
}
|
||||
if (closing) {
|
||||
if (statement.depth === 0 && name === statement.name) {
|
||||
put(at, ";", whole.length);
|
||||
statement = null;
|
||||
closes.length = 0;
|
||||
skipping = 0;
|
||||
continue;
|
||||
}
|
||||
statement.depth = Math.max(0, statement.depth - 1);
|
||||
if (skipping) {
|
||||
skipping--;
|
||||
continue;
|
||||
}
|
||||
const close = closes.pop();
|
||||
if (close?.trailingComma) trailing.push(at);
|
||||
if (close?.text) put(at, ` ${close.text} `, whole.length);
|
||||
continue;
|
||||
}
|
||||
if (selfClosing) continue;
|
||||
statement.depth++;
|
||||
if (skipping || SKIPPED.has(name)) {
|
||||
skipping++;
|
||||
continue;
|
||||
}
|
||||
let open: string | null = null;
|
||||
let close: string | null = null;
|
||||
let trailingComma = false;
|
||||
if (name === "where") {
|
||||
open = "where";
|
||||
leading.push(end);
|
||||
} else if (name === "set") {
|
||||
open = "set";
|
||||
trailingComma = true;
|
||||
} else if (name === "trim") {
|
||||
open = attr(attrs, "prefix");
|
||||
close = attr(attrs, "suffix");
|
||||
if (/\b(and|or)\b/i.test(attr(attrs, "prefixOverrides") ?? "")) leading.push(end);
|
||||
trailingComma = (attr(attrs, "suffixOverrides") ?? "").includes(",");
|
||||
} else if (name === "foreach") {
|
||||
open = attr(attrs, "open");
|
||||
close = attr(attrs, "close");
|
||||
}
|
||||
if (open) put(at, ` ${open} `, whole.length);
|
||||
closes.push({ text: close, trailingComma });
|
||||
}
|
||||
if (statement && !skipping) copy(textFrom, doc.length);
|
||||
for (const from of leading) {
|
||||
let i = from;
|
||||
while (i < out.length && /\s/.test(out[i]!)) i++;
|
||||
const word = /^(and|or)\b/i.exec(out.slice(i, i + 4).join(""));
|
||||
if (word) for (let k = 0; k < word[0].length; k++) out[i + k] = " ";
|
||||
}
|
||||
for (const before of trailing) {
|
||||
let i = before - 1;
|
||||
while (i >= 0 && /\s/.test(out[i]!)) i--;
|
||||
if (out[i] === ",") out[i] = " ";
|
||||
}
|
||||
return { text: out.join(""), segments };
|
||||
}
|
||||
|
||||
/** Whether offset `pos` is in (or right after) SQL text of the mapper. */
|
||||
export function inMapperSql(sql: MapperSql, pos: number): boolean {
|
||||
return sql.segments.some((s) => pos >= s.from && pos <= s.to);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { offsetToPos } from "@/editor/lsp/positions";
|
||||
import type { DbCompletion, DbCompletionTable, DbDriver } from "@/platform/ipc";
|
||||
import { formatSql } from "./sql/format";
|
||||
import { SqlResolver, type SqlSymbol } from "./sql/resolve";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { consoleSchema, consoleSource, revealInTree, sourceById, useDatabase } from "./store";
|
||||
|
||||
/** Producer id of the console's diagnostics (Problems view, hover). */
|
||||
@@ -38,18 +39,29 @@ function sourceOf(path: string): { id: string | null; driver: DbDriver; model: D
|
||||
};
|
||||
}
|
||||
|
||||
function resolver(path: string, state: EditorState): SqlResolver {
|
||||
/**
|
||||
* Where the SQL of a file is: its text as the SQL tools read it (the file's offsets), and
|
||||
* whether an offset is in SQL. A SQL file is SQL throughout; a MyBatis mapper only in its statements.
|
||||
*/
|
||||
export interface SqlText {
|
||||
text(state: EditorState): string;
|
||||
at?(state: EditorState, pos: number): boolean;
|
||||
}
|
||||
|
||||
export const WHOLE_FILE: SqlText = { text: (state) => state.doc.toString() };
|
||||
|
||||
function resolver(path: string, state: EditorState, sql: SqlText): SqlResolver {
|
||||
const { driver, model } = sourceOf(path);
|
||||
return new SqlResolver(state.doc.toString(), driver, model);
|
||||
return new SqlResolver(sql.text(state), driver, model);
|
||||
}
|
||||
|
||||
/** Unresolved tables / columns / aliases as error diagnostics, re-checked after edits and schema loads. */
|
||||
function inspections(path: string): Extension {
|
||||
function inspections(path: string, sql: SqlText): Extension {
|
||||
return ViewPlugin.define((view) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const run = () => {
|
||||
const doc = view.state.doc;
|
||||
const problems = sourceOf(path).model ? resolver(path, view.state).problems() : [];
|
||||
const problems = sourceOf(path).model ? resolver(path, view.state, sql).problems() : [];
|
||||
setFileDiagnostics(
|
||||
path,
|
||||
INSPECTIONS,
|
||||
@@ -69,9 +81,18 @@ function inspections(path: string): Extension {
|
||||
schedule();
|
||||
// The schema model arrives (or the console is bound to another source / schema) after the editor opens.
|
||||
const unsubscribe = useDatabase.subscribe((s, prev) => {
|
||||
if (s.completion !== prev.completion || s.consoles !== prev.consoles || s.consoleSchemas !== prev.consoleSchemas)
|
||||
if (
|
||||
s.completion !== prev.completion ||
|
||||
s.consoles !== prev.consoles ||
|
||||
s.consoleSchemas !== prev.consoleSchemas ||
|
||||
s.sources !== prev.sources
|
||||
)
|
||||
schedule();
|
||||
});
|
||||
// SQL resolution scopes can move the file to another data source.
|
||||
const unsubscribeSettings = useProject.subscribe((s, prev) => {
|
||||
if (s.settings !== prev.settings) schedule();
|
||||
});
|
||||
return {
|
||||
update: (u) => {
|
||||
if (u.docChanged) schedule();
|
||||
@@ -79,16 +100,20 @@ function inspections(path: string): Extension {
|
||||
destroy: () => {
|
||||
clearTimeout(timer);
|
||||
unsubscribe();
|
||||
unsubscribeSettings();
|
||||
setFileDiagnostics(path, INSPECTIONS, []);
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function definition(path: string): ContributedDefinition {
|
||||
function definition(path: string, sql: SqlText): ContributedDefinition {
|
||||
return (view, pos) => {
|
||||
const r = resolver(path, view.state).resolveAt(pos);
|
||||
if (sql.at && !sql.at(view.state, pos)) return false;
|
||||
const r = resolver(path, view.state, sql).resolveAt(pos);
|
||||
const sym = r?.symbol;
|
||||
// Outside SQL names, other providers (the XML language server) may know the place.
|
||||
if (!sym && sql.at) return false;
|
||||
const id = consoleSource(path);
|
||||
const reveal = (t: DbCompletionTable, column?: string) => {
|
||||
if (id) void revealInTree(id, t.schema, t.name, t.kind, column);
|
||||
@@ -172,9 +197,10 @@ function symbolDoc(sym: SqlSymbol, model: DbCompletion | null): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
function hover(path: string): ContributedHover {
|
||||
function hover(path: string, sql: SqlText): ContributedHover {
|
||||
return (state, pos) => {
|
||||
const r = resolver(path, state).resolveAt(pos);
|
||||
if (sql.at && !sql.at(state, pos)) return null;
|
||||
const r = resolver(path, state, sql).resolveAt(pos);
|
||||
const markdown = r?.symbol ? symbolDoc(r.symbol, sourceOf(path).model) : null;
|
||||
return r && markdown ? { from: r.from, to: r.to, markdown } : null;
|
||||
};
|
||||
@@ -184,11 +210,12 @@ function formatter(path: string): ContributedFormatter {
|
||||
return (state, range) => formatSql(state.doc.toString(), sourceOf(path).driver, range);
|
||||
}
|
||||
|
||||
export function sqlSupport(path: string): Extension {
|
||||
/** Inspections, navigation and documentation for the SQL of `path` (and Reformat Code for SQL files). */
|
||||
export function sqlSupport(path: string, sql: SqlText = WHOLE_FILE): Extension {
|
||||
const data = {
|
||||
[CONTRIBUTED_DEFINITION]: definition(path),
|
||||
[CONTRIBUTED_HOVER]: hover(path),
|
||||
[CONTRIBUTED_FORMAT]: formatter(path),
|
||||
[CONTRIBUTED_DEFINITION]: definition(path, sql),
|
||||
[CONTRIBUTED_HOVER]: hover(path, sql),
|
||||
...(sql === WHOLE_FILE ? { [CONTRIBUTED_FORMAT]: formatter(path) } : {}),
|
||||
};
|
||||
return [inspections(path), EditorState.languageData.of(() => [data])];
|
||||
return [inspections(path, sql), EditorState.languageData.of(() => [data])];
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача