From 386f75867e0d5bde8d3bba298233f95fd2494f08 Mon Sep 17 00:00:00 2001 From: "Visal .In" Date: Thu, 21 Nov 2024 14:16:32 +0700 Subject: [PATCH] add test for raw with placeholders --- src/connections/sql-base.ts | 6 +++++- src/utils/placeholder.ts | 3 +-- tests/connections/connection.test.ts | 28 ++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/connections/sql-base.ts b/src/connections/sql-base.ts index 8573799..89d62eb 100644 --- a/src/connections/sql-base.ts +++ b/src/connections/sql-base.ts @@ -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, diff --git a/src/utils/placeholder.ts b/src/utils/placeholder.ts index 3be331a..ce2c484 100644 --- a/src/utils/placeholder.ts +++ b/src/utils/placeholder.ts @@ -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) { @@ -90,7 +89,7 @@ export function namedPlaceholder( const key = placeholders[i]; if (numbered) { - newQuery += `$${key}`; + newQuery += `$${i + 1}`; } else { newQuery += `?`; } diff --git a/tests/connections/connection.test.ts b/tests/connections/connection.test.ts index 8c45dc6..387e067 100644 --- a/tests/connections/connection.test.ts +++ b/tests/connections/connection.test.ts @@ -36,6 +36,34 @@ function cleanup(data: Record[]) { } 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,