Skip to content

Commit 81c287a

Browse files
authored
Serialize arrays of Uint8Array objects as hex escape sequences (#2930)
Previously, if you attempted to pass an array of `Uint8Array` objects to a prepared statement, it would render each literal numeric value of that array. Since `Uint8Array` (and `TypedArray` types) represent views over raw bytes, ensure these are serialized to Postgres as a byte representation.
1 parent df0f4d1 commit 81c287a

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

Diff for: packages/pg/lib/utils.js

+11-2
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,17 @@ function arrayString(val) {
2121
result = result + 'NULL'
2222
} else if (Array.isArray(val[i])) {
2323
result = result + arrayString(val[i])
24-
} else if (val[i] instanceof Buffer) {
25-
result += '\\\\x' + val[i].toString('hex')
24+
} else if (ArrayBuffer.isView(val[i])) {
25+
var item = val[i]
26+
if (!(item instanceof Buffer)) {
27+
var buf = Buffer.from(item.buffer, item.byteOffset, item.byteLength)
28+
if (buf.length === item.byteLength) {
29+
item = buf
30+
} else {
31+
item = buf.slice(item.byteOffset, item.byteOffset + item.byteLength)
32+
}
33+
}
34+
result += '\\\\x' + item.toString('hex')
2635
} else {
2736
result += escapeElement(prepareValue(val[i]))
2837
}

Diff for: packages/pg/test/unit/utils-tests.js

+7
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,13 @@ test('prepareValue: buffer array prepared properly', function () {
175175
assert.strictEqual(out, '{\\\\xdead,\\\\xbeef}')
176176
})
177177

178+
test('prepareValue: Uint8Array array prepared properly', function () {
179+
var buffer1 = Uint8Array.from(Buffer.from('dead', 'hex'))
180+
var buffer2 = Uint8Array.from(Buffer.from('beef', 'hex'))
181+
var out = utils.prepareValue([buffer1, buffer2])
182+
assert.strictEqual(out, '{\\\\xdead,\\\\xbeef}')
183+
})
184+
178185
test('prepareValue: objects with complex toPostgres prepared properly', function () {
179186
var buf = Buffer.from('zomgcustom!')
180187
var customType = {

0 commit comments

Comments
 (0)