feat(sql-library): show matching line snippets with jump in search
This commit is contained in:
1 parent
eeeb67e62c
commit
51f9dfc854
19 files changed
+686
-106
No files matched your search
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { findSavedSqlSearchMatches, formatMatchTooltip, formatSnippetLine, splitSearchMatchSegments } from "@/lib/savedSql/savedSqlSearch";
|
||||
|
||||
describe("splitSearchMatchSegments", () => {
|
||||
it("returns empty or untouched segments when input or query is empty", () => {
|
||||
expect(splitSearchMatchSegments("", "select")).toEqual([]);
|
||||
expect(splitSearchMatchSegments("SELECT 1", "")).toEqual([{ text: "SELECT 1", matched: false }]);
|
||||
});
|
||||
|
||||
it("handles text without matches", () => {
|
||||
expect(splitSearchMatchSegments("SELECT 1", "from")).toEqual([{ text: "SELECT 1", matched: false }]);
|
||||
});
|
||||
|
||||
it("matches case-insensitively and preserves text casing", () => {
|
||||
const segments = splitSearchMatchSegments("Select user_id, userName From Users", "user");
|
||||
expect(segments).toEqual([
|
||||
{ text: "Select ", matched: false },
|
||||
{ text: "user", matched: true },
|
||||
{ text: "_id, ", matched: false },
|
||||
{ text: "user", matched: true },
|
||||
{ text: "Name From ", matched: false },
|
||||
{ text: "User", matched: true },
|
||||
{ text: "s", matched: false },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatSnippetLine", () => {
|
||||
it("keeps short line as trimmed", () => {
|
||||
expect(formatSnippetLine(" SELECT * FROM users; ", "users", 50)).toBe("SELECT * FROM users;");
|
||||
});
|
||||
|
||||
it("truncates long lines and centers context when match is deep", () => {
|
||||
const longLine = "SELECT a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, orders.id FROM very_long_table_name";
|
||||
const snippet = formatSnippetLine(longLine, "orders", 30);
|
||||
expect(snippet).toContain("orders");
|
||||
expect(snippet.startsWith("...")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("findSavedSqlSearchMatches", () => {
|
||||
it("returns empty result on empty sql or query", () => {
|
||||
expect(findSavedSqlSearchMatches("", "select")).toEqual({ matches: [], totalMatches: 0 });
|
||||
expect(findSavedSqlSearchMatches("SELECT 1", "")).toEqual({ matches: [], totalMatches: 0 });
|
||||
});
|
||||
|
||||
it("finds matching lines with 1-based line numbers and columns", () => {
|
||||
const sql = ["-- comments", "SELECT id, name", " FROM customers", " WHERE status = 'active';"].join("\n");
|
||||
|
||||
const result = findSavedSqlSearchMatches(sql, "from");
|
||||
expect(result.totalMatches).toBe(1);
|
||||
expect(result.matches).toHaveLength(1);
|
||||
|
||||
const match = result.matches[0];
|
||||
expect(match.lineNumber).toBe(3);
|
||||
// original line has 2 spaces before FROM, so column is 3
|
||||
expect(match.column).toBe(3);
|
||||
expect(match.lineText).toBe("FROM customers");
|
||||
expect(match.contextBefore).toEqual({ lineNumber: 2, text: "SELECT id, name" });
|
||||
expect(match.contextAfter).toEqual({ lineNumber: 4, text: "WHERE status = 'active';" });
|
||||
expect(match.segments).toEqual([
|
||||
{ text: "FROM", matched: true },
|
||||
{ text: " customers", matched: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("respects maxMatches while maintaining totalMatches", () => {
|
||||
const sql = ["SELECT 1;", "SELECT 2;", "SELECT 3;", "SELECT 4;", "SELECT 5;"].join("\n");
|
||||
|
||||
const result = findSavedSqlSearchMatches(sql, "select", { maxMatches: 2 });
|
||||
expect(result.totalMatches).toBe(5);
|
||||
expect(result.matches).toHaveLength(2);
|
||||
expect(result.matches.map((m) => m.lineNumber)).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMatchTooltip", () => {
|
||||
it("formats context before, match line, and context after with line numbers", () => {
|
||||
const tooltip = formatMatchTooltip({
|
||||
lineNumber: 10,
|
||||
column: 1,
|
||||
lineText: "SELECT * FROM orders",
|
||||
segments: [],
|
||||
contextBefore: { lineNumber: 9, text: "-- Fetch active orders" },
|
||||
contextAfter: { lineNumber: 11, text: "WHERE status = 'active'" },
|
||||
});
|
||||
|
||||
expect(tooltip).toBe("9 | -- Fetch active orders\n10 | SELECT * FROM orders\n11 | WHERE status = 'active'");
|
||||
});
|
||||
|
||||
it("handles missing context lines gracefully", () => {
|
||||
const tooltip = formatMatchTooltip({
|
||||
lineNumber: 1,
|
||||
column: 1,
|
||||
lineText: "SELECT 1;",
|
||||
segments: [],
|
||||
});
|
||||
|
||||
expect(tooltip).toBe("1 | SELECT 1;");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
export interface SavedSqlMatchSegment {
|
||||
text: string;
|
||||
matched: boolean;
|
||||
}
|
||||
|
||||
export interface SavedSqlLineMatch {
|
||||
lineNumber: number;
|
||||
column: number;
|
||||
lineText: string;
|
||||
segments: SavedSqlMatchSegment[];
|
||||
contextBefore?: { lineNumber: number; text: string };
|
||||
contextAfter?: { lineNumber: number; text: string };
|
||||
}
|
||||
|
||||
export interface SavedSqlSearchMatchResult {
|
||||
matches: SavedSqlLineMatch[];
|
||||
totalMatches: number;
|
||||
}
|
||||
|
||||
export interface FindSavedSqlSearchMatchesOptions {
|
||||
maxMatches?: number;
|
||||
maxLineLength?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits text into matched and unmatched segments based on case-insensitive query matching.
|
||||
* Preserves the original character casing from the input text.
|
||||
*/
|
||||
export function splitSearchMatchSegments(text: string, query: string): SavedSqlMatchSegment[] {
|
||||
if (!text || !query) return text ? [{ text, matched: false }] : [];
|
||||
const lowerText = text.toLowerCase();
|
||||
const lowerQuery = query.toLowerCase();
|
||||
const segments: SavedSqlMatchSegment[] = [];
|
||||
let cursor = 0;
|
||||
|
||||
while (cursor < text.length) {
|
||||
const matchIndex = lowerText.indexOf(lowerQuery, cursor);
|
||||
if (matchIndex < 0) {
|
||||
segments.push({ text: text.slice(cursor), matched: false });
|
||||
break;
|
||||
}
|
||||
if (matchIndex > cursor) {
|
||||
segments.push({ text: text.slice(cursor, matchIndex), matched: false });
|
||||
}
|
||||
segments.push({
|
||||
text: text.slice(matchIndex, matchIndex + query.length),
|
||||
matched: true,
|
||||
});
|
||||
cursor = matchIndex + query.length;
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncates a line around the first match occurrence if it exceeds maxLineLength,
|
||||
* prepending/appending ellipsis when truncated.
|
||||
*/
|
||||
export function formatSnippetLine(line: string, query: string, maxLineLength = 100): string {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length <= maxLineLength) return trimmed;
|
||||
|
||||
const lowerTrimmed = trimmed.toLowerCase();
|
||||
const lowerQuery = query.toLowerCase();
|
||||
const matchIndex = lowerTrimmed.indexOf(lowerQuery);
|
||||
if (matchIndex < 0) {
|
||||
return `${trimmed.slice(0, maxLineLength)}...`;
|
||||
}
|
||||
|
||||
// Keep some context characters before and after the match
|
||||
const leadContext = 20;
|
||||
if (matchIndex <= leadContext + 5) {
|
||||
return `${trimmed.slice(0, maxLineLength)}...`;
|
||||
}
|
||||
|
||||
const start = Math.max(0, matchIndex - leadContext);
|
||||
const end = Math.min(trimmed.length, start + maxLineLength);
|
||||
const prefix = start > 0 ? "..." : "";
|
||||
const suffix = end < trimmed.length ? "..." : "";
|
||||
return `${prefix}${trimmed.slice(start, end)}${suffix}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches SQL text for lines matching the query, returning snippets and context lines.
|
||||
*/
|
||||
export function findSavedSqlSearchMatches(sql: string, query: string, options: FindSavedSqlSearchMatchesOptions = {}): SavedSqlSearchMatchResult {
|
||||
const trimmedQuery = query.trim();
|
||||
if (!sql || !trimmedQuery) {
|
||||
return { matches: [], totalMatches: 0 };
|
||||
}
|
||||
|
||||
const maxMatches = options.maxMatches ?? 3;
|
||||
const maxLineLength = options.maxLineLength ?? 100;
|
||||
const lines = sql.split(/\r?\n/);
|
||||
const lowerQuery = trimmedQuery.toLowerCase();
|
||||
const matches: SavedSqlLineMatch[] = [];
|
||||
let totalMatches = 0;
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const rawLine = lines[i];
|
||||
const lowerLine = rawLine.toLowerCase();
|
||||
const matchCol = lowerLine.indexOf(lowerQuery);
|
||||
if (matchCol >= 0) {
|
||||
totalMatches++;
|
||||
if (matches.length < maxMatches) {
|
||||
const snippetText = formatSnippetLine(rawLine, trimmedQuery, maxLineLength);
|
||||
const segments = splitSearchMatchSegments(snippetText, trimmedQuery);
|
||||
|
||||
const contextBefore = i > 0 && lines[i - 1].trim() ? { lineNumber: i, text: lines[i - 1].trim() } : undefined;
|
||||
const contextAfter = i < lines.length - 1 && lines[i + 1].trim() ? { lineNumber: i + 2, text: lines[i + 1].trim() } : undefined;
|
||||
|
||||
matches.push({
|
||||
lineNumber: i + 1,
|
||||
column: matchCol + 1,
|
||||
lineText: snippetText,
|
||||
segments,
|
||||
contextBefore,
|
||||
contextAfter,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { matches, totalMatches };
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a 3-line code context snippet for hover tooltips.
|
||||
*/
|
||||
export function formatMatchTooltip(match: SavedSqlLineMatch): string {
|
||||
const parts: string[] = [];
|
||||
if (match.contextBefore) {
|
||||
parts.push(`${match.contextBefore.lineNumber} | ${match.contextBefore.text}`);
|
||||
}
|
||||
parts.push(`${match.lineNumber} | ${match.lineText}`);
|
||||
if (match.contextAfter) {
|
||||
parts.push(`${match.contextAfter.lineNumber} | ${match.contextAfter.text}`);
|
||||
}
|
||||
return parts.join("\n");
|
||||
}
|
||||
Reference in new issue
Block a user