knex/src/util/batchInsert.js

76 lines
1.9 KiB
JavaScript
Raw Normal View History

import { isNumber, isArray, chunk, flatten, assign } from 'lodash';
import Promise from 'bluebird';
export default function batchInsert(client, tableName, batch, chunkSize = 1000) {
let returning = void 0;
let autoTransaction = true;
let transaction = null;
const getTransaction = () => new Promise((resolve, reject) => {
if(transaction) {
return resolve(transaction);
2016-05-09 22:38:56 +02:00
}
client.transaction(resolve)
.catch(reject);
});
const wrapper = assign(new Promise((resolve, reject) => {
const chunks = chunk(batch, chunkSize);
if(!isNumber(chunkSize) || chunkSize < 1) {
return reject(new TypeError(`Invalid chunkSize: ${chunkSize}`));
}
if(!isArray(batch)) {
return reject(new TypeError(`Invalid batch: Expected array, got ${typeof batch}`));
2016-05-09 22:38:56 +02:00
}
//Next tick to ensure wrapper functions are called if needed
return Promise.delay(1)
.then(getTransaction)
.then((tr) => {
return Promise.mapSeries(chunks, (items) => tr(tableName).insert(items, returning))
2016-05-10 08:41:06 +02:00
.then((result) => {
result = flatten(result || []);
2017-03-24 10:52:38 +01:00
if(autoTransaction) {
//TODO: -- Oracle tr.commit() does not return a 'thenable' !? Ugly hack for now.
return (tr.commit(result) || Promise.resolve())
2017-03-24 10:52:38 +01:00
.then(() => result);
2016-05-10 08:41:06 +02:00
}
2017-03-24 10:52:38 +01:00
return result;
2016-05-10 08:41:06 +02:00
})
.catch((error) => {
if(autoTransaction) {
return tr.rollback(error)
.then(() => Promise.reject(error));
2016-05-10 08:41:06 +02:00
}
return Promise.reject(error);
})
})
.then(resolve)
.catch(reject);
}), {
returning(columns) {
returning = columns;
return this;
},
transacting(tr) {
transaction = tr;
autoTransaction = false;
return this;
}
});
return wrapper;
2017-03-24 10:52:38 +01:00
}