From 397b8607f49c9e08bc10cb765dc7a9f9d7b432dc Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 19 May 2026 16:08:11 +0800 Subject: [PATCH] fix(sqlserver): strip order by when wrapping queries --- apps/desktop/src/lib/queryResultPagination.ts | 9 +- apps/desktop/src/lib/queryResultSort.ts | 4 +- .../desktop/src/lib/sqlServerQueryWrapping.ts | 130 ++++++++++++++++++ .../app-tests/queryResultPagination.test.ts | 30 ++++ packages/app-tests/queryResultSort.test.ts | 15 ++ 5 files changed, 184 insertions(+), 4 deletions(-) create mode 100644 apps/desktop/src/lib/sqlServerQueryWrapping.ts diff --git a/apps/desktop/src/lib/queryResultPagination.ts b/apps/desktop/src/lib/queryResultPagination.ts index 914e806dd..69881cb62 100644 --- a/apps/desktop/src/lib/queryResultPagination.ts +++ b/apps/desktop/src/lib/queryResultPagination.ts @@ -2,6 +2,7 @@ import type { DatabaseType } from "../types/database.ts"; import { usesFetchFirst } from "./databaseCapabilities.ts"; import { quoteTableIdentifier } from "./tableSelectSql.ts"; import { findStatementAtCursor } from "./sqlStatementSplit.ts"; +import { sqlServerStatementForDerivedTable } from "./sqlServerQueryWrapping.ts"; export interface PaginatedQuerySqlResult { ok: true; @@ -84,13 +85,14 @@ export function buildPaginatedQuerySql( const safeLimit = Math.max(1, Math.floor(limit)); const safeOffset = Math.max(0, Math.floor(offset)); const alias = quoteTableIdentifier(databaseType, "dbx_page"); - const base = `SELECT * FROM (${statement.sql}) ${alias}`; + const wrappedSql = databaseType === "sqlserver" ? sqlServerStatementForDerivedTable(statement.sql) : statement.sql; + const base = `SELECT * FROM (${wrappedSql}) ${alias}`; if (databaseType === "sqlserver") { if (safeOffset > 0) return { ok: false, reason: "unsupported" }; return { ok: true, - sql: `SELECT TOP (${safeLimit}) * FROM (${statement.sql}) ${alias}`, + sql: `SELECT TOP (${safeLimit}) * FROM (${wrappedSql}) ${alias}`, }; } @@ -112,7 +114,8 @@ export function buildCountQuerySql( if (unsupportedPaginationTypes.has(databaseType)) return { ok: false, reason: "unsupported" }; const alias = quoteTableIdentifier(databaseType, "dbx_count"); - return { ok: true, sql: `SELECT COUNT(*) AS dbx_total_rows FROM (${statement.sql}) ${alias};` }; + const wrappedSql = databaseType === "sqlserver" ? sqlServerStatementForDerivedTable(statement.sql) : statement.sql; + return { ok: true, sql: `SELECT COUNT(*) AS dbx_total_rows FROM (${wrappedSql}) ${alias};` }; } function singleSelectableStatement( diff --git a/apps/desktop/src/lib/queryResultSort.ts b/apps/desktop/src/lib/queryResultSort.ts index 8934f2696..ad0bcdde6 100644 --- a/apps/desktop/src/lib/queryResultSort.ts +++ b/apps/desktop/src/lib/queryResultSort.ts @@ -1,6 +1,7 @@ import type { DatabaseType } from "../types/database.ts"; import { quoteTableIdentifier } from "./tableSelectSql.ts"; import { findStatementAtCursor } from "./sqlStatementSplit.ts"; +import { sqlServerStatementForDerivedTable } from "./sqlServerQueryWrapping.ts"; export type QuerySortDirection = "asc" | "desc"; @@ -44,9 +45,10 @@ export function buildSortedQuerySql( const sortAlias = aliases[columnIndex] ?? aliases[resultColumns.indexOf(column)] ?? fallbackAlias(columnIndex); const quotedColumn = quoteTableIdentifier(databaseType, sortAlias); const aliasList = aliases.map((alias) => quoteTableIdentifier(databaseType, alias)).join(", "); + const wrappedStatement = databaseType === "sqlserver" ? sqlServerStatementForDerivedTable(statement) : statement; return { ok: true, - sql: `SELECT * FROM (${statement}) t(${aliasList}) ORDER BY ${quotedColumn} ${direction.toUpperCase()};`, + sql: `SELECT * FROM (${wrappedStatement}) t(${aliasList}) ORDER BY ${quotedColumn} ${direction.toUpperCase()};`, }; } diff --git a/apps/desktop/src/lib/sqlServerQueryWrapping.ts b/apps/desktop/src/lib/sqlServerQueryWrapping.ts new file mode 100644 index 000000000..71c28307c --- /dev/null +++ b/apps/desktop/src/lib/sqlServerQueryWrapping.ts @@ -0,0 +1,130 @@ +export function sqlServerStatementForDerivedTable(statement: string): string { + const orderBy = findTopLevelTrailingOrderBy(statement); + if (orderBy === undefined) return statement; + if (hasTopLevelSelectTop(statement) || hasTopLevelForXml(statement)) return statement; + return statement.slice(0, orderBy).trimEnd(); +} + +function findTopLevelTrailingOrderBy(sql: string): number | undefined { + const tokens = topLevelSqlTokens(sql); + for (let i = tokens.length - 2; i >= 0; i--) { + if (tokens[i].text === "ORDER" && tokens[i + 1]?.text === "BY") { + return tokens[i].start; + } + } + return undefined; +} + +function hasTopLevelSelectTop(sql: string): boolean { + const tokens = topLevelSqlTokens(sql); + const selectIndex = tokens.findIndex((token) => token.text === "SELECT"); + if (selectIndex < 0) return false; + const fromIndex = tokens.findIndex((token, index) => index > selectIndex && token.text === "FROM"); + const end = fromIndex < 0 ? tokens.length : fromIndex; + return tokens.slice(selectIndex + 1, end).some((token) => token.text === "TOP"); +} + +function hasTopLevelForXml(sql: string): boolean { + const tokens = topLevelSqlTokens(sql); + return tokens.some((token, index) => token.text === "FOR" && tokens[index + 1]?.text === "XML"); +} + +function topLevelSqlTokens(sql: string): Array<{ text: string; start: number }> { + const tokens: Array<{ text: string; start: number }> = []; + let i = 0; + let depth = 0; + + while (i < sql.length) { + const ch = sql[i]; + const next = sql[i + 1]; + + if (ch === "-" && next === "-") { + i += 2; + while (i < sql.length && sql[i] !== "\n") i++; + continue; + } + + if (ch === "/" && next === "*") { + i += 2; + while (i < sql.length - 1 && !(sql[i] === "*" && sql[i + 1] === "/")) i++; + i = Math.min(i + 2, sql.length); + continue; + } + + if (ch === "'" || ch === '"' || ch === "`") { + i = skipSqlQuoted(sql, i, ch); + continue; + } + + if (ch === "[") { + i = skipSqlBracketIdentifier(sql, i); + continue; + } + + if (ch === "(") { + depth++; + i++; + continue; + } + + if (ch === ")") { + depth = Math.max(0, depth - 1); + i++; + continue; + } + + if (depth === 0 && isSqlTokenStart(ch)) { + const start = i; + i++; + while (i < sql.length && isSqlTokenPart(sql[i])) i++; + tokens.push({ text: sql.slice(start, i).toUpperCase(), start }); + continue; + } + + i++; + } + + return tokens; +} + +function skipSqlQuoted(sql: string, pos: number, quote: string): number { + let i = pos + 1; + while (i < sql.length) { + if (sql[i] === quote) { + if (sql[i + 1] === quote) { + i += 2; + continue; + } + return i + 1; + } + if (quote === "'" && sql[i] === "\\") { + i += 2; + continue; + } + i++; + } + return sql.length; +} + +function skipSqlBracketIdentifier(sql: string, pos: number): number { + let i = pos + 1; + while (i < sql.length) { + if (sql[i] === "]") { + if (sql[i + 1] === "]") { + i += 2; + continue; + } + return i + 1; + } + i++; + } + return sql.length; +} + +function isSqlTokenStart(ch: string | undefined): boolean { + return !!ch && /[A-Za-z_]/.test(ch); +} + +function isSqlTokenPart(ch: string | undefined): boolean { + return !!ch && /[A-Za-z0-9_$#]/.test(ch); +} diff --git a/packages/app-tests/queryResultPagination.test.ts b/packages/app-tests/queryResultPagination.test.ts index 86c91ec96..af9ea8c1f 100644 --- a/packages/app-tests/queryResultPagination.test.ts +++ b/packages/app-tests/queryResultPagination.test.ts @@ -33,6 +33,15 @@ test("uses SQL Server TOP pagination for the first page to support SQL Server 20 }); }); +test("strips top-level SQL Server order by before wrapping paginated query", () => { + const result = buildPaginatedQuerySql("SELECT id FROM users ORDER BY id DESC", "sqlserver", 100, 0); + + assert.deepEqual(result, { + ok: true, + sql: "SELECT TOP (100) * FROM (SELECT id FROM users) [dbx_page]", + }); +}); + test("does not generate SQL Server OFFSET pagination for later query-result pages", () => { const result = buildPaginatedQuerySql("SELECT id FROM users", "sqlserver", 100, 300); @@ -92,6 +101,27 @@ test("wraps a single select query for total row count", () => { }); }); +test("strips top-level SQL Server order by before wrapping count query", () => { + const result = buildCountQuerySql("SELECT id FROM users ORDER BY id DESC", "sqlserver"); + + assert.deepEqual(result, { + ok: true, + sql: "SELECT COUNT(*) AS dbx_total_rows FROM (SELECT id FROM users) [dbx_count];", + }); +}); + +test("keeps nested SQL Server order by expressions when wrapping count query", () => { + const result = buildCountQuerySql( + "SELECT ROW_NUMBER() OVER (ORDER BY created_at DESC) AS rn, id FROM users ORDER BY id DESC", + "sqlserver", + ); + + assert.deepEqual(result, { + ok: true, + sql: "SELECT COUNT(*) AS dbx_total_rows FROM (SELECT ROW_NUMBER() OVER (ORDER BY created_at DESC) AS rn, id FROM users) [dbx_count];", + }); +}); + test("uses MySQL style quoting for count query alias", () => { const result = buildCountQuerySql("WITH cte AS (SELECT 1 AS id) SELECT * FROM cte", "mysql"); diff --git a/packages/app-tests/queryResultSort.test.ts b/packages/app-tests/queryResultSort.test.ts index 40efb697d..8c2da36ce 100644 --- a/packages/app-tests/queryResultSort.test.ts +++ b/packages/app-tests/queryResultSort.test.ts @@ -33,6 +33,21 @@ test("assigns unique aliases for duplicate result column names", () => { }); }); +test("strips top-level SQL Server order by before wrapping result sort query", () => { + const result = buildSortedQuerySql( + "SELECT id, name FROM users ORDER BY id DESC", + "sqlserver", + ["id", "name"], + 1, + "name", + "asc", + ); + assert.deepEqual(result, { + ok: true, + sql: "SELECT * FROM (SELECT id, name FROM users) t([id], [name]) ORDER BY [name] ASC;", + }); +}); + test("rejects multiple statements for result sorting", () => { const result = buildSortedQuerySql("SELECT 1; SELECT 2;", "postgres", ["id"], 0, "id", "asc"); assert.deepEqual(result, { ok: false, reason: "multi" });