Connect.php 6.2 KB
Newer Older
lzc828's avatar
init  
lzc828 已提交
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
<?php

namespace One\Database\Mysql;

use One\ConfigTrait;
use One\Facades\Log;
use One\Swoole\Pools;
use Swoole\Mysql\Exception;

class Connect
{

    use ConfigTrait, Pools;

    private static $pdo = [];

    private $key;

    private $config = [];

    private $model;

    /**
     * Connect constructor.
     * @param string $key
     * @param string $model
     */
    public function __construct($key, $model)
    {
lzc828's avatar
lzc828 已提交
30 31
        $this->key    = $key;
        $this->model  = $model;
lzc828's avatar
init  
lzc828 已提交
32 33 34 35 36 37 38 39 40 41
        $this->config = self::$conf[$key];
    }

    /**
     * @param string $sql
     * @param array $data
     * @return \PDOStatement|array
     */
    private function execute($sql, $data = [], $retry = 0, $return_pdo = false)
    {
lzc828's avatar
lzc828 已提交
42
        $pdo  = $this->pop();
lzc828's avatar
init  
lzc828 已提交
43 44 45 46 47 48 49 50
        $time = microtime(true);
        try {
            $res = $pdo->prepare($sql, [\PDO::ATTR_CURSOR => \PDO::CURSOR_SCROLL]);
            if (!$res) {
                return $this->retry($sql, $time, $data, $pdo->errorInfo()[2], $retry, $return_pdo);
            }
            $res->setFetchMode(\PDO::FETCH_CLASS, $this->model);
            $res->execute($data);
lzc828's avatar
lzc828 已提交
51
            $this->debugLog($sql, $time, $data, '');
lzc828's avatar
lzc828 已提交
52 53 54 55
            if ($res->errorInfo()[0] !== '00000') {
                $this->push($pdo);
                throw new DbException(json_encode(['info' => $res->errorInfo(), 'sql' => $sql, 'data' => $data]), 8);
            }
lzc828's avatar
init  
lzc828 已提交
56 57 58 59 60 61 62
            if ($return_pdo) {
                return [$res, $pdo];
            } else {
                $this->push($pdo);
                return $res;
            }
        } catch (\PDOException $e) {
lzc828's avatar
lzc828 已提交
63
            $this->debugLog($sql, $time, $data, $e->getMessage());
lzc828's avatar
init  
lzc828 已提交
64
            return $this->retry($sql, $time, $data, $e->getMessage(), $retry, $return_pdo);
lzc828's avatar
lzc828 已提交
65 66
        } catch (DbException $e) {
            throw $e;
lzc828's avatar
init  
lzc828 已提交
67
        } catch (\Throwable $e) {
lzc828's avatar
lzc828 已提交
68
            self::$connect_count--;
lzc828's avatar
lzc828 已提交
69
            throw new DbException(json_encode(['info' => $e->getMessage(), 'sql' => $sql]), $e->getCode());
lzc828's avatar
init  
lzc828 已提交
70 71 72 73 74
        }
    }

    private function retry($sql, $time, $data, $err, $retry, $return_pdo)
    {
lzc828's avatar
lzc828 已提交
75
        self::$connect_count--;
lzc828's avatar
init  
lzc828 已提交
76
        $this->debugLog($sql, $time, $data, $err);
lzc828's avatar
lzc828 已提交
77
        if ($this->isBreak($err) && $retry < $this->config['max_connect_count'] + 1) {
lzc828's avatar
init  
lzc828 已提交
78 79 80 81 82 83 84 85
            return $this->execute($sql, $data, ++$retry, $return_pdo);
        }
        throw new DbException(json_encode(['info' => $err, 'sql' => $sql]), 7);
    }

