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
10 changes: 1 addition & 9 deletions src/embedSql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,5 @@ const isRoutine = (
isCreateFunctionStmt(node) || isCreateProcedureStmt(node);

const detectQuote = (node: StringLiteral): string | undefined => {
const match = node.text.match(/^('|\$[^$]*\$)/);
const quote = match?.[1];
if (quote === "'") {
// Convert `'` quotes to `$$`.
// But bail out if the code already contains $$.
return node.value.includes("$$") ? undefined : "$$";
} else {
return quote;
}
return node.text.match(/^\$[^$]*\$/)?.[0];
};
15 changes: 4 additions & 11 deletions src/formatBigqueryString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const formatBigqueryString = (
return async (
textToDoc: (text: string, options: Options) => Promise<Doc>,
) => {
const quotes = detectQuotes(node.value);
const quotes = detectQuotes(node.text);
if (!quotes) {
return undefined;
}
Expand All @@ -25,14 +25,7 @@ export const formatBigqueryString = (
};
};

// Whether to quote the code with single- or double-quotes.
// Returns undefined when neither can be used without escaping.
const detectQuotes = (code: string): [string, string] | undefined => {
Comment thread
nene marked this conversation as resolved.
Resolved
if (!/'''/.test(code)) {
return ["r'''", "'''"];
}
if (!/"""/.test(code)) {
return ['r"""', '"""'];
}
return undefined;
const detectQuotes = (text: string): [string, string] | undefined => {
const match = text.match(/^[rR]('''|""")/);
return match ? [match[0], match[1]] : undefined;
};
46 changes: 28 additions & 18 deletions test/embed/execute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,28 @@ describe("PL/pgSQL EXECUTE embedding", () => {
});

describe("BigQuery EXECUTE IMMEDIATE embedding", () => {
it("does not embed wrapped JSON with conflicting triple quotes", async () => {
const result = await pretty(
`EXECUTE IMMEDIATE r'''select JSON '{"message":"a long message that will force this JSON document to wrap","enabled":true}' '''`,
{ dialect: "bigquery", printWidth: 40 },
);
// embedJson can use ''' for wrapped JSON, closing the outer raw string.
expect(result).toBe(dedent`
EXECUTE IMMEDIATE
r'''
SELECT JSON '{"message":"a long message that will force this JSON document to wrap","enabled":true}';
'''
`);
await testBigquery(result, { printWidth: 40 });
});
it("formats a command with INTO and named parameters", async () => {
expect(
await pretty('EXECUTE IMMEDIATE "select @id" INTO result USING 1 AS id', {
dialect: "bigquery",
}),
await pretty(
"EXECUTE IMMEDIATE r'''select @id''' INTO result USING 1 AS id",
{
dialect: "bigquery",
},
),
).toBe(dedent`
EXECUTE IMMEDIATE
r'''
Expand All @@ -113,7 +130,7 @@ describe("BigQuery EXECUTE IMMEDIATE embedding", () => {

it("preserves backslashes when quoting the formatted command", async () => {
expect(
await pretty(String.raw`EXECUTE IMMEDIATE r"select '\n'"`, {
await pretty(String.raw`EXECUTE IMMEDIATE r'''select '\n' '''`, {
dialect: "bigquery",
}),
).toBe(
Expand All @@ -126,28 +143,21 @@ describe("BigQuery EXECUTE IMMEDIATE embedding", () => {
);
});

it("uses double quotes when the command contains triple single quotes", async () => {
expect(
await pretty(`EXECUTE IMMEDIATE ${JSON.stringify(`select "'''"`)}`, {
dialect: "bigquery",
}),
).toBe(dedent`
it("preserves triple double quotes", async () => {
await testBigquery(dedent`
EXECUTE IMMEDIATE
r"""
SELECT "'''";
SELECT 'value';
"""
`);
});

it("preserves commands containing both triple-quote delimiters", async () => {
await testBigquery(
`EXECUTE IMMEDIATE ${JSON.stringify(`select "'''", '"""'`)}`,
);
});

it.each([
'EXECUTE IMMEDIATE "select @id"',
"EXECUTE IMMEDIATE r'select ?'",
"EXECUTE IMMEDIATE '''select 1'''",
'EXECUTE IMMEDIATE "select " || column_name',
'EXECUTE IMMEDIATE "unsupported SQL syntax"',
`EXECUTE IMMEDIATE r'''unsupported SQL syntax'''`,
])("preserves commands it cannot embed: %s", async (source) => {
await testBigquery(source);
});
Expand Down
32 changes: 17 additions & 15 deletions test/embed/language_js.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@ import dedent from "dedent-js";
import { pretty, testBigquery } from "../test_utils";

describe("LANGUAGE js", () => {
it.each(["'return 1'", '"return 1"', "'''return 1'''", "r'return 1'"])(
"preserves JavaScript in unsupported quote style: %s",
async (body) => {
await testBigquery(
dedent`
CREATE FUNCTION f()
RETURNS INT64
LANGUAGE js
AS ${body}
`,
);
},
);
it(`formats JavaScript FUNCTION`, async () => {
await testBigquery(dedent`
CREATE FUNCTION gen_random()
Expand All @@ -21,7 +34,7 @@ describe("LANGUAGE js", () => {
CREATE FUNCTION gen_random()
RETURNS FLOAT64
LANGUAGE js
AS ' if(true) {return Math.random () *2}'
AS r''' if(true) {return Math.random () *2}'''
`,
{ dialect: "bigquery" },
),
Expand All @@ -37,35 +50,24 @@ describe("LANGUAGE js", () => {
`);
});

it(`quotes JavaScript in double-quotes when single-quotes can't be used`, async () => {
it(`preserves raw double quotes and uppercase prefix`, async () => {
expect(
await pretty(
dedent`
CREATE FUNCTION contains_quotes(x STRING)
RETURNS FLOAT64
LANGUAGE js
AS " return /'''/.test(x) "
AS R""" return /'''/.test(x) """
Comment on lines -40 to +60

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

This R v/s r prefix is probably something we should standardize. But I think out of scope for this pull request.

Just a note for myself.

`,
{ dialect: "bigquery" },
),
).toBe(dedent`
CREATE FUNCTION contains_quotes(x STRING)
RETURNS FLOAT64
LANGUAGE js
AS r"""
AS R"""
return /'''/.test(x);
"""
`);
});

it(`does not reformat JavaScript when neither ''' or """ can be easily used for quoting`, async () => {
await testBigquery(
dedent`
CREATE FUNCTION contains_quotes(x STRING)
RETURNS FLOAT64
LANGUAGE js
AS " return /'''|\\"\\"\\"/.test(x) "
`,
);
});
});
29 changes: 4 additions & 25 deletions test/embed/language_plpgsql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,34 +30,13 @@ describe("LANGUAGE plpgsql", () => {
`);
});

it(`converts single-quoted string to dollar-quoted string`, async () => {
expect(
await pretty(
dedent`
it(`preserves single-quoted string`, async () => {
await testPostgresql(
dedent`
${code}
LANGUAGE plpgsql
AS 'BEGIN SELECT ''foo''; END'
AS 'BEGIN RETURN 1; END'
`,
{ dialect: "postgresql", sqlExperimentalPlpgsql: true },
),
).toBe(dedent`
${code}
LANGUAGE plpgsql
AS $$
BEGIN
SELECT 'foo';
END;
$$
`);
});

it(`does not reformat single-quoted SQL string when its source contains $$-quotes`, async () => {
await testPostgresql(
dedent`
${code}
LANGUAGE plpgsql
AS 'BEGIN SELECT $$foo$$; END'
`,
{ sqlExperimentalPlpgsql: true },
);
});
Expand Down
31 changes: 6 additions & 25 deletions test/embed/language_sql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,32 +30,13 @@ describe("LANGUAGE sql", () => {
`);
});

it(`converts single-quoted SQL string to dollar-quoted string`, async () => {
expect(
await pretty(
dedent`
it(`preserves single-quoted SQL string`, async () => {
await testPostgresql(
dedent`
${code}
LANGUAGE sql
AS 'SELECT ''foo'''
AS 'SELECT 1'
`,
{ dialect: "postgresql" },
),
).toBe(dedent`
${code}
LANGUAGE sql
AS $$
SELECT 'foo';
$$
`);
});

it(`does not reformat single-quoted SQL string when its source contains $$-quotes`, async () => {
await testPostgresql(
dedent`
${code}
LANGUAGE sql
AS 'SELECT $$foo$$'
`,
);
});

Expand All @@ -75,7 +56,7 @@ describe("LANGUAGE sql", () => {
dedent`
${code}
LANGUAGE Sql
AS 'SELECT 1'
AS $$SELECT 1$$
`,
{ dialect: "postgresql" },
),
Expand All @@ -94,7 +75,7 @@ describe("LANGUAGE sql", () => {
expect(
await pretty(
dedent`
DO LANGUAGE sql 'select 1'
DO LANGUAGE sql $$select 1$$
`,
{ dialect: "postgresql", sqlExperimentalPlpgsql: true },
),
Expand Down
Loading