Skip to content

Commit

Permalink
fix(Clause): match whole variable when inlining using interpolate
Browse files Browse the repository at this point in the history
Previously when inlining variables, a simple string replacement was used which meant that shorter
variables could be inlined into longer ones. Eg. a variable "$param" could be inlined into the
string "$paramName" to produce 'value'Name, which is obviously incorrect. The string replacement
operation now attempts to only inline a param if it matches the entire variable.
  • Loading branch information
jamesfer committed Aug 6, 2018
1 parent 350bb63 commit d0588aa
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
26 changes: 26 additions & 0 deletions src/clause.spec.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,28 @@
import { Clause } from './clause';
import { Where } from './clauses';
import { expect } from 'chai';
import { ParameterBag } from './parameter-bag';

describe('Clause', () => {
describe('interpolate', () => {
it('should correctly inline parameters that share a prefix', () => {
class SpecialClause extends Clause {
constructor(public query: string) {
super();
}

build() {
return this.query;
}
}

const bag = new ParameterBag();
bag.addParam('abc', 'param');
bag.addParam('def', 'paramLong');

const clause = new SpecialClause('param = $paramLong');
clause.useParameterBag(bag);
expect(clause.interpolate()).to.equal(`param = 'def'`);
});
});
});
5 changes: 3 additions & 2 deletions src/clause.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@ export abstract class Clause extends ParameterContainer {
* @return {string}
*/
interpolate() {
const params = this.getParams();
let query = this.build();
const params = this.getParams();
for (const name in params) {
query = query.replace('$' + name, stringifyValue(params[name]));
const pattern = new RegExp(`\\$${name}(?![a-zA-Z0-9_])`, 'g');
query = query.replace(pattern, stringifyValue(params[name]));
}
return query;
}
Expand Down

0 comments on commit d0588aa

Please sign in to comment.