Blame view

node_modules/loopback-connector-mysql/lib/transaction.js 1.75 KB
f7563de62   Palak Handa   first commit
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
  // Copyright IBM Corp. 2015,2016. All Rights Reserved.
  // Node module: loopback-connector-mysql
  // This file is licensed under the MIT License.
  // License text available at https://opensource.org/licenses/MIT
  
  'use strict';
  var debug = require('debug')('loopback:connector:mysql:transaction');
  module.exports = mixinTransaction;
  
  /*!
   * @param {MySQL} MySQL connector class
   * @param {Object} mysql mysql driver
   */
  function mixinTransaction(MySQL, mysql) {
    /**
     * Begin a new transaction
     * @param isolationLevel
     * @param cb
     */
    MySQL.prototype.beginTransaction = function(isolationLevel, cb) {
      debug('Begin a transaction with isolation level: %s', isolationLevel);
      this.client.getConnection(function(err, connection) {
        if (err) return cb(err);
        if (isolationLevel) {
          connection.query(
            'SET SESSION TRANSACTION ISOLATION LEVEL ' + isolationLevel,
            function(err) {
              if (err) return cb(err);
              connection.beginTransaction(function(err) {
                if (err) return cb(err);
                return cb(null, connection);
              });
            });
        } else {
          connection.beginTransaction(function(err) {
            if (err) return cb(err);
            return cb(null, connection);
          });
        }
      });
    };
  
    /**
     *
     * @param connection
     * @param cb
     */
    MySQL.prototype.commit = function(connection, cb) {
      debug('Commit a transaction');
      connection.commit(function(err) {
        connection.release();
        cb(err);
      });
    };
  
    /**
     *
     * @param connection
     * @param cb
     */
    MySQL.prototype.rollback = function(connection, cb) {
      debug('Rollback a transaction');
      connection.rollback(function(err) {
        connection.release();
        cb(err);
      });
    };
  }