2

I have a multi row node-postgres insert that is giving me issues. It is a parameterized query that uses a Common Table Expression to update a primary table and two tables with foreign keys. The query works with the parameters to the primary table, but, when I try to parameterize the foreign key tables, which are multi row, it throws the syntax error.

First, I have this function that takes an array and returns a string of values.

const buildValues = (id, values) => {
    return values 
        .map(val => "(" + id + ", '" + val + "', " + false + ")")
        .join(", ");
    };

Here is my query:

app.post('/api/saveperson', function (req, res) {
  pg.connect(connectionString, (err, client, done) => {

    const insertPerson = `
    WITH x AS ( INSERT INTO people (title, notes, name)
        VALUES ($1, $2, $3)
        RETURNING personId
    ),
    b AS (
        INSERT INTO sports (personid, name, favorite)
        VALUES $4 )
    INSERT INTO instructions (personid, name, favorite)
    VALUES $5; 
    `;

      client.query(insertPerson, 
            [ req.body.title
            , req.body.notes
            , req.body.name
            , queries.buildValues("SELECT personId FROM x", req.body.sports)
            , queries.buildValues("SELECT personId FROM x", req.body.instructions)
            ]
         )
          .then( () => client.end())
          .catch( err => console.log(err));
  });
  return res.json(req.body);
});
Matt
  • 4,462
  • 5
  • 25
  • 35

1 Answers1

1

Not sure if this is the best solution, but I ended up using pg-promise library instead of just pg. Then I use a transaction and a chained query:

  db.tx(t => {
      // BEGIN has been executed
      return t.one(
          `INSERT INTO people (title, notes, name) 
          VALUES ($[title], $[notes], $[name]) 
          RETURNING personid`, req.body)
          .then(data => {
            let sportsQueries = req.body.sports.map(sport => {
              return t.none(`INSERT INTO sports (personid, name) 
                          VALUES ($1, $2)`, [data.personid, sport]);     
            });

            let instructionsQueries = req.body.instructions.map(ins => {
              return t.none(`INSERT INTO instructions (personid, instruction) 
                          VALUES ($1, $2)`, [data.personid, ins]);
            });

            return t.batch(sportsQueries.concat(instructionsQueries));

          });
  })
     .then(data => {
         // Success, and COMMIT has been executed
     })
     .catch(error => {
         // Failure, and ROLLBACK has been executed
     })
vitaly-t
  • 24,279
  • 15
  • 116
  • 138
Matt
  • 4,462
  • 5
  • 25
  • 35
  • This looks correct. For higher-performance version though, see also: [Multi-row insert with pg-promise](http://stackoverflow.com/questions/37300997/multi-row-insert-with-pg-promise), i.e. you can generate each set of inserts as a single query, which would make the transaction much faster ;) – vitaly-t Apr 14 '17 at 14:51
  • I will look into that. Thank you! – Matt Apr 16 '17 at 13:11