Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

574
Visualizações
Batch update in Postgres and Knex.js, is there a way to tell exactly which rows have been updated?

I'm doing a batch update in Postgres using Knex.js. I don't know in advance which of the rows were actually changed. The update is wrapped in a transaction along with an insert operation to create a customized "upsert" operation. It looks more or less like this:

const upsertData = (data, trx) => {
  // Generate an update query for each row if row exists
  const updateQueries = [];
  data.forEach(row => {
    const query = trx('data')
      .returning('id')
      .where('id', '=', row.id)
      .update(row)
      .transacting(trx); // This makes every update be in the same transaction
    updateQueries.push(query);
  })
  return Promise.all(updateQueries) // Once every query is written
    .then(existingIds => {

      // Filter out the remaining rows
      const flatIds = existingIds.reduce((acc, id) => acc.concat(id), []);
      const rowsToInsert = data.filter(row => !flatIds.includes(row.id))

      // And insert them
      if (rowsToInsert.length > 0) {
        return trx('data')
          .returning('Title')
          .insert(rowsToInsert)
      }
    })
    .then(() => console.log('Data updated'))
    .catch(err => {
      console.log('error updating data: ', err);
      throw 'data update error';
    });
}

This way I get the ids of all updated rows, so I can insert the rest of the data. But now I also want to tell which of the updating rows were actually changed. That is, a lot of the rows were updated with the exact same data (as mentioned above, I have no way of telling in advance which rows have changed. I would have to read the existing data and compare it with the new data coming in). I want to tell exactly which rows received new data and which didn't.

Is this at all possible? If so, how?
Any help would be greatly appreciated!

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda