Skip to content

Instantly share code, notes, and snippets.

@GeoffreyHervet
Last active February 20, 2024 13:59
Show Gist options
  • Save GeoffreyHervet/1461895894fc802ae1f307664c1c716b to your computer and use it in GitHub Desktop.
Save GeoffreyHervet/1461895894fc802ae1f307664c1c716b to your computer and use it in GitHub Desktop.
knex batch insert -> on duplicate key update
const { flow, chunk, map } = required('lodash/fp');
// batchInsert
const knexInsert = knex => async rows => knex.batchInsert('equipment_city', rows, BATCH_INSERT);
// batchInsert on duplicate
const knexInsertOnDuplicate = knex => /* async */ rows => flow(
chunk(BATCH_INSERT),
map(insertOnDuplicate(knex))
)(rows);
const insertOnDuplicate = knex => async batch => {
const sql = knex('equipment_city').insert(batch).toSQL().toNative();
return await knex.raw(sql.sql + ' ON DUPLICATE KEY UPDATE `size`=`size`+VALUES(`size`)', sql.bindings);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment