batchInsert.js
2.63 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
exports.__esModule = true;
var _typeof2 = require('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _assign2 = require('lodash/assign');
var _assign3 = _interopRequireDefault(_assign2);
var _flatten2 = require('lodash/flatten');
var _flatten3 = _interopRequireDefault(_flatten2);
var _chunk2 = require('lodash/chunk');
var _chunk3 = _interopRequireDefault(_chunk2);
var _isArray2 = require('lodash/isArray');
var _isArray3 = _interopRequireDefault(_isArray2);
var _isNumber2 = require('lodash/isNumber');
var _isNumber3 = _interopRequireDefault(_isNumber2);
exports.default = batchInsert;
var _bluebird = require('bluebird');
var _bluebird2 = _interopRequireDefault(_bluebird);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function batchInsert(client, tableName, batch) {
var chunkSize = arguments.length <= 3 || arguments[3] === undefined ? 1000 : arguments[3];
var _returning = void 0;
var autoTransaction = true;
var transaction = null;
var getTransaction = function getTransaction() {
return new _bluebird2.default(function (resolve, reject) {
if (transaction) {
return resolve(transaction);
}
client.transaction(resolve).catch(reject);
});
};
var wrapper = (0, _assign3.default)(new _bluebird2.default(function (resolve, reject) {
var chunks = (0, _chunk3.default)(batch, chunkSize);
if (!(0, _isNumber3.default)(chunkSize) || chunkSize < 1) {
return reject(new TypeError('Invalid chunkSize: ' + chunkSize));
}
if (!(0, _isArray3.default)(batch)) {
return reject(new TypeError('Invalid batch: Expected array, got ' + (typeof batch === 'undefined' ? 'undefined' : (0, _typeof3.default)(batch))));
}
//Next tick to ensure wrapper functions are called if needed
return _bluebird2.default.delay(1).then(getTransaction).then(function (tr) {
return _bluebird2.default.mapSeries(chunks, function (items) {
return tr(tableName).insert(items, _returning);
}).then(function (result) {
if (autoTransaction) {
tr.commit();
}
return (0, _flatten3.default)(result);
}).catch(function (error) {
if (autoTransaction) {
tr.rollback(error);
}
throw error;
});
}).then(resolve).catch(reject);
}), {
returning: function returning(columns) {
_returning = columns;
return this;
},
transacting: function transacting(tr) {
transaction = tr;
autoTransaction = false;
return this;
}
});
return wrapper;
}
module.exports = exports['default'];