Skip to content

Instantly share code, notes, and snippets.

@saikat
Last active December 25, 2015 00:58
Show Gist options
  • Save saikat/a5424c23ba29e9e13589 to your computer and use it in GitHub Desktop.
Save saikat/a5424c23ba29e9e13589 to your computer and use it in GitHub Desktop.
knex.bulkInsert = async function(table, values, {transaction}={}) {
if (values.length < 1)
return;
let valueKeys = Object.keys(values[0])
let columns = `("${valueKeys.join('","')}")`;
let valueString = values.map((valueObj) => {
let quotedValues = valueKeys.map((key) => {
let val = valueObj[key]
if (typeof val === 'object')
val = val.toISOString()
else
val = val.toString()
val = val.replace('\'', '\'\'')
return `'${val}'`
})
return `(${quotedValues.join(',')})`
}).join(', ')
let statement = `INSERT INTO "${table}" ${columns} VALUES ${valueString}`
let query = knex.raw(statement)
if (transaction)
query = query.transacting(transaction)
return query
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment