feat(query-editor): enhance current statement framing
This commit is contained in:
18 files changed
+480
-10
No files matched your search
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { currentStatementFrameRangeTo, isWideSqlChar, visualSqlColumns } from "@/lib/sql/currentStatementFrame";
|
||||
import type { SqlTextRange } from "@/lib/sql/sqlStatementRanges";
|
||||
|
||||
describe("currentStatementFrameRangeTo", () => {
|
||||
it("includes a directly adjacent trailing semicolon in frame width calculations", () => {
|
||||
const range: SqlTextRange = { from: 0, to: "SELECT 1".length, sql: "SELECT 1" };
|
||||
expect(currentStatementFrameRangeTo(";", range)).toBe(range.to + 1);
|
||||
});
|
||||
|
||||
it("does not extend the frame when the next character is not a semicolon", () => {
|
||||
const range: SqlTextRange = { from: 0, to: "SELECT 1".length, sql: "SELECT 1" };
|
||||
expect(currentStatementFrameRangeTo("\n", range)).toBe(range.to);
|
||||
});
|
||||
});
|
||||
|
||||
describe("visualSqlColumns", () => {
|
||||
it("counts ASCII as one column, tabs as four, and CJK/fullwidth characters as two", () => {
|
||||
expect(visualSqlColumns("A\t中B")).toBe(1 + 4 + 2 + 2);
|
||||
});
|
||||
|
||||
it("recognizes common wide SQL text characters", () => {
|
||||
expect(isWideSqlChar("中")).toBe(true);
|
||||
expect(isWideSqlChar("A")).toBe(true);
|
||||
expect(isWideSqlChar("A")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Text } from "@codemirror/state";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { executableStatementRangeCacheForDoc, executableStatementRangeStartingAt, type ExecutableStatementRangeParser } from "@/lib/sql/executableStatementRangeCache";
|
||||
import { executableStatementRangeAtCursor, executableStatementRangeCacheForDoc, executableStatementRangeStartingAt, type ExecutableStatementRangeParser } from "@/lib/sql/executableStatementRangeCache";
|
||||
|
||||
describe("executableStatementRangeCacheForDoc", () => {
|
||||
it("reuses parsed executable statement ranges for the same document and database type", () => {
|
||||
@@ -27,6 +27,41 @@ describe("executableStatementRangeCacheForDoc", () => {
|
||||
expect(executableStatementRangeStartingAt(cache, secondStatementLine.from)?.sql).toBe("SELECT *\nFROM menus AS mn\nLIMIT 100");
|
||||
});
|
||||
|
||||
it("resolves the current statement from a cursor inside a continuation line", () => {
|
||||
const doc = Text.of(["SELECT *", "FROM apis AS ap", "LIMIT 100;", "", "SELECT *", "FROM menus AS mn", "LIMIT 100;"]);
|
||||
const cache = executableStatementRangeCacheForDoc(null, doc, "mysql");
|
||||
const cursor = doc.toString().indexOf("menus");
|
||||
|
||||
expect(executableStatementRangeAtCursor(cache, cursor)?.sql).toBe("SELECT *\nFROM menus AS mn\nLIMIT 100");
|
||||
});
|
||||
|
||||
it("keeps indentation and same-line semicolon gaps attached to the current statement", () => {
|
||||
const doc = Text.of(["SELECT 1;", " SELECT 2;"]);
|
||||
const cache = executableStatementRangeCacheForDoc(null, doc, "mysql");
|
||||
const indentationCursor = doc.line(2).from + 2;
|
||||
const semicolonGapCursor = doc.toString().indexOf(";") + 1;
|
||||
|
||||
expect(executableStatementRangeAtCursor(cache, indentationCursor)?.sql).toBe("SELECT 2");
|
||||
expect(executableStatementRangeAtCursor(cache, semicolonGapCursor)?.sql).toBe("SELECT 1");
|
||||
});
|
||||
|
||||
it("returns null for blank and pure comment cursor lines", () => {
|
||||
const doc = Text.of(["SELECT 1;", "-- comment", "/* block comment */", "", "SELECT 2;"]);
|
||||
const cache = executableStatementRangeCacheForDoc(null, doc, "mysql");
|
||||
|
||||
expect(executableStatementRangeAtCursor(cache, doc.line(2).from + 3)).toBeNull();
|
||||
expect(executableStatementRangeAtCursor(cache, doc.line(3).from + 3)).toBeNull();
|
||||
expect(executableStatementRangeAtCursor(cache, doc.line(4).from)).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves SQL after a leading block comment on the same line", () => {
|
||||
const doc = Text.of(["/* comment */ SELECT 1;"]);
|
||||
const cache = executableStatementRangeCacheForDoc(null, doc, "mysql");
|
||||
|
||||
expect(executableStatementRangeAtCursor(cache, doc.toString().indexOf("SELECT"))?.sql).toBe("SELECT 1");
|
||||
expect(executableStatementRangeAtCursor(cache, doc.toString().indexOf("comment"))).toBeNull();
|
||||
});
|
||||
|
||||
it("rebuilds the cache when the document instance changes", () => {
|
||||
const firstDoc = Text.of(["SELECT 1;"]);
|
||||
const secondDoc = Text.of(["SELECT 1;"]);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildExecutionCandidates, executableStatementRanges, fullSqlRange, hasMultipleExecutionTargets, splitSqlStatementRanges, statementRangeAtCursor, supportsExecutionTargetPicker } from "@/lib/sql/sqlStatementRanges";
|
||||
import { buildExecutionCandidates, currentExecutableStatementRange, executableStatementRanges, fullSqlRange, hasMultipleExecutionTargets, splitSqlStatementRanges, statementRangeAtCursor, supportsExecutionTargetPicker } from "@/lib/sql/sqlStatementRanges";
|
||||
|
||||
function indexOf(sql: string, needle: string, occurrence = 1): number {
|
||||
let from = 0;
|
||||
@@ -74,6 +74,17 @@ BEGIN
|
||||
END;
|
||||
SELECT 2;`;
|
||||
|
||||
const mysqlRoutineWithLoopsFixture = `CREATE PROCEDURE p_loop()
|
||||
BEGIN
|
||||
WHILE 1 = 0 DO
|
||||
SELECT 'while; still body';
|
||||
END WHILE;
|
||||
REPEAT
|
||||
SELECT 'repeat; still body';
|
||||
UNTIL 1 = 1 END REPEAT;
|
||||
END;
|
||||
SELECT 2;`;
|
||||
|
||||
describe("splitSqlStatementRanges", () => {
|
||||
it("splits multiple top-level statements", () => {
|
||||
const sql = "SELECT 1;\nSELECT 2;\nSELECT 3;";
|
||||
@@ -149,6 +160,16 @@ describe("splitSqlStatementRanges", () => {
|
||||
expect(rangeSqlTexts(splitSqlStatementRanges(sql, "mysql"))).toEqual(["BEGIN", "INSERT INTO t VALUES (1)", "COMMIT"]);
|
||||
});
|
||||
|
||||
it("treats SQL Server GO lines as batch delimiters", () => {
|
||||
const sql = "SELECT 1\nGO\nSELECT 2;\n GO 2\nSELECT 3";
|
||||
expect(rangeSqlTexts(splitSqlStatementRanges(sql, "sqlserver"))).toEqual(["SELECT 1", "SELECT 2", "SELECT 3"]);
|
||||
});
|
||||
|
||||
it("does not treat GO inside strings or comments as a SQL Server batch delimiter", () => {
|
||||
const sql = "SELECT 'GO'\n-- GO\nSELECT 2\nGO\nSELECT 3";
|
||||
expect(rangeSqlTexts(splitSqlStatementRanges(sql, "sqlserver"))).toEqual(["SELECT 'GO'\n-- GO\nSELECT 2", "SELECT 3"]);
|
||||
});
|
||||
|
||||
it("keeps Oracle PL/SQL blocks together and treats slash lines as delimiters", () => {
|
||||
const ranges = splitSqlStatementRanges(oraclePlSqlFixture, "oracle");
|
||||
expect(rangeSqlTexts(ranges)).toEqual([oraclePlSqlFixture.slice(0, oraclePlSqlFixture.indexOf("\n/")), "SELECT 1"]);
|
||||
@@ -386,6 +407,18 @@ WHERE request_json LIKE '%"paperFlag":null%';`;
|
||||
expect(range?.sql.trim()).toBe(mysqlRoutineFixture.slice(0, mysqlRoutineFixture.indexOf("\nSELECT 2;")).replace(/;$/, "").trim());
|
||||
});
|
||||
|
||||
it("returns null on SQL Server GO batch delimiter lines", () => {
|
||||
const sql = "SELECT 1\nGO\nSELECT 2";
|
||||
expect(statementRangeAtCursor(sql, indexOf(sql, "GO"), "sqlserver")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns the current SQL Server batch around GO delimiters", () => {
|
||||
const sql = "SELECT 1\nGO\nSELECT 2\nGO\nSELECT 3";
|
||||
expect(statementRangeAtCursor(sql, indexOf(sql, "1"), "sqlserver")?.sql.trim()).toBe("SELECT 1");
|
||||
expect(statementRangeAtCursor(sql, indexOf(sql, "2"), "sqlserver")?.sql.trim()).toBe("SELECT 2");
|
||||
expect(statementRangeAtCursor(sql, indexOf(sql, "3"), "sqlserver")?.sql.trim()).toBe("SELECT 3");
|
||||
});
|
||||
|
||||
it("returns the full Oracle PL/SQL block for cursors inside nested statements", () => {
|
||||
const range = statementRangeAtCursor(oraclePlSqlFixture, indexOf(oraclePlSqlFixture, "ORDERS_10K", 2), "oracle");
|
||||
expect(range?.sql.trim()).toBe(oraclePlSqlFixture.slice(0, oraclePlSqlFixture.indexOf("\n/")));
|
||||
@@ -427,6 +460,42 @@ describe("executableStatementRanges", () => {
|
||||
it("does not split executable MySQL routine ranges at inner statements", () => {
|
||||
expect(rangeSqlTexts(executableStatementRanges(mysqlRoutineFixture, "mysql"))).toEqual([mysqlRoutineFixture.slice(0, mysqlRoutineFixture.indexOf("\nSELECT 2;")).replace(/;$/, "").trim(), "SELECT 2"]);
|
||||
});
|
||||
|
||||
it("does not split executable MySQL routine ranges at WHILE and REPEAT endings", () => {
|
||||
expect(rangeSqlTexts(executableStatementRanges(mysqlRoutineWithLoopsFixture, "mysql"))).toEqual([mysqlRoutineWithLoopsFixture.slice(0, mysqlRoutineWithLoopsFixture.indexOf("\nSELECT 2;")).replace(/;$/, "").trim(), "SELECT 2"]);
|
||||
});
|
||||
|
||||
it("returns executable SQL Server batches without GO delimiter lines", () => {
|
||||
expect(rangeSqlTexts(executableStatementRanges("SELECT 1\nGO\nSELECT 2;", "sqlserver"))).toEqual(["SELECT 1", "SELECT 2"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("currentExecutableStatementRange", () => {
|
||||
it("uses the current SQL statement range for multi-line DDL", () => {
|
||||
const sql = "ALTER TABLE `yb_course_order`\n ADD COLUMN `audit_status` tinyint(4) DEFAULT NULL\n COMMENT '审核状态:0-待审核,1-已通过,2-已拒绝',\n ADD COLUMN `close_reason` varchar(30) DEFAULT NULL\n COMMENT '关闭原因:timeout-超时关闭,cancel-取消关闭,refund-退款关闭';\nSELECT 1;";
|
||||
|
||||
expect(currentExecutableStatementRange(sql, indexOf(sql, "close_reason"), "mysql")?.sql.trim()).toBe(sql.slice(0, sql.indexOf(";\nSELECT")));
|
||||
});
|
||||
|
||||
it("returns null on blank and pure comment lines", () => {
|
||||
const sql = "SELECT 1;\n-- comment\n\nSELECT 2;";
|
||||
|
||||
expect(currentExecutableStatementRange(sql, indexOf(sql, "comment"), "mysql")).toBeNull();
|
||||
expect(currentExecutableStatementRange(sql, sql.indexOf("\n\n") + 1, "mysql")).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the current Redis command line", () => {
|
||||
const sql = "GET user:1\n DEL user:2\n# comment";
|
||||
|
||||
expect(currentExecutableStatementRange(sql, indexOf(sql, "DEL"), "redis")?.sql).toBe("DEL user:2");
|
||||
expect(currentExecutableStatementRange(sql, indexOf(sql, "comment"), "redis")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not expose current statement framing for MongoDB", () => {
|
||||
const sql = "db.users.find({})";
|
||||
|
||||
expect(currentExecutableStatementRange(sql, indexOf(sql, "users"), "mongodb")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("fullSqlRange", () => {
|
||||
@@ -526,6 +595,12 @@ describe("buildExecutionCandidates", () => {
|
||||
const candidates = buildExecutionCandidates(sql, indexOf(sql, "COUNT", 2), "mysql");
|
||||
expect(candidateSummaries(candidates)).toEqual(["cursor:select COUNT(1) FROM your_table;", "all:select COUNT(1) FROM your_table;\ndelimiter ;;\nselect COUNT(1) FROM your_table;\n\n;;\ndelimiter ;"]);
|
||||
});
|
||||
|
||||
it("uses the current SQL Server batch for cursor candidates", () => {
|
||||
const sql = "SELECT 1\nGO\nSELECT 2;";
|
||||
const candidates = buildExecutionCandidates(sql, indexOf(sql, "2"), "sqlserver");
|
||||
expect(candidateSummaries(candidates)).toEqual(["cursor:SELECT 2", "all:SELECT 1\nGO\nSELECT 2;"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasMultipleExecutionTargets", () => {
|
||||
@@ -555,6 +630,10 @@ describe("hasMultipleExecutionTargets", () => {
|
||||
expect(hasMultipleExecutionTargets(mysqlRoutineFixture, "mysql")).toBe(true);
|
||||
});
|
||||
|
||||
it("counts SQL Server GO batches as multiple execution targets", () => {
|
||||
expect(hasMultipleExecutionTargets("SELECT 1\nGO\nSELECT 2", "sqlserver")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not show multiple targets for MySQL DESC UPDATE joins", () => {
|
||||
const sql = "desc update test_orders a\njoin test_users b\non a.id=b.id \nset a.name = '张三'\nwhere b.id > 10;";
|
||||
expect(hasMultipleExecutionTargets(sql, "mysql")).toBe(false);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { SqlTextRange } from "@/lib/sql/sqlStatementRanges";
|
||||
|
||||
export function currentStatementFrameRangeTo(nextChar: string, range: SqlTextRange): number {
|
||||
return nextChar === ";" ? range.to + 1 : range.to;
|
||||
}
|
||||
|
||||
export function visualSqlColumns(text: string): number {
|
||||
let columns = 0;
|
||||
for (const ch of text) {
|
||||
if (ch === "\t") {
|
||||
columns += 4;
|
||||
} else if (isWideSqlChar(ch)) {
|
||||
columns += 2;
|
||||
} else {
|
||||
columns += 1;
|
||||
}
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
export function isWideSqlChar(ch: string): boolean {
|
||||
return /[\u1100-\u115f\u2329\u232a\u2e80-\u303e\u3040-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe10-\ufe19\ufe30-\ufe6f\uff00-\uff60\uffe0-\uffe6]/u.test(ch);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ export interface ExecutableStatementRangeCache {
|
||||
doc: Text;
|
||||
databaseType?: DatabaseType;
|
||||
byStart: Map<number, SqlTextRange>;
|
||||
ranges: SqlTextRange[];
|
||||
}
|
||||
|
||||
export type ExecutableStatementRangeParser = (sql: string, databaseType?: DatabaseType) => SqlTextRange[];
|
||||
@@ -14,12 +15,59 @@ export function executableStatementRangeCacheForDoc(cache: ExecutableStatementRa
|
||||
if (cache?.doc === doc && cache.databaseType === databaseType) return cache;
|
||||
|
||||
const byStart = new Map<number, SqlTextRange>();
|
||||
for (const range of parse(doc.toString(), databaseType)) {
|
||||
const ranges = parse(doc.toString(), databaseType);
|
||||
for (const range of ranges) {
|
||||
byStart.set(range.from, range);
|
||||
}
|
||||
return { doc, databaseType, byStart };
|
||||
return { doc, databaseType, byStart, ranges };
|
||||
}
|
||||
|
||||
export function executableStatementRangeStartingAt(cache: ExecutableStatementRangeCache, lineFrom: number): SqlTextRange | null {
|
||||
return cache.byStart.get(lineFrom) ?? null;
|
||||
}
|
||||
|
||||
export function executableStatementRangeAtCursor(cache: ExecutableStatementRangeCache, cursorPos: number): SqlTextRange | null {
|
||||
const pos = Math.max(0, Math.min(cursorPos, cache.doc.length));
|
||||
const line = cache.doc.lineAt(pos);
|
||||
const lineText = line.text.trim();
|
||||
if (!lineText || lineText.startsWith("--") || lineText.startsWith("#") || isCursorOnLeadingBlockComment(line.text, pos - line.from)) return null;
|
||||
|
||||
for (let index = 0; index < cache.ranges.length; index += 1) {
|
||||
const range = cache.ranges[index];
|
||||
if (pos >= range.from && pos <= range.to) return range;
|
||||
|
||||
if (pos < range.from && range.from <= line.to && cache.doc.sliceString(pos, range.from).trim() === "") {
|
||||
return range;
|
||||
}
|
||||
|
||||
const next = cache.ranges[index + 1];
|
||||
if (pos > range.to && (!next || pos < next.from) && range.to >= line.from && range.to <= line.to && cursorRemainsOnRangeLine(cache.doc, range.to, pos)) {
|
||||
return range;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function isCursorOnLeadingBlockComment(lineText: string, lineOffset: number): boolean {
|
||||
const commentStart = lineText.search(/\S/);
|
||||
if (commentStart < 0 || !lineText.startsWith("/*", commentStart)) return false;
|
||||
|
||||
const commentEnd = lineText.indexOf("*/", commentStart + 2);
|
||||
if (commentEnd < 0) return true;
|
||||
const afterComment = lineText.slice(commentEnd + 2);
|
||||
if (!afterComment.trim()) return true;
|
||||
|
||||
return lineOffset <= commentEnd + 2;
|
||||
}
|
||||
|
||||
function cursorRemainsOnRangeLine(doc: Text, rangeTo: number, cursorPos: number): boolean {
|
||||
const between = doc.sliceString(rangeTo, cursorPos);
|
||||
if (between.includes("\n")) return false;
|
||||
const delimiterIndex = between.lastIndexOf(";");
|
||||
if (delimiterIndex === -1) return between.trim() === "";
|
||||
|
||||
const beforeDelimiter = between.slice(0, delimiterIndex);
|
||||
const afterDelimiter = between.slice(delimiterIndex + 1);
|
||||
return beforeDelimiter.trim() === "" && afterDelimiter.trim() === "";
|
||||
}
|
||||
@@ -271,6 +271,14 @@ export function splitSqlStatementRanges(sql: string, databaseType?: DatabaseType
|
||||
continue;
|
||||
}
|
||||
|
||||
if (supportsSqlServerGoCommands(databaseType) && isAtLineStart(sql, i) && isSqlServerGoLine(sql, i)) {
|
||||
const lineEnd = findLineEnd(sql, i);
|
||||
flush(i);
|
||||
i = nextLineStart(sql, lineEnd);
|
||||
statementHitStart = i;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === "'") {
|
||||
markContent(i);
|
||||
state = "single";
|
||||
@@ -296,7 +304,7 @@ export function splitSqlStatementRanges(sql: string, databaseType?: DatabaseType
|
||||
continue;
|
||||
}
|
||||
// Postgres dollar quoting: $tag$ ... $tag$ (tag may be empty, i.e. $$)
|
||||
if (ch === "$") {
|
||||
if (!customDelimiter && ch === "$") {
|
||||
const tagMatch = /^\$[A-Za-z_0-9]*\$/.exec(sql.slice(i));
|
||||
if (tagMatch) {
|
||||
markContent(i);
|
||||
@@ -1386,6 +1394,15 @@ function isSlashLine(sql: string, pos: number): boolean {
|
||||
return sql.slice(pos, lineEnd).trim() === "/";
|
||||
}
|
||||
|
||||
function supportsSqlServerGoCommands(databaseType?: DatabaseType): boolean {
|
||||
return databaseType === "sqlserver";
|
||||
}
|
||||
|
||||
function isSqlServerGoLine(sql: string, pos: number): boolean {
|
||||
const lineEnd = findLineEnd(sql, pos);
|
||||
return /^go(?:\s+\d+)?$/i.test(sql.slice(pos, lineEnd).trim());
|
||||
}
|
||||
|
||||
function startsDelimiterCommand(sql: string, pos: number): boolean {
|
||||
const prefix = sql.slice(pos, pos + 9);
|
||||
return prefix.toLowerCase() === "delimiter" && (sql[pos + 9] === " " || sql[pos + 9] === "\t");
|
||||
@@ -1468,9 +1485,15 @@ export function executableStatementRanges(sql: string, databaseType?: DatabaseTy
|
||||
return splitSqlStatementRanges(sql, databaseType).flatMap((statement) => splitStatementRangeAtSoftStarts(sql, statement, databaseType).map((range) => rangeFor(range, sql)));
|
||||
}
|
||||
|
||||
export function currentExecutableStatementRange(sql: string, cursorPos: number, databaseType?: DatabaseType): SqlTextRange | null {
|
||||
if (databaseType === "redis") return redisCommandRangeAtCursor(sql, cursorPos);
|
||||
if (databaseType === "mongodb") return null;
|
||||
return statementRangeAtCursor(sql, cursorPos, databaseType);
|
||||
}
|
||||
|
||||
export function buildExecutionCandidates(sql: string, cursorPos: number, databaseType?: DatabaseType): SqlExecutionCandidate[] {
|
||||
const full = fullSqlRange(sql);
|
||||
const cursorStatement = databaseType === "redis" ? redisCommandRangeAtCursor(sql, cursorPos) : statementRangeAtCursor(sql, cursorPos, databaseType);
|
||||
const cursorStatement = currentExecutableStatementRange(sql, cursorPos, databaseType);
|
||||
|
||||
if (!full && !cursorStatement) return [];
|
||||
if (!full) {
|
||||
|
||||
Reference in new issue
Block a user