postgres icon indicating copy to clipboard operation
postgres copied to clipboard

Dynamic columns in insert and update should handle the case of empty object/array

Open paulovieira opened this issue 2 years ago • 1 comments

Consider this scenario:

const user = { name: 'Murray', age: 68 }
let columns = [];  // will be filled later 

// assume something went wrong and columns is still empty

await sql`
  insert into users ${
    sql(user, [])
  }
`

Or maybe this:


const user = {}; // will be filled later

// assume something went wrong and user is still empty

await sql`
  insert into users ${
    sql(user)
  }
`

We get this no-so-informative error: PostgresError: syntax error at or near "where".

Since dynamic columns can be, by definition, very dynamic, I think it would make sense to handle these special cases:

  • the object with data (first argument) is "empty"
  • the columns array (second argument) is empty

It would be a simple change in src/types.js, in the update and insert entries in the builders: https://github.com/porsager/postgres/blob/master/cjs/src/types.js#L164-L176

Before using the escapeIdentifier, it would be a matter of checking if the array is empty.

paulovieira avatar Jul 17 '23 12:07 paulovieira

That sounds reasonable.

Want to make a PR?

porsager avatar Oct 26 '23 22:10 porsager