diff --git a/cli/api/utils/query_transforms.ts b/cli/api/utils/query_transforms.ts index 0cc417a11..6e61841c3 100644 --- a/cli/api/utils/query_transforms.ts +++ b/cli/api/utils/query_transforms.ts @@ -1,27 +1,23 @@ -/** - * Whether the string or bytes literal opening quote (`'` or `"`) at `quoteIndex` is preceded by a - * GoogleSQL raw literal prefix (`r`, `rb` or `br`, case-insensitive). - */ -function hasRawLiteralPrefix(statement: string, quoteIndex: number): boolean { - const prefix = statement.slice(Math.max(0, quoteIndex - 3), quoteIndex); - return /(?:^|[^a-zA-Z0-9_])(?:r|rb|br)$/i.test(prefix); -} - /** * Returns `statement` with comments (`--`, `#` and `/* *\/`) and the contents of string/bytes * literals (single, double and triple quoted, including raw literals) and quoted identifiers * replaced with spaces of the same length. Preserving lengths keeps character indices aligned - * with `statement`, while leaving only unquoted SQL tokens and empty quotes. + * with `statement`, while leaving only unquoted SQL tokens and empty quotes. An unterminated + * literal runs to the end of the statement, and its last character is replaced with its quote + * character rather than a space, so that it still ends in code. + * + * Exported only for unit testing; not intended for use outside this file. */ -function stripCommentsAndQuotedContent(statement: string): string { +export function stripCommentsAndQuotedContent(statement: string): string { let result = ""; let i = 0; while (i < statement.length) { const char = statement[i]; const next = statement[i + 1]; if ((char === "-" && next === "-") || char === "#") { - const newline = statement.indexOf("\n", i); - const end = newline === -1 ? statement.length : newline; + // BigQuery also ends a line comment at a lone \r. + const newline = statement.slice(i).search(/[\r\n]/); + const end = newline === -1 ? statement.length : i + newline; result += " ".repeat(end - i); i = end; } else if (char === "/" && next === "*") { @@ -30,20 +26,26 @@ function stripCommentsAndQuotedContent(statement: string): string { result += " ".repeat(end - i); i = end; } else if (char === "'" || char === '"' || char === "`") { - const isRaw = char !== "`" && hasRawLiteralPrefix(statement, i); const tripleQuote = char.repeat(3); const closing = char !== "`" && statement.startsWith(tripleQuote, i) ? tripleQuote : char; const start = i; i += closing.length; while (i < statement.length && !statement.startsWith(closing, i)) { - // Skip escaped characters, e.g. \' inside a non-raw single-quoted string. - i += !isRaw && statement[i] === "\\" ? 2 : 1; + // A backslash keeps the next character from closing the literal, e.g. \' in 'it\'s'. This + // also applies to raw literals, where the backslash is kept: r'a\'' is the string a\'. + i += statement[i] === "\\" ? 2 : 1; + } + if (i < statement.length) { + i += closing.length; + result += closing + " ".repeat(i - start - 2 * closing.length) + closing; + } else { + // An unterminated literal runs to the end of the statement. It's replaced up to there, and + // ends with a quote rather than a space, so that it still counts as code (e.g. a statement + // terminator goes after it, not inside it). + const bodyLength = statement.length - start - closing.length; + i = statement.length; + result += closing + (bodyLength > 0 ? " ".repeat(bodyLength - 1) + char : ""); } - i = Math.min(i + closing.length, statement.length); - result += - closing + - " ".repeat(Math.max(0, i - start - 2 * closing.length)) + - (i - start >= 2 * closing.length ? closing : ""); } else { result += char; i++; diff --git a/cli/api/utils/query_transforms_test.ts b/cli/api/utils/query_transforms_test.ts index 6270638f3..a2a1b6f62 100644 --- a/cli/api/utils/query_transforms_test.ts +++ b/cli/api/utils/query_transforms_test.ts @@ -3,6 +3,7 @@ import { expect } from "chai"; import { concatenateQueries, setsDatasetId, + stripCommentsAndQuotedContent, terminateStatements, wrapWithCreateSchemaIfNotExists, } from "df/cli/api/utils/query_transforms"; @@ -66,18 +67,23 @@ suite("concatenateQueries", () => { expect(terminated("SELECT 'it\\'s -- x'")).equals("SELECT 'it\\'s -- x';\nSELECT 2"); }); - test("doesn't treat \\ as an escape inside raw string or bytes literals", () => { + test("treats \\ before a quote as part of raw string and bytes literals, like BigQuery", () => { + // In raw literals the backslash is kept, but it still keeps the next quote from closing the + // literal: r'a\'' is the string a\', and r'\' is unterminated. const terminated = (statement: string) => concatenateQueries([statement, "SELECT 2"]); - expect(terminated("SELECT r'\\' -- comment")).equals("SELECT r'\\'; -- comment\nSELECT 2"); - expect(terminated("SELECT REPLACE(p, r'\\', '/'), 'ok' -- don't fail")).equals( - "SELECT REPLACE(p, r'\\', '/'), 'ok'; -- don't fail\nSELECT 2", + expect(terminated("SELECT r'a\\'' -- comment")).equals("SELECT r'a\\''; -- comment\nSELECT 2"); + expect(terminated("SELECT REPLACE('p', r'\\\\', '/'), 'ok' -- don't fail")).equals( + "SELECT REPLACE('p', r'\\\\', '/'), 'ok'; -- don't fail\nSELECT 2", ); - expect(terminated('R"\\" -- comment')).equals('R"\\"; -- comment\nSELECT 2'); - expect(terminated("SELECT r'''a\\''' -- comment")).equals( - "SELECT r'''a\\'''; -- comment\nSELECT 2", + expect(terminated('SELECT R"a\\"b" -- comment')).equals( + 'SELECT R"a\\"b"; -- comment\nSELECT 2', ); - expect(terminated("SELECT rb'\\' -- comment")).equals("SELECT rb'\\'; -- comment\nSELECT 2"); - expect(terminated('SELECT BR"\\" -- comment')).equals('SELECT BR"\\"; -- comment\nSELECT 2'); + expect(terminated("SELECT r'''a\\'''' -- comment")).equals( + "SELECT r'''a\\''''; -- comment\nSELECT 2", + ); + expect(terminated("SELECT rb'\\'' -- comment")).equals("SELECT rb'\\''; -- comment\nSELECT 2"); + expect(terminated('SELECT BR"\\"" -- comment')).equals('SELECT BR"\\""; -- comment\nSELECT 2'); + expect(terminated("SELECT r'\\\\' -- comment")).equals("SELECT r'\\\\'; -- comment\nSELECT 2"); // Non-raw `b` prefix and SQL keywords ending in `r` still escape quotes with `\`. expect(terminated("SELECT b'it\\'s -- x'")).equals("SELECT b'it\\'s -- x';\nSELECT 2"); expect(terminated("SELECT flag OR'it\\'s -- x'")).equals( @@ -174,8 +180,10 @@ suite("wrapWithCreateSchemaIfNotExists", () => { }); test("terminates a raw string ending in a backslash before a trailing comment", () => { - expect(wrapWithCreateSchemaIfNotExists("project", "dataset", "SELECT r'\\' -- comment")).equals( - "create schema if not exists `project.dataset`;\nbegin\nSELECT r'\\'; -- comment\nend;", + expect( + wrapWithCreateSchemaIfNotExists("project", "dataset", "SELECT r'\\\\' -- comment"), + ).equals( + "create schema if not exists `project.dataset`;\nbegin\nSELECT r'\\\\'; -- comment\nend;", ); }); @@ -213,9 +221,9 @@ suite("setsDatasetId", () => { expect(setsDatasetId("SELECT 'SET @@dataset_id = \"my_ds\"'")).equals(false); expect(setsDatasetId("SELECT \"SET @@dataset_id = 'my_ds'\"")).equals(false); expect(setsDatasetId("SELECT '''\nSET @@dataset_id = 'my_ds'\n'''")).equals(false); - expect(setsDatasetId("SELECT r'\\' -- not a comment\n, 'SET @@dataset_id = \"my_ds\"'")).equals( - false, - ); + expect( + setsDatasetId("SELECT r'a\\'' -- not a comment\n, 'SET @@dataset_id = \"my_ds\"'"), + ).equals(false); expect(setsDatasetId("SELECT * FROM `SET @@dataset_id = 'my_ds'`")).equals(false); }); @@ -243,3 +251,41 @@ suite("terminateStatements", () => { expect(terminateStatements([])).equals(""); }); }); + +suite("stripCommentsAndQuotedContent", () => { + test("keeps a semicolon after a raw string with an escaped quote", () => { + // r'a\'' is one literal, so the semicolon after it is code, and the next ' opens a literal. + expect(stripCommentsAndQuotedContent("SELECT r'a\\'' AS s; SELECT 'b'")).equals( + "SELECT r' ' AS s; SELECT ' '", + ); + }); + + test("keeps the length of unterminated literals", () => { + for (const statement of [ + "SELECT '''a", + "SELECT 'a", + "SELECT `a", + "SELECT r'\\", + "SELECT 'a\\", + ]) { + expect(stripCommentsAndQuotedContent(statement).length).equals(statement.length); + } + }); +}); + +suite("query transforms on unterminated literals and lone \\r", () => { + test("puts the terminator after an unterminated literal, not inside it", () => { + expect(concatenateQueries(["SELECT 'abc", "SELECT 2"])).equals("SELECT 'abc;\nSELECT 2"); + expect(concatenateQueries(["SELECT r'\\", "SELECT 2"])).equals("SELECT r'\\;\nSELECT 2"); + expect(wrapWithCreateSchemaIfNotExists("p", "d", "SELECT 'abc def")).equals( + "create schema if not exists `p.d`;\nbegin\nSELECT 'abc def;\nend;", + ); + }); + + test("ends a line comment at a lone \\r, like BigQuery", () => { + expect(concatenateQueries(["SELECT 1 -- c\rFROM x", "SELECT 2"])).equals( + "SELECT 1 -- c\rFROM x;\nSELECT 2", + ); + expect(setsDatasetId("SELECT 1 # c\rSET @@dataset_id = 'd'")).equals(true); + }); +});