Skip to content

Commit

Permalink
add test for raw with placeholders
Browse files Browse the repository at this point in the history
  • Loading branch information
invisal committed Nov 21, 2024
1 parent 9cbefa7 commit 386f758
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/connections/sql-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,11 @@ export abstract class SqlConnection extends Connection {
}

// Named placeholder
const { query: newQuery, bindings } = namedPlaceholder(query, params!);
const { query: newQuery, bindings } = namedPlaceholder(
query,
params!,
this.numberedPlaceholder
);
return await this.internalQuery({
query: newQuery,
parameters: bindings,
Expand Down
3 changes: 1 addition & 2 deletions src/utils/placeholder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ function parse(query: string): [string] | [string[], (string | number)[]] {
do {
for (i = curpos, end = ppos.index; i < end; ++i) {
let chr = query.charCodeAt(i);
console.log(i, query[i], inQuote, qchr);
if (chr === BSLASH) escape = !escape;
else {
if (escape) {
Expand Down Expand Up @@ -90,7 +89,7 @@ export function namedPlaceholder(
const key = placeholders[i];

if (numbered) {
newQuery += `$${key}`;
newQuery += `$${i + 1}`;
} else {
newQuery += `?`;
}
Expand Down
28 changes: 28 additions & 0 deletions tests/connections/connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,34 @@ function cleanup(data: Record<string, unknown>[]) {
}

describe('Database Connection', () => {
test('Support named parameters', async () => {
if (process.env.CONNECTION_TYPE === 'mongo') return;

const sql =
process.env.CONNECTION_TYPE === 'mysql'
? 'SELECT CONCAT(:hello, :world) AS testing_word'
: 'SELECT (:hello || :world) AS testing_word';

const { data } = await db.raw(sql, {
hello: 'hello ',
world: 'world',
});

expect(data).toEqual([{ testing_word: 'hello world' }]);
});

test('Support positional placeholder', async () => {
if (process.env.CONNECTION_TYPE === 'mongo') return;

const sql =
process.env.CONNECTION_TYPE === 'mysql'
? 'SELECT CONCAT(?, ?) AS testing_word'
: 'SELECT (? || ?) AS testing_word';

const { data } = await db.raw(sql, ['hello ', 'world']);
expect(data).toEqual([{ testing_word: 'hello world' }]);
});

test('Create table', async () => {
const { error: createTableTeamError } = await db.createTable(
DEFAULT_SCHEMA,
Expand Down

0 comments on commit 386f758

Please sign in to comment.