felixfbecker / node-sql-template-strings

ES6 tagged template strings for prepared SQL statements 📋
ISC License
610 stars 40 forks source link

Dynamic column names #58

Closed matbz closed 7 years ago

matbz commented 7 years ago

I try to do an update with dynamic column names and values. With fixed column names the code works, but not with dynamic ones. What would I have to change to make it work? Thanks!


      const updateData = SQL` `;
      Object.keys(data).forEach((key, index, arr) => {
        updateData.append(SQL`${key} = ${data[key]}`);
        if(index < arr.length - 1) {
          updateData.append(', ');
        }
      });

      const query = SQL`
      update category
      set`.append(updateData).append(SQL`
      where id = ${id}
      `);
felixfbecker commented 7 years ago

Column names can not be dynamic placeholders. See the readme section about raw values.

JonCognioDigital commented 3 years ago

Has anybody found a good workaround for this?

Building a dynamic statement for patching a record seems to be fairly laborious. There must be a better way than using an individual .append statement for each column you want to add wrapped in an if statement?

Let's say you have an input object...

{
    col2: "value2", 
    col4: "value4"
}

... and you want to loop over it to create a statement like this....

UPDATE table_name SET col1=val1, col2=val2, col3=val3, col4=val4, col5=val5;

... but you only want to set the columns aren't undefined in the input object. maybe I'm missing something here? How do people do this?