Last active
December 25, 2015 00:58
-
-
Save saikat/a5424c23ba29e9e13589 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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