aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/database-utils.ts
diff options
context:
space:
mode:
Diffstat (limited to 'server/helpers/database-utils.ts')
-rw-r--r--server/helpers/database-utils.ts69
1 files changed, 69 insertions, 0 deletions
diff --git a/server/helpers/database-utils.ts b/server/helpers/database-utils.ts
new file mode 100644
index 000000000..b842ab9ec
--- /dev/null
+++ b/server/helpers/database-utils.ts
@@ -0,0 +1,69 @@
1// TODO: import from ES6 when retry typing file will include errorFilter function
2import retry = require('async/retry')
3
4const db = require('../initializers/database')
5import { logger } from './logger'
6
7function commitTransaction (t, callback) {
8 return t.commit().asCallback(callback)
9}
10
11function rollbackTransaction (err, t, callback) {
12 // Try to rollback transaction
13 if (t) {
14 // Do not catch err, report the original one
15 t.rollback().asCallback(function () {
16 return callback(err)
17 })
18 } else {
19 return callback(err)
20 }
21}
22
23// { arguments, errorMessage }
24function retryTransactionWrapper (functionToRetry, options, finalCallback) {
25 const args = options.arguments ? options.arguments : []
26
27 transactionRetryer(
28 function (callback) {
29 return functionToRetry.apply(this, args.concat([ callback ]))
30 },
31 function (err) {
32 if (err) {
33 logger.error(options.errorMessage, { error: err })
34 }
35
36 // Do not return the error, continue the process
37 return finalCallback(null)
38 }
39 )
40}
41
42function transactionRetryer (func, callback) {
43 retry({
44 times: 5,
45
46 errorFilter: function (err) {
47 const willRetry = (err.name === 'SequelizeDatabaseError')
48 logger.debug('Maybe retrying the transaction function.', { willRetry })
49 return willRetry
50 }
51 }, func, callback)
52}
53
54function startSerializableTransaction (callback) {
55 db.sequelize.transaction({ isolationLevel: 'SERIALIZABLE' }).asCallback(function (err, t) {
56 // We force to return only two parameters
57 return callback(err, t)
58 })
59}
60
61// ---------------------------------------------------------------------------
62
63export {
64 commitTransaction,
65 retryTransactionWrapper,
66 rollbackTransaction,
67 startSerializableTransaction,
68 transactionRetryer
69}