/
batchInsert.js
84 lines (71 loc) · 2.06 KB
/
batchInsert.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const { isNumber, chunk, flatten } = require('lodash');
const Bluebird = require('bluebird');
module.exports = function batchInsert(
client,
tableName,
batch,
chunkSize = 1000
) {
let returning = void 0;
let autoTransaction = true;
let transaction = null;
const getTransaction = () =>
new Bluebird((resolve, reject) => {
if (transaction) {
autoTransaction = false;
return resolve(transaction);
}
autoTransaction = true;
client.transaction(resolve).catch(reject);
});
const wrapper = Object.assign(
new Bluebird((resolve, reject) => {
const chunks = chunk(batch, chunkSize);
if (!isNumber(chunkSize) || chunkSize < 1) {
return reject(new TypeError(`Invalid chunkSize: ${chunkSize}`));
}
if (!Array.isArray(batch)) {
return reject(
new TypeError(`Invalid batch: Expected array, got ${typeof batch}`)
);
}
//Next tick to ensure wrapper functions are called if needed
return Bluebird.delay(1)
.then(getTransaction)
.then((tr) => {
return Bluebird.mapSeries(chunks, (items) =>
tr(tableName).insert(items, returning)
)
.then((result) => {
result = flatten(result || []);
if (autoTransaction) {
//TODO: -- Oracle tr.commit() does not return a 'thenable' !? Ugly hack for now.
return (tr.commit(result) || Bluebird.resolve()).then(
() => result
);
}
return result;
})
.catch((error) => {
if (autoTransaction) {
return tr.rollback(error).then(() => Bluebird.reject(error));
}
return Bluebird.reject(error);
});
})
.then(resolve)
.catch(reject);
}),
{
returning(columns) {
returning = columns;
return this;
},
transacting(tr) {
transaction = tr;
return this;
},
}
);
return wrapper;
};