Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 23 additions & 21 deletions cli/api/utils/query_transforms.ts
Original file line number Diff line number Diff line change
@@ -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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): since this is exported only so it can be unit-tested, a short note in the doc comment saying so would discourage other callers from depending on it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in ece27fe. I added a note to the doc comment that it's exported only for unit testing.

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 === "*") {
Expand All @@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): the function's doc comment still says literal contents are replaced with spaces. With this branch an unterminated literal ends with a quote character instead. Now that the function is exported, it would help to say that in the doc comment as well, not only here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in ece27fe. The doc comment now says that an unterminated literal runs to the end of the statement, and that its last character is replaced with its quote character rather than a space, so it still ends in code.

// 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++;
Expand Down
74 changes: 60 additions & 14 deletions cli/api/utils/query_transforms_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { expect } from "chai";
import {
concatenateQueries,
setsDatasetId,
stripCommentsAndQuotedContent,
terminateStatements,
wrapWithCreateSchemaIfNotExists,
} from "df/cli/api/utils/query_transforms";
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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;",
);
});

Expand Down Expand Up @@ -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);
});

Expand Down Expand Up @@ -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);
});
});