From 81c287a49b6472283124cecdd3ae4683308c7cb0 Mon Sep 17 00:00:00 2001 From: Shane da Silva Date: Fri, 9 Feb 2024 21:25:41 -0800 Subject: [PATCH] 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. --- packages/pg/lib/utils.js | 13 +++++++++++-- packages/pg/test/unit/utils-tests.js | 7 +++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/packages/pg/lib/utils.js b/packages/pg/lib/utils.js index c82b6d89..09b8d3dd 100644 --- a/packages/pg/lib/utils.js +++ b/packages/pg/lib/utils.js @@ -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])) } diff --git a/packages/pg/test/unit/utils-tests.js b/packages/pg/test/unit/utils-tests.js index e300de6a..5eca7179 100644 --- a/packages/pg/test/unit/utils-tests.js +++ b/packages/pg/test/unit/utils-tests.js @@ -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 = {