Skip to content

JSONB arguments not treated consistently #2012

Open
@jasperblues

Description

@jasperblues

According to docs, there is no special treatment required for JSONB bind arguments. In practice there is:

  • When the argument is a single object, it is bound correctly
  • When the argument is an Array, it is necessary to call JSON.stringify on the args.

Here's a test case that reproduces the issue:

const { Client } = require('pg');
const { inspect } = require('util');
async function doIt() {
    const client = new Client();
    console.log('Connecting...');
    await client.connect();
    console.log('Connected');
    const a = [
        {
            the: 'quick',
            brown: 'fox',
            jumps: 'over the',
            lazy: 'dog',
            some: { other: 'object', dilroy: ['hello', 'world'], numpty: new Date() }
        }
    ];
    console.log('Inserting...');
    const result = await client.query(`insert into sb_json(c1) values ($1) returning *`, [a]);
    console.log(`result = ${inspect(result, { depth: null })}`);
    console.log('Disconnecting...');
    await client.end();
}
doIt()
    .then(() => console.log('All done'))
    .catch(e => console.log(inspect(e)));

Current documented contract is that no special treatment is required.

Possible solution:

  • Document current behavior. This is the less ideal solution, as arguably it is better to be consistent. Never call JSON.stringify on args, or always do so. Not one case for arrays, and on case for single items.
  • Inspect the contents of the array. If it contains all primitive types insert for that type. Otherwise call JSON.stringify internally. This operation would run in O(n) time - for a very large array it would be slow.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions