Skip to content

Commit 5d821c3

Browse files
charmanderbrianc
authored andcommitted
Use more correct escaping for array elements (brianc#1177)
It’s not JSON.
1 parent 27bee1d commit 5d821c3

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

lib/utils.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@
88

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

11+
function escapeElement(elementRepresentation) {
12+
var escaped = elementRepresentation
13+
.replace(/\\/g, '\\\\')
14+
.replace(/"/g, '\\"');
15+
16+
return '"' + escaped + '"';
17+
}
18+
1119
// convert a JS array to a postgres array literal
1220
// uses comma separator so won't work for types like box that use
1321
// a different array separator.
@@ -25,7 +33,7 @@ function arrayString(val) {
2533
}
2634
else
2735
{
28-
result = result + JSON.stringify(prepareValue(val[i]));
36+
result += escapeElement(prepareValue(val[i]));
2937
}
3038
}
3139
result = result + '}';
@@ -104,15 +112,15 @@ function dateToString(date) {
104112
}
105113

106114
function dateToStringUTC(date) {
107-
115+
108116
var ret = pad(date.getUTCFullYear(), 4) + '-' +
109117
pad(date.getUTCMonth() + 1, 2) + '-' +
110118
pad(date.getUTCDate(), 2) + 'T' +
111119
pad(date.getUTCHours(), 2) + ':' +
112120
pad(date.getUTCMinutes(), 2) + ':' +
113121
pad(date.getUTCSeconds(), 2) + '.' +
114122
pad(date.getUTCMilliseconds(), 3);
115-
123+
116124
return ret + "+00:00";
117125
}
118126

test/integration/client/array-tests.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,36 @@
11
var helper = require(__dirname + "/test-helper");
22
var pg = helper.pg;
33

4+
test('serializing arrays', function() {
5+
pg.connect(helper.config, assert.calls(function(err, client, done) {
6+
assert.isNull(err);
7+
8+
test('nulls', function() {
9+
client.query('SELECT $1::text[] as array', [[null]], assert.success(function(result) {
10+
var array = result.rows[0].array;
11+
assert.lengthIs(array, 1);
12+
assert.isNull(array[0]);
13+
}));
14+
});
15+
16+
test('elements containing JSON-escaped characters', function() {
17+
var param = '\\"\\"';
18+
19+
for (var i = 1; i <= 0x1f; i++) {
20+
param += String.fromCharCode(i);
21+
}
22+
23+
client.query('SELECT $1::text[] as array', [[param]], assert.success(function(result) {
24+
var array = result.rows[0].array;
25+
assert.lengthIs(array, 1);
26+
assert.equal(array[0], param);
27+
}));
28+
29+
done();
30+
});
31+
}));
32+
});
33+
434
test('parsing array results', function() {
535
pg.connect(helper.config, assert.calls(function(err, client, done) {
636
assert.isNull(err);

0 commit comments

Comments
 (0)