    private function debugLog($sql, $time = 0, $build = [], $err = [])
    {
        if (self::$conf['debug_log']) {
lzc828's avatar
lzc828 已提交
86 87 88
            $time  = $time ? (microtime(true) - $time) * 1000 : $time;
            $s     = vsprintf(str_replace('?', "'%s'", $sql), $build);
            $id    = md5(str_replace('()', '', str_replace(['?', ','], '', $sql)));
lzc828's avatar
lzc828 已提交
89
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 13);
lzc828's avatar
lzc828 已提交
90
            $k     = 1;
lzc828's avatar
lzc828 已提交
91 92
            foreach ($trace as $i => $v) {
                if (strpos($v['file'], DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'lizhichao' . DIRECTORY_SEPARATOR) === false) {
lzc828's avatar
lzc828 已提交
93 94 95 96
                    $k = $i + 1;
                    break;
                }
            }
lzc828's avatar
lzc828 已提交
97
            Log::debug(['sql' => $s, 'id' => $id, 'time' => $time, 'err' => $err], $k, 'sql');
lzc828's avatar
init  
lzc828 已提交
98 99 100 101 102 103 104 105
        }
    }

    public function getDns()
    {
        return $this->config['dns'];
    }

lzc828's avatar
lzc828 已提交
106 107 108 109 110
    public function getKey()
    {
        return $this->key;
    }

lzc828's avatar
init  
lzc828 已提交
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

    private function isBreak($error)
    {
        $info = [
            'server has gone away',
            'no connection to the server',
            'Lost connection',
            'is dead or not enabled',
            'Error while sending',
            'decryption failed or bad record mac',
            'server closed the connection unexpectedly',
            'SSL connection has been closed unexpectedly',
            'Error writing data to the connection',
            'Resource deadlock avoided',
        ];

        foreach ($info as $msg) {
            if (false !== stripos($error, $msg)) {
                return true;
            }
        }
        return false;
    }


lzc828's avatar
lzc828 已提交
136 137 138
    private $log_k = 0;


lzc828's avatar
init  
lzc828 已提交
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 184 185 186 187 188 189 190 191 192 193 194 195
    /**
     * @param string $sql
     * @param array $data
     * @return mixed
     */
    public function find($sql, $data = [])
    {
        return $this->execute($sql, $data)->fetch();
    }

    /**
     * @param string $sql
     * @param array $data
     * @return mixed
     */
    public function findAll($sql, $data = [])
    {
        return $this->execute($sql, $data)->fetchAll();
    }

    /**
     * @param string $sql
     * @param int
     */
    public function exec($sql, $data = [], $last_id = false)
    {
        list($res, $pdo) = $this->execute($sql, $data, 0, true);
        if ($last_id) {
            $r = $pdo->lastInsertId();
        } else {
            $r = $res->rowCount();
        }
        $this->push($pdo);
        return $r;
    }


    /**
     * @return bool
     */
    public function beginTransaction()
    {
        if ($this->inTransaction()) {
            return true;
        }
        $this->debugLog('begin');
        return $this->pop(true)->beginTransaction();
    }

    /**
     * @return bool
     */
    public function rollBack()
    {
        if ($this->inTransaction()) {
            $this->debugLog('rollBack');
            $pdo = $this->pop();
lzc828's avatar
lzc828 已提交
196
            $r   = $pdo->rollBack();
lzc828's avatar
init  
lzc828 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210
            $this->push($pdo, true);
            return $r;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function commit()
    {
        if ($this->inTransaction()) {
            $this->debugLog('commit');
            $pdo = $this->pop();
lzc828's avatar
lzc828 已提交
211
            $r   = $pdo->commit();
lzc828's avatar
init  
lzc828 已提交
212 213 214 215 216 217 218 219 220 221 222 223
            $this->push($pdo, true);
            return $r;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function inTransaction()
    {
        $pdo = $this->pop();
lzc828's avatar
lzc828 已提交
224
        $r   = $pdo->inTransaction();
lzc828's avatar
init  
lzc828 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        if (!$r) {
            $this->push($pdo);
        }
        return $r;
    }

    /**
     * @return \PDO
     * @throws DbException
     */
    private function createRes()
    {
        try {
            return new \PDO($this->config['dns'], $this->config['username'], $this->config['password'], $this->config['ops']);
        } catch (\PDOException $e) {
lzc828's avatar
lzc828 已提交
240
            throw new DbException('connection failed ' . $e->getMessage(), $e->getCode());
lzc828's avatar
init  
lzc828 已提交
241 242 243 244
        }
    }

}