Skip to content

Commit

Permalink
Use more correct escaping for array elements (#1177)
Browse files Browse the repository at this point in the history
It’s not JSON.
  • Loading branch information
charmander authored and brianc committed Dec 10, 2016
1 parent 27bee1d commit 5d821c3
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@

var defaults = require('./defaults');

function escapeElement(elementRepresentation) {
var escaped = elementRepresentation
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"');

return '"' + escaped + '"';
}

// convert a JS array to a postgres array literal
// uses comma separator so won't work for types like box that use
// a different array separator.
Expand All @@ -25,7 +33,7 @@ function arrayString(val) {
}
else
{
result = result + JSON.stringify(prepareValue(val[i]));
result += escapeElement(prepareValue(val[i]));
}
}
result = result + '}';
Expand Down Expand Up @@ -104,15 +112,15 @@ function dateToString(date) {
}

function dateToStringUTC(date) {

var ret = pad(date.getUTCFullYear(), 4) + '-' +
pad(date.getUTCMonth() + 1, 2) + '-' +
pad(date.getUTCDate(), 2) + 'T' +
pad(date.getUTCHours(), 2) + ':' +
pad(date.getUTCMinutes(), 2) + ':' +
pad(date.getUTCSeconds(), 2) + '.' +
pad(date.getUTCMilliseconds(), 3);

return ret + "+00:00";
}

Expand Down
30 changes: 30 additions & 0 deletions test/integration/client/array-tests.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,36 @@
var helper = require(__dirname + "/test-helper");
var pg = helper.pg;

test('serializing arrays', function() {
pg.connect(helper.config, assert.calls(function(err, client, done) {
assert.isNull(err);

test('nulls', function() {
client.query('SELECT $1::text[] as array', [[null]], assert.success(function(result) {
var array = result.rows[0].array;
assert.lengthIs(array, 1);
assert.isNull(array[0]);
}));
});

test('elements containing JSON-escaped characters', function() {
var param = '\\"\\"';

for (var i = 1; i <= 0x1f; i++) {
param += String.fromCharCode(i);
}

client.query('SELECT $1::text[] as array', [[param]], assert.success(function(result) {
var array = result.rows[0].array;
assert.lengthIs(array, 1);
assert.equal(array[0], param);
}));

done();
});
}));
});

test('parsing array results', function() {
pg.connect(helper.config, assert.calls(function(err, client, done) {
assert.isNull(err);
Expand Down

0 comments on commit 5d821c3

Please sign in to comment.