Skip to content

Commit

Permalink
Serialize arrays of Uint8Array objects as hex escape sequences (#2930)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
sds authored Feb 10, 2024
1 parent df0f4d1 commit 81c287a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
13 changes: 11 additions & 2 deletions packages/pg/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]))
}
Expand Down
7 changes: 7 additions & 0 deletions packages/pg/test/unit/utils-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down

0 comments on commit 81c287a

Please sign in to comment.