Skip to content

Instantly share code, notes, and snippets.

@noam-honig
Last active September 11, 2024 13:02
Show Gist options
  • Save noam-honig/db0186f0fcaef0784bb5efd29f5d4c42 to your computer and use it in GitHub Desktop.
Save noam-honig/db0186f0fcaef0784bb5efd29f5d4c42 to your computer and use it in GitHub Desktop.
bulk insert without hooks - just push to sql db
async function bulkInsert<entityType extends EntityBase>(
array: entityType[],
db: SqlDatabase,
) {
if (array.length == 0) return
const chunkSize = 250
for (let i = 0; i < array.length; i += chunkSize) {
const items = array.slice(i, i + chunkSize)
// do whatever
const c = db.createCommand()
let sql =
'insert into ' +
(await items[0]._.metadata.dbName) +
' (' +
(
await Promise.all(
items[0]._.metadata.fields.toArray().map((f) => f.dbName),
)
).join(',') +
') values '
sql += items
.map(
(row) =>
'(' +
row.$.toArray()
.map((f) => c.param(f.metadata.valueConverter.toDb!(f.value)))
.join(', ') +
')',
)
.join(',')
await c.execute(sql)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment