Skip to content

Commit

Permalink
add more test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
invisal committed Nov 21, 2024
1 parent 599e047 commit cfaff2f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/utils/placeholder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];

Expand All @@ -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]);
}
}
Expand All @@ -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];

Expand Down
31 changes: 31 additions & 0 deletions tests/units/placeholder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit cfaff2f

Please sign in to comment.