Passed
Push — 5.1 ( 5f0d26...c377d9 )
by liu
09:49
created

Mysql::getExplain()   B

Complexity

Conditions 11
Paths 33

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 19
c 1
b 0
f 0
nc 33
nop 1
dl 0
loc 33
rs 7.3166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
12
namespace think\db\connector;
13
14
use PDO;
15
use think\db\Connection;
16
use think\db\Query;
17
18
/**
19
 * mysql数据库驱动
0 ignored issues
show
Coding Style introduced by
Doc comment short description must start with a capital letter
Loading history...
20
 */
21
class Mysql extends Connection
22
{
23
24
    protected $builder = '\\think\\db\\builder\\Mysql';
25
26
    /**
27
     * 初始化
28
     * @access protected
29
     * @return void
30
     */
31
    protected function initialize()
32
    {
33
        // Point类型支持
34
        Query::extend('point', function ($query, $field, $value = null, $fun = 'GeomFromText', $type = 'POINT') {
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
35
            if (!is_null($value)) {
36
                $query->data($field, ['point', $value, $fun, $type]);
37
            } else {
38
                if (is_string($field)) {
39
                    $field = explode(',', $field);
40
                }
41
                $query->setOption('point', $field);
42
            }
43
44
            return $query;
45
        });
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
46
    }
47
48
    /**
49
     * 解析pdo连接的dsn信息
50
     * @access protected
51
     * @param  array $config 连接信息
52
     * @return string
53
     */
54
    protected function parseDsn($config)
55
    {
56
        if (!empty($config['socket'])) {
57
            $dsn = 'mysql:unix_socket=' . $config['socket'];
58
        } elseif (!empty($config['hostport'])) {
59
            $dsn = 'mysql:host=' . $config['hostname'] . ';port=' . $config['hostport'];
60
        } else {
61
            $dsn = 'mysql:host=' . $config['hostname'];
62
        }
63
        $dsn .= ';dbname=' . $config['database'];
64
65
        if (!empty($config['charset'])) {
66
            $dsn .= ';charset=' . $config['charset'];
67
        }
68
69
        return $dsn;
70
    }
71
72
    /**
73
     * 取得数据表的字段信息
74
     * @access public
75
     * @param  string $tableName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
76
     * @return array
77
     */
78
    public function getFields($tableName)
79
    {
80
        list($tableName) = explode(' ', $tableName);
81
82
        if (false === strpos($tableName, '`')) {
83
            if (strpos($tableName, '.')) {
84
                $tableName = str_replace('.', '`.`', $tableName);
85
            }
86
            $tableName = '`' . $tableName . '`';
87
        }
88
89
        $sql    = 'SHOW COLUMNS FROM ' . $tableName;
90
        $pdo    = $this->query($sql, [], false, true);
91
        $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
92
        $info   = [];
93
94
        if ($result) {
95
            foreach ($result as $key => $val) {
96
                $val                 = array_change_key_case($val);
97
                $info[$val['field']] = [
98
                    'name'    => $val['field'],
99
                    'type'    => $val['type'],
100
                    'notnull' => (bool) ('' === $val['null']), // not null is empty, null is yes
101
                    'default' => $val['default'],
102
                    'primary' => (strtolower($val['key']) == 'pri'),
103
                    'autoinc' => (strtolower($val['extra']) == 'auto_increment'),
104
                ];
105
            }
106
        }
107
108
        return $this->fieldCase($info);
109
    }
110
111
    /**
112
     * 取得数据库的表信息
113
     * @access public
114
     * @param  string $dbName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
115
     * @return array
116
     */
117
    public function getTables($dbName = '')
118
    {
119
        $sql    = !empty($dbName) ? 'SHOW TABLES FROM ' . $dbName : 'SHOW TABLES ';
120
        $pdo    = $this->query($sql, [], false, true);
121
        $result = $pdo->fetchAll(PDO::FETCH_ASSOC);
122
        $info   = [];
123
124
        foreach ($result as $key => $val) {
125
            $info[$key] = current($val);
126
        }
127
128
        return $info;
129
    }
130
131
    /**
132
     * SQL性能分析
133
     * @access protected
134
     * @param  string $sql
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
135
     * @return array
136
     */
137
    protected function getExplain($sql)
138
    {
139
        $pdo = $this->linkID->prepare("EXPLAIN " . $this->queryStr);
140
141
        foreach ($this->bind as $key => $val) {
142
            // 占位符
143
            $param = is_int($key) ? $key + 1 : ':' . $key;
144
145
            if (is_array($val)) {
146
                if (PDO::PARAM_INT == $val[1] && '' === $val[0]) {
147
                    $val[0] = 0;
148
                } elseif (self::PARAM_FLOAT == $val[1]) {
149
                    $val[0] = is_string($val[0]) ? (float) $val[0] : $val[0];
150
                    $val[1] = PDO::PARAM_STR;
151
                }
152
153
                $result = $pdo->bindValue($param, $val[0], $val[1]);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
154
            } else {
155
                $result = $pdo->bindValue($param, $val);
156
            }
157
        }
158
159
        $pdo->execute();
160
        $result = $pdo->fetch(PDO::FETCH_ASSOC);
161
        $result = array_change_key_case($result);
162
163
        if (isset($result['extra'])) {
164
            if (strpos($result['extra'], 'filesort') || strpos($result['extra'], 'temporary')) {
165
                $this->log('SQL:' . $this->queryStr . '[' . $result['extra'] . ']', 'warn');
166
            }
167
        }
168
169
        return $result;
170
    }
171
172
    protected function supportSavepoint()
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
173
    {
174
        return true;
175
    }
176
177
    /**
178
     * 启动XA事务
179
     * @access public
180
     * @param  string $xid XA事务id
181
     * @return void
182
     */
183
    public function startTransXa($xid)
184
    {
185
        $this->initConnect(true);
186
        if (!$this->linkID) {
187
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type void.
Loading history...
188
        }
189
190
        $this->execute("XA START '$xid'");
191
    }
192
193
    /**
194
     * 预编译XA事务
195
     * @access public
196
     * @param  string $xid XA事务id
197
     * @return void
198
     */
199
    public function prepareXa($xid)
200
    {
201
        $this->initConnect(true);
202
        $this->execute("XA END '$xid'");
203
        $this->execute("XA PREPARE '$xid'");
204
    }
205
206
    /**
207
     * 提交XA事务
208
     * @access public
209
     * @param  string $xid XA事务id
210
     * @return void
211
     */
212
    public function commitXa($xid)
213
    {
214
        $this->initConnect(true);
215
        $this->execute("XA COMMIT '$xid'");
216
    }
217
218
    /**
219
     * 回滚XA事务
220
     * @access public
221
     * @param  string $xid XA事务id
222
     * @return void
223
     */
224
    public function rollbackXa($xid)
225
    {
226
        $this->initConnect(true);
227
        $this->execute("XA ROLLBACK '$xid'");
228
    }
229
}
230