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.
This commit is contained in:
Shane da Silva 2024-02-09 21:25:41 -08:00 committed by GitHub
parent df0f4d19fb
commit 81c287a49b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 2 deletions

View File

@ -21,8 +21,17 @@ function arrayString(val) {
result = result + 'NULL'
} else if (Array.isArray(val[i])) {
result = result + arrayString(val[i])
} else if (val[i] instanceof Buffer) {
result += '\\\\x' + val[i].toString('hex')
} else if (ArrayBuffer.isView(val[i])) {
var item = val[i]
if (!(item instanceof Buffer)) {
var buf = Buffer.from(item.buffer, item.byteOffset, item.byteLength)
if (buf.length === item.byteLength) {
item = buf
} else {
item = buf.slice(item.byteOffset, item.byteOffset + item.byteLength)
}
}
result += '\\\\x' + item.toString('hex')
} else {
result += escapeElement(prepareValue(val[i]))
}

View File

@ -175,6 +175,13 @@ test('prepareValue: buffer array prepared properly', function () {
assert.strictEqual(out, '{\\\\xdead,\\\\xbeef}')
})
test('prepareValue: Uint8Array array prepared properly', function () {
var buffer1 = Uint8Array.from(Buffer.from('dead', 'hex'))
var buffer2 = Uint8Array.from(Buffer.from('beef', 'hex'))
var out = utils.prepareValue([buffer1, buffer2])
assert.strictEqual(out, '{\\\\xdead,\\\\xbeef}')
})
test('prepareValue: objects with complex toPostgres prepared properly', function () {
var buf = Buffer.from('zomgcustom!')
var customType = {