Use more correct escaping for array elements (#1177)

It’s not JSON.
This commit is contained in:
Charmander 2016-12-10 15:28:48 -08:00 committed by Brian C
parent 27bee1d0bc
commit 5d821c3acb
2 changed files with 41 additions and 3 deletions

View File

@ -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.
@ -25,7 +33,7 @@ function arrayString(val) {
}
else
{
result = result + JSON.stringify(prepareValue(val[i]));
result += escapeElement(prepareValue(val[i]));
}
}
result = result + '}';
@ -104,7 +112,7 @@ function dateToString(date) {
}
function dateToStringUTC(date) {
var ret = pad(date.getUTCFullYear(), 4) + '-' +
pad(date.getUTCMonth() + 1, 2) + '-' +
pad(date.getUTCDate(), 2) + 'T' +
@ -112,7 +120,7 @@ function dateToStringUTC(date) {
pad(date.getUTCMinutes(), 2) + ':' +
pad(date.getUTCSeconds(), 2) + '.' +
pad(date.getUTCMilliseconds(), 3);
return ret + "+00:00";
}

View File

@ -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);