From cfaff2f0e76b7b491294dff7de7913b057e7c8b8 Mon Sep 17 00:00:00 2001 From: "Visal .In" Date: Thu, 21 Nov 2024 18:24:23 +0700 Subject: [PATCH] add more test cases --- src/utils/placeholder.ts | 25 +++++++++++++++++++++++++ tests/units/placeholder.test.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/utils/placeholder.ts b/src/utils/placeholder.ts index ce2c484..ad240eb 100644 --- a/src/utils/placeholder.ts +++ b/src/utils/placeholder.ts @@ -82,6 +82,13 @@ export function namedPlaceholder( const [sqlFragments, placeholders] = parts; + // If placeholders contains any number, then it's a mix of named and numbered placeholders + if (placeholders.some((p) => typeof p === 'number')) { + throw new Error( + 'Mixing named and positional placeholder should throw error' + ); + } + for (let i = 0; i < sqlFragments.length; i++) { newQuery += sqlFragments[i]; @@ -94,6 +101,11 @@ export function namedPlaceholder( newQuery += `?`; } + const placeholderValue = params[key]; + if (placeholderValue === undefined) { + throw new Error(`Missing value for placeholder ${key}`); + } + bindings.push(params[key]); } } @@ -119,6 +131,19 @@ export function toNumberedPlaceholders( const [sqlFragments, placeholders] = parts; + if (placeholders.length !== params.length) { + throw new Error( + 'Number of positional placeholder should match with the number of values' + ); + } + + // Mixing named and numbered placeholders should throw error + if (placeholders.some((p) => typeof p === 'string')) { + throw new Error( + 'Mixing named and positional placeholder should throw error' + ); + } + for (let i = 0; i < sqlFragments.length; i++) { newQuery += sqlFragments[i]; diff --git a/tests/units/placeholder.test.ts b/tests/units/placeholder.test.ts index b8aa61f..695dfb5 100644 --- a/tests/units/placeholder.test.ts +++ b/tests/units/placeholder.test.ts @@ -60,6 +60,37 @@ test('Named placeholder to number placeholder with string', () => { }); }); +test('Named placeholder with missing value should throw an error', () => { + expect(() => + namedPlaceholder('SELECT * FROM users WHERE id = :id AND age > :age', { + id: 1, + }) + ).toThrow(); +}); + +test('Number of positional placeholder should match with the number of values', () => { + expect(() => + toNumberedPlaceholders('SELECT * FROM users WHERE id = ? AND age > ?', [ + 1, + ]) + ).toThrow(); +}); + +test('Mixing named and positional placeholder should throw error', () => { + expect(() => + namedPlaceholder('SELECT * FROM users WHERE id = :id AND age > ?', { + id: 1, + }) + ).toThrow(); + + expect(() => { + toNumberedPlaceholders( + `SELECT * FROM users WHERE id = ? AND age > :age`, + [1, 30] + ); + }).toThrow(); +}); + test('Convert positional placeholder to numbered placeholder', () => { expect( toNumberedPlaceholders(