diff --git a/src/features/database/results-view.test.tsx b/src/features/database/results-view.test.tsx index d27cdd01f0..80fb9254fe 100644 --- a/src/features/database/results-view.test.tsx +++ b/src/features/database/results-view.test.tsx @@ -646,6 +646,76 @@ describe("unsubmitted edits of a result", () => { }); }); +describe("counting the rows of a result", () => { + /** The server's error for each rejected count query, else 1600 rows. */ + const rejected = new Map(); + beforeEach(() => { + rejected.clear(); + backend.execute.mockImplementation((_r: unknown, _id: unknown, statements: Array<{ text: string }>) => { + const st = statements[0]!; + const error = rejected.get(st.text) ?? null; + const counted = { ...result([{ name: "" }], [["1600"]]), statement: st.text }; + return Promise.resolve({ status: "ok", data: [{ statement: st, result: error ? null : counted, error }] }); + }); + }); + + // Each count query was run on SQL Server (Azure SQL Edge), which gave these errors for the plain wrapper. + const orderBy = + "[1033] The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified."; + it.each([ + ["SELECT a FROM t ORDER BY a", "select count(*) from (\nSELECT a FROM t\n) q", orderBy], + [ + "SELECT a FROM t UNION SELECT a FROM u ORDER BY 1 DESC", + "select count(*) from (\nSELECT a FROM t UNION SELECT a FROM u\n) q", + orderBy, + ], + [ + "WITH x AS (SELECT a FROM t), y (n) AS (SELECT 1)\nSELECT a FROM x CROSS JOIN y ORDER BY a", + "WITH x AS (SELECT a FROM t), y (n) AS (SELECT 1)\nselect count(*) from (\nSELECT a FROM x CROSS JOIN y\n) q", + "[156] Incorrect syntax near the keyword 'WITH'.", + ], + [ + "SELECT a FROM t ORDER BY a OPTION (MAXDOP 1)", + "select count(*) from (\nSELECT a FROM t\n) q OPTION (MAXDOP 1)", + "[156] Incorrect syntax near the keyword 'OPTION'.", + ], + // TOP and OFFSET … FETCH keep the ORDER BY that picks their rows; one in parentheses is a subquery's. + [ + "SELECT TOP 2 a FROM t ORDER BY a DESC", + "select count(*) from (\nSELECT TOP 2 a FROM t ORDER BY a DESC\n) q", + null, + ], + [ + "SELECT a FROM t ORDER BY a OFFSET 1 ROWS FETCH NEXT 5 ROWS ONLY", + "select count(*) from (\nSELECT a FROM t ORDER BY a OFFSET 1 ROWS FETCH NEXT 5 ROWS ONLY\n) q", + null, + ], + [ + "SELECT a FROM t WHERE a IN (SELECT TOP 1 a FROM u ORDER BY a)", + "select count(*) from (\nSELECT a FROM t WHERE a IN (SELECT TOP 1 a FROM u ORDER BY a)\n) q", + null, + ], + ])("counts SQL Server's %s", async (text, sent, error) => { + backend.driver = "sqlServer"; + if (error) rejected.set(`select count(*) from (\n${text}\n) q`, error); + const tab = show(text, [{ name: "a" }], [["1"]]); + expect(await countResult(tab.id)).toBe(1600); + expect(useDatabase.getState().results[0]?.total).toBe(1600); + expect(backend.execute.mock.lastCall?.[2]).toEqual([{ from: 0, to: sent.length, text: sent }]); + }); + + it.each(["postgres", "mysql", "sqlite", "oracle", "snowflake", "clickhouse", "jdbc"] as const)( + "counts %s's query as it is written", + async (driver) => { + backend.driver = driver; + const text = "WITH x AS (SELECT a FROM t) SELECT a FROM x ORDER BY a"; + const tab = show(text, [{ name: "a" }], [["1"]]); + expect(await countResult(tab.id)).toBe(1600); + expect(backend.execute.mock.lastCall?.[2]?.[0]?.text).toBe(`select count(*) from (\n${text}\n) q`); + }, + ); +}); + describe("read-only results with a reason", () => { it.each([ ["SELECT * FROM a JOIN b ON a.id = b.id", [{ name: "id" }], [["1"]], "Read-only: the query joins several tables."], diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 352b45e312..8c3a932a37 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -70,7 +70,7 @@ import type { DbObjectRef } from "./objects"; import type { SqlCatalog } from "./sql/complete"; import { nameMatcher, sqlDriverOf } from "./sql/dialect"; import { formatted } from "./sql/format"; -import { lex } from "./sql/lexer"; +import { lex, type Token } from "./sql/lexer"; import { bindParams, findParams, unbindRange } from "./sql/params"; import { unsafeStatement, type UnsafeStatement } from "./sql/unsafe"; import { isReadOnlyQuery } from "./sql/readOnly"; @@ -2589,22 +2589,59 @@ export async function loadResultPage(tabId: number, page: number, pageSize: numb } /** `SELECT COUNT(*)` over a query, for queries that can be a subquery. */ -function countQuery(text: string): string | null { +function countQuery(text: string, driver: DbDriver): string | null { if (!/^\s*(\(|select\b|with\b|values\b|table\b)/i.test(text)) return null; + const query = text.trim(); + const { lead, counted, tail } = + driver === "sqlServer" ? sqlServerCount(query) : { lead: "", counted: query, tail: "" }; // `)` on its own line: a trailing line comment (`… from t -- note`) would swallow it. - return `select count(*) from (\n${text.trim()}\n) q`; + return `${lead}select count(*) from (\n${counted}\n) q${tail}`; } +/** + * What of SQL Server `query` goes before and after the derived table that counts it, which can hold + * neither a leading WITH (CTEs start a statement) nor an OPTION clause (it ends one), nor an ORDER BY + * without TOP, OFFSET or FOR XML / JSON (error 1033); such an ORDER BY does not change the count. + */ +function sqlServerCount(query: string): { lead: string; counted: string; tail: string } { + const outer: Token[] = []; + let depth = 0; + for (const t of lex(query, "sqlServer").tokens) { + if (t.text === ")") depth = Math.max(0, depth - 1); + else if (depth === 0) outer.push(t); + if (t.text === "(") depth++; + } + const is = (t: Token | undefined, word: string) => t?.kind === "word" && t.upper === word; + const select = is(outer[0], "WITH") ? outer.findIndex((t) => is(t, "SELECT")) : -1; + const main = select > 0 ? outer.slice(select) : outer; + const from = select > 0 ? main[0]!.from : 0; + const option = main.find((t) => is(t, "OPTION")); + const order = main.findIndex((t, i) => is(t, "ORDER") && is(main[i + 1], "BY")); + const sorted = order < 0 ? [] : main.slice(order); + // Valid with TOP, OFFSET … FETCH or FOR XML / JSON, which take or lay out rows in that order. + const keepOrder = + main.some((t) => is(t, "TOP")) || + sorted.some((t, i) => is(t, "OFFSET") || (is(t, "FOR") && ["XML", "JSON"].some((w) => is(sorted[i + 1], w)))); + const end = order >= 0 && !keepOrder ? main[order]!.from : (option?.from ?? query.length); + return { + lead: query.slice(0, from), + counted: query.slice(from, end).trimEnd(), + tail: option ? ` ${query.slice(option.from)}` : "", + }; +} + +const resultDriver = (tab: ResultTab): DbDriver => sourceById(tab.sourceId)?.driver ?? "sqlite"; + /** Whether the rows of result tab `tab` can be counted. */ export function countable(tab: ResultTab): boolean { - return pageable(tab) && countQuery(tab.outcome.statement.text) !== null; + return pageable(tab) && countQuery(tab.outcome.statement.text, resultDriver(tab)) !== null; } /** Counts the rows of result tab `tabId`'s whole query (the pager's "of 501+"). */ export async function countResult(tabId: number): Promise { const tab = findResult(tabId); if (!tab || tab.busy || !countable(tab)) return null; - const text = countQuery(tab.outcome.statement.text)!; + const text = countQuery(tab.outcome.statement.text, resultDriver(tab))!; patchResult(tabId, { busy: true }); try { const [outcome] = await run(