# Code coverage report for thinkjs/lib/Lib/Driver/Db/MysqlDb.js

## Statements: 100% (65 / 65) Branches: 100% (26 / 26) Functions: 100% (21 / 21) Lines: 100% (65 / 65) Ignored: none

All files » thinkjs/lib/Lib/Driver/Db/ » MysqlDb.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
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183

    2
    2

    2

    4

    440
    440
    440
    439
    439
    439
    439
    439
    1

    439

    439

    1
    1
    1

    444
    1

    443
    2990
    27009
    2

    443

    93
    93
    93
    92
    4

    92

    212
    212
    210
    210
    1329

    210

    2
    2
    1

    2
    2
    6
    6

    5
    4
    4

    1
    1

    5
    2
    2

    3

    3
    2
    2

    1

    856
    856
    815

    856

    33

    4
    1
    1

     /**
     * mysql数据库
     * @return {[type]} [description]
     */
    var mysqlSocket = thinkRequire('MysqlSocket');
    module.exports = Db(function(){
      'use strict';

      return {
        /**
         * 连接数据库
         * @param  {[type]} config  [description]
         * @param  {[type]} linknum [description]
         * @return {[type]}         [description]
         */
        connect: function(config){
          return mysqlSocket(config);
        },
        /**
         * 查询一条sql
         * @param  string str
         * @return promise
         */
        query: function(str){
          this.setSql(str);
          var self = this;
          if (!(str in this.queryWaiting)) {
            this.queryWaiting[str] = [];
            return this.initConnect(false).query(str).then(function(data){
              data = self.bufferToString(data);
              process.nextTick(function(){
                self.queryWaiting[str].forEach(function(deferred){
                  deferred.resolve(data);
                });
                delete self.queryWaiting[str];
              })
              return data;
            });
          }else{
            var deferred = getDefer();
            this.queryWaiting[str].push(deferred);
            return deferred.promise;
          }
        },
        /**
         * 将buffer转为string
         * @param  {[type]} data [description]
         * @return {[type]}      [description]
         */
        bufferToString: function(data){
          if (!C('db_buffer_tostring') || !isArray(data)) {
            return data;
          }
          for(var i = 0, length = data.length; i < length; i++){
            for(var key in data[i]){
              if(isBuffer(data[i][key])){
                data[i][key] = data[i][key].toString();
              }
            }
          }
          return data;
        },
        /**
         * 执行一条sql, 返回影响的行数
         * @param  {[type]} str [description]
         * @return {[type]}     [description]
         */
        execute: function(str){
          this.setSql(str);
          var self = this;
          return this.initConnect(true).query(str).then(function(data){
            if (data.insertId) {
              self.lastInsertId = data.insertId;
            }
            return data.affectedRows || 0;
          });
        },
        /**
         * 获取数据表字段信息
         * @param  string tableName 数据表名
         * @return promise 返回一个promise
         */
        getFields: function(tableName){
          var sql = 'SHOW COLUMNS FROM ' + this.parseKey(tableName);
          return this.query(sql).then(function(data){
            var ret = {};
            data.forEach(function(item){
              ret[item.Field] = {
                'name': item.Field,
                'type': item.Type,
                'notnull': item.Null === '',
                'default': item.Default,
                'primary': item.Key === 'PRI',
                'unique': item.Key === 'UNI',
                'autoinc': item.Extra.toLowerCase() === 'auto_increment'
              };
            });
            return ret;
          });
        },
        /**
         * 获取数据库的表信息
         * @param  {[type]} dbName [description]
         * @return {[type]}        [description]
         */
        getTables: function(dbName){
          var sql = 'SHOW TABLES';
          if (dbName) {
            sql += ' FROM ' + dbName;
          }
          return this.query(sql).then(function(data){
            return data.map(function(item){
              for(var key in item){
                return item[key];
              }
            });
          });
        },
        /**
         * 启动事务
         * @return {[type]} [description]
         */
        startTrans: function(){
          if (this.transTimes === 0) {
            this.transTimes++;
            return this.execute('START TRANSACTION');
          }
          this.transTimes++;
          return getPromise();
        },
        /**
         * 提交事务
         * @return {[type]} [description]
         */
        commit: function(){
          if (this.transTimes > 0) {
            this.transTimes = 0;
            return this.execute('COMMIT');
          }
          return getPromise();
        },
        /**
         * 回滚事务
         * @return {[type]} [description]
         */
        rollback: function(){
          if (this.transTimes > 0) {
            this.transTimes = 0;
            return this.execute('ROLLBACK');
          }
          return getPromise();
        },
        /**
         * 解析key
         * @param  {[type]} key [description]
         * @return {[type]}     [description]
         */
        parseKey: function(key){
          key = (key || '').trim();
          if (!(/[,\'\"\*\(\)`.\s]/.test(key))) {
            key = '`' + key + '`';
          }
          return key;
        },
        /**
         * 获取最后插入的id
         * @return {[type]} [description]
         */
        getLastInsertId: function(){
          return this.lastInsertId;
        },
        /**
         * 关闭连接
         * @return {[type]} [description]
         */
        close: function(){
          if (this.linkId) {
            this.linkId.close();
            this.linkId = null;
          }
        }
      };
    });