Skip to content

Commit

Permalink
Automatically strip out any comments in SQL templates (#60)
Browse files Browse the repository at this point in the history
* Strip comments from sql template strings

* Added SQL with comments unit tests
  • Loading branch information
NuroDev authored Feb 21, 2025
1 parent 8b16bbc commit 1022684
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/queries/statements.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { Statement } from '@ronin/compiler';

const MULTILINE_SQL_COMMENTS = /\/\*[\s\S]*?\*\//g;
const SINGLELINE_SQL_COMMENTS = /--[^\n]*\n/g;

/**
* Used to track whether SQL queries are run in batches.
*/
Expand All @@ -21,7 +24,12 @@ export const getSyntaxProxySQL = (options: {
const params: Array<unknown> = [];

strings.forEach((string, i) => {
text += string;
// Remove comments but preserve the newline
const processedString = string
.replace(MULTILINE_SQL_COMMENTS, '')
.replace(SINGLELINE_SQL_COMMENTS, '\n');

text += processedString;

if (i < values.length) {
text += `$${i + 1}`;
Expand Down
46 changes: 45 additions & 1 deletion tests/queries/statements.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { expect, spyOn, test } from 'bun:test';
import { describe, expect, spyOn, test } from 'bun:test';
import { getBatchProxySQL, getSyntaxProxySQL } from '@/src/queries';
import type { Statement } from '@ronin/compiler';
import { expectTypeOf } from 'expect-type';
Expand Down Expand Up @@ -70,3 +70,47 @@ test('using raw SQL with multiple lines', async () => {
params: ['elaine'],
});
});

describe('using raw SQL with comments', () => {
test('--', async () => {
let statement: Statement | undefined;

const sqlProxy = getSyntaxProxySQL({
callback: (value) => {
statement = value;
},
});

const accountHandle = 'elaine';
sqlProxy`
-- Select all accounts with the given handle:
SELECT * FROM accounts WHERE handle = ${accountHandle}
`;

expect(statement).toMatchObject({
statement: 'SELECT * FROM accounts WHERE handle = $1',
params: ['elaine'],
});
});

test('/* ... */', async () => {
let statement: Statement | undefined;

const sqlProxy = getSyntaxProxySQL({
callback: (value) => {
statement = value;
},
});

const accountHandle = 'elaine';
sqlProxy`
/* Select all accounts with the given handle */
SELECT * FROM accounts WHERE handle = ${accountHandle}
`;

expect(statement).toMatchObject({
statement: 'SELECT * FROM accounts WHERE handle = $1',
params: ['elaine'],
});
});
});

0 comments on commit 1022684

Please sign in to comment.