aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/database-utils.js
blob: 6fe7e99aaca7cde5ca50084e97f132c9c5f7e6dd (plain) (blame)
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
'use strict'

const retry = require('async/retry')

const db = require('../initializers/database')
const logger = require('./logger')

const utils = {
  commitTransaction,
  retryTransactionWrapper,
  rollbackTransaction,
  startSerializableTransaction,
  transactionRetryer
}

function commitTransaction (t, callback) {
  return t.commit().asCallback(callback)
}

function rollbackTransaction (err, t, callback) {
  // Try to rollback transaction
  if (t) {
    // Do not catch err, report the original one
    t.rollback().asCallback(function () {
      return callback(err)
    })
  } else {
    return callback(err)
  }
}

// { arguments, errorMessage }
function retryTransactionWrapper (functionToRetry, options, finalCallback) {
  const args = options.arguments ? options.arguments : []

  utils.transactionRetryer(
    function (callback) {
      return functionToRetry.apply(this, args.concat([ callback ]))
    },
    function (err) {
      if (err) {
        logger.error(options.errorMessage, { error: err })
      }

      // Do not return the error, continue the process
      return finalCallback(null)
    }
  )
}

function transactionRetryer (func, callback) {
  retry({
    times: 5,

    errorFilter: function (err) {
      const willRetry = (err.name === 'SequelizeDatabaseError')
      logger.debug('Maybe retrying the transaction function.', { willRetry })
      return willRetry
    }
  }, func, callback)
}

function startSerializableTransaction (callback) {
  console.log(db)
  db.sequelize.transaction({ isolationLevel: 'SERIALIZABLE' }).asCallback(function (err, t) {
    // We force to return only two parameters
    return callback(err, t)
  })
}

// ---------------------------------------------------------------------------

module.exports = utils