Skip to content

Commit

Permalink
feat: throw an error if named placeholder values contain props not pr…
Browse files Browse the repository at this point in the history
…esent in the query
  • Loading branch information
gajus committed Apr 14, 2017
1 parent b1618d8 commit 9ab68a6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/utilities/normalizeNamedValuePlaceholders.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
} from '../types';

/**
* @see https://regex101.com/r/KrEe8i/1
* @see https://regex101.com/r/KrEe8i/2
*/
const namedPlaceholderRegex = /[\s,(]:([a-zA-Z]+)/g;

Expand All @@ -23,6 +23,7 @@ export default (
let placeholderIndex = 0;

const normalizedValues = [];
const valueNames = Object.keys(values);

// eslint-disable-next-line no-cond-assign
while (match = namedPlaceholderRegex.exec(sql)) {
Expand All @@ -35,6 +36,10 @@ export default (

const value = values[matchName];

if (valueNames.includes(matchName)) {
valueNames.splice(valueNames.indexOf(matchName));
}

normalizedValues.push(value);

result += sql.slice(chunkIndex, matchIndex);
Expand All @@ -46,6 +51,10 @@ export default (
result += '$' + placeholderIndex;
}

if (valueNames.length) {
throw new Error('Named placeholder values contain value(s) not present in the query.');
}

if (chunkIndex === 0) {
result = sql;
} else if (chunkIndex < sql.length) {
Expand Down
9 changes: 9 additions & 0 deletions test/utilities/normalizeNamedValuePlaceholders.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,12 @@ test('interpolates multiple value placeholders (same value)', (t) => {
'FOO'
]);
});

test('throws if values object contains properties not present in the query', (t) => {
t.throws(() => {
normalizeNamedValuePlaceholders('SELECT :foo', {
bar: 'BAR',
foo: 'FOO'
});
}, 'Named placeholder values contain value(s) not present in the query.');
});

0 comments on commit 9ab68a6

Please sign in to comment.