Connect.php 6.4 KB
Newer Older
lzc828's avatar
lzc828 已提交
1 2
<?php

lzc828's avatar
lzc828 已提交
3
namespace One\Database\Pgsql;
lzc828's avatar
lzc828 已提交
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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

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)
    {
        $this->key    = $key;
        $this->model  = $model;
        $this->config = self::$conf[$key];
    }

    /**
     * @param string $sql
     * @param array $data
     * @return \PDOStatement|array
     */
    private function execute($sql, $data = [], $retry = 0, $return_pdo = false)
    {
        $pdo  = $this->pop();
        $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);
            $this->debugLog($sql, $time, $data, '');
            if ($res->errorInfo()[0] !== '00000') {
                $this->push($pdo);
                throw new DbException(json_encode(['info' => $res->errorInfo(), 'sql' => $sql, 'data' => $data]), 8);
            }
            if ($return_pdo) {
                return [$res, $pdo];
            } else {
                $this->push($pdo);
                return $res;
            }
        } catch (\PDOException $e) {
            $this->debugLog($sql, $time, $data, $e->getMessage());
            return $this->retry($sql, $time, $data, $e->getMessage(), $retry, $return_pdo);
        } catch (DbException $e) {
            throw $e;
        } catch (\Throwable $e) {
            self::$connect_count--;
            throw new DbException(json_encode(['info' => $e->getMessage(), 'sql' => $sql]), 7);
        }
    }

    private function retry($sql, $time, $data, $err, $retry, $return_pdo)
    {
        self::$connect_count--;
        $this->debugLog($sql, $time, $data, $err);
        if ($this->isBreak($err) && $retry < $this->config['max_connect_count'] + 1) {
            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']) {
            $time = $time ? (microtime(true) - $time) * 1000 : $time;
            $info = explode('?', $sql);
            foreach ($info as $i => &$v) {
                if (isset($build[$i])) {
                    $v = $v . "'{$build[$i]}'";
                }
            }
            $s   = implode('', $info);
            $sql = str_replace(['?', ','], '', $sql);
            $id  = md5(str_replace('()', '', $sql));

            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 13);
            $k = 1;
            foreach ($trace as $i => $v) {
                if (strpos($v['file'], DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'lizhichao' . DIRECTORY_SEPARATOR) === false) {
                    $k = $i + 1;
                    break;
                }
            }
            Log::debug(['sql' => $s, 'id' => $id, 'time' => $time, 'err' => $err], $k, 'sql');
        }
    }

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

    public function getKey()
    {
        return $this->key;
    }


    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;
    }


    private $log_k = 0;


    /**
     * @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();
            $r   = $pdo->rollBack();
            $this->push($pdo, true);
            return $r;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function commit()
    {
        if ($this->inTransaction()) {
            $this->debugLog('commit');
            $pdo = $this->pop();
            $r   = $pdo->commit();
            $this->push($pdo, true);
            return $r;
        }
        return false;
    }

    /**
     * @return bool
     */
    public function inTransaction()
    {
        $pdo = $this->pop();
        $r   = $pdo->inTransaction();
        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) {
            throw new DbException('connection failed ' . $e->getMessage(), 0);
        }
    }

}