12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067 |
- <?php
- namespace think\db;
- use PDO;
- use PDOStatement;
- use think\Db;
- use think\db\exception\BindParamException;
- use think\Debug;
- use think\Exception;
- use think\exception\PDOException;
- use think\Log;
- abstract class Connection
- {
-
- protected $PDOStatement;
-
- protected $queryStr = '';
-
- protected $numRows = 0;
-
- protected $transTimes = 0;
-
- protected $error = '';
-
- protected $links = [];
-
- protected $linkID;
- protected $linkRead;
- protected $linkWrite;
-
- protected $fetchType = PDO::FETCH_ASSOC;
-
- protected $attrCase = PDO::CASE_LOWER;
-
- protected static $event = [];
-
- protected $builder;
-
- protected $config = [
-
- 'type' => '',
-
- 'hostname' => '',
-
- 'database' => '',
-
- 'username' => '',
-
- 'password' => '',
-
- 'hostport' => '',
-
- 'dsn' => '',
-
- 'params' => [],
-
- 'charset' => 'utf8',
-
- 'prefix' => '',
-
- 'debug' => false,
-
- 'deploy' => 0,
-
- 'rw_separate' => false,
-
- 'master_num' => 1,
-
- 'slave_no' => '',
-
- 'read_master' => false,
-
- 'fields_strict' => true,
-
- 'result_type' => PDO::FETCH_ASSOC,
-
- 'resultset_type' => 'array',
-
- 'auto_timestamp' => false,
-
- 'datetime_format' => 'Y-m-d H:i:s',
-
- 'sql_explain' => false,
-
- 'builder' => '',
-
- 'query' => '\\think\\db\\Query',
-
- 'break_reconnect' => true,
- ];
-
- protected $params = [
- PDO::ATTR_CASE => PDO::CASE_NATURAL,
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
- PDO::ATTR_STRINGIFY_FETCHES => false,
- PDO::ATTR_EMULATE_PREPARES => false,
- ];
-
- protected $bind = [];
-
- public function __construct(array $config = [])
- {
- if (!empty($config)) {
- $this->config = array_merge($this->config, $config);
- }
- }
-
- protected function getQuery()
- {
- $class = $this->config['query'];
- return new $class($this);
- }
-
- public function getBuilder()
- {
- if (!empty($this->builder)) {
- return $this->builder;
- } else {
- return $this->getConfig('builder') ?: '\\think\\db\\builder\\' . ucfirst($this->getConfig('type'));
- }
- }
-
- public function __call($method, $args)
- {
- return call_user_func_array([$this->getQuery(), $method], $args);
- }
-
- abstract protected function parseDsn($config);
-
- abstract public function getFields($tableName);
-
- abstract public function getTables($dbName);
-
- abstract protected function getExplain($sql);
-
- public function fieldCase($info)
- {
-
- switch ($this->attrCase) {
- case PDO::CASE_LOWER:
- $info = array_change_key_case($info);
- break;
- case PDO::CASE_UPPER:
- $info = array_change_key_case($info, CASE_UPPER);
- break;
- case PDO::CASE_NATURAL:
- default:
-
- }
- return $info;
- }
-
- public function getConfig($config = '')
- {
- return $config ? $this->config[$config] : $this->config;
- }
-
- public function setConfig($config, $value = '')
- {
- if (is_array($config)) {
- $this->config = array_merge($this->config, $config);
- } else {
- $this->config[$config] = $value;
- }
- }
-
- public function connect(array $config = [], $linkNum = 0, $autoConnection = false)
- {
- if (!isset($this->links[$linkNum])) {
- if (!$config) {
- $config = $this->config;
- } else {
- $config = array_merge($this->config, $config);
- }
-
- if (isset($config['params']) && is_array($config['params'])) {
- $params = $config['params'] + $this->params;
- } else {
- $params = $this->params;
- }
-
- $this->attrCase = $params[PDO::ATTR_CASE];
-
- if (isset($config['result_type'])) {
- $this->fetchType = $config['result_type'];
- }
- try {
- if (empty($config['dsn'])) {
- $config['dsn'] = $this->parseDsn($config);
- }
- if ($config['debug']) {
- $startTime = microtime(true);
- }
- $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params);
- if ($config['debug']) {
-
- Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn'], 'sql');
- }
- } catch (\PDOException $e) {
- if ($autoConnection) {
- Log::record($e->getMessage(), 'error');
- return $this->connect($autoConnection, $linkNum);
- } else {
- throw $e;
- }
- }
- }
- return $this->links[$linkNum];
- }
-
- public function free()
- {
- try {
- $this->PDOStatement = null;
- } catch (\Exception $e) {
- Log::write("has error when free PDOStatement maybe mysql gone away,skip it:" . $e->getMessage(), log::DEBUG);
- }
- }
-
- public function getPdo()
- {
- if (!$this->linkID) {
- return false;
- } else {
- return $this->linkID;
- }
- }
-
- public function query($sql, $bind = [], $master = false, $pdo = false)
- {
- $this->initConnect($master);
- if (!$this->linkID) {
- return false;
- }
-
- $this->queryStr = $sql;
- if ($bind) {
- $this->bind = $bind;
- }
- Db::$queryTimes++;
- try {
-
- $this->debug(true);
-
- $this->PDOStatement = $this->linkID->prepare($sql);
-
- $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
-
- if ($procedure) {
- $this->bindParam($bind);
- } else {
- $this->bindValue($bind);
- }
-
- $this->PDOStatement->execute();
-
- $this->debug(false, '', $master);
-
- return $this->getResult($pdo, $procedure);
- } catch (\PDOException $e) {
- if ($this->isBreak($e)) {
- return $this->close()->query($sql, $bind, $master, $pdo);
- }
- throw new PDOException($e, $this->config, $this->getLastsql());
- } catch (\Throwable $e) {
- if ($this->isBreak($e)) {
- return $this->close()->query($sql, $bind, $master, $pdo);
- }
- throw $e;
- } catch (\Exception $e) {
- if ($this->isBreak($e)) {
- return $this->close()->query($sql, $bind, $master, $pdo);
- }
- throw $e;
- }
- }
-
- public function execute($sql, $bind = [], Query $query = null)
- {
- $this->initConnect(true);
- if (!$this->linkID) {
- return false;
- }
-
- $this->queryStr = $sql;
- if ($bind) {
- $this->bind = $bind;
- }
- Db::$executeTimes++;
- try {
-
- $this->debug(true);
-
- $this->PDOStatement = $this->linkID->prepare($sql);
-
- $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
-
- if ($procedure) {
- $this->bindParam($bind);
- } else {
- $this->bindValue($bind);
- }
-
- $this->PDOStatement->execute();
-
- $this->debug(false, '', true);
- if ($query && !empty($this->config['deploy']) && !empty($this->config['read_master'])) {
- $query->readMaster();
- }
- $this->numRows = $this->PDOStatement->rowCount();
- return $this->numRows;
- } catch (\PDOException $e) {
- if ($this->isBreak($e)) {
- return $this->close()->execute($sql, $bind, $query);
- }
- throw new PDOException($e, $this->config, $this->getLastsql());
- } catch (\Throwable $e) {
- if ($this->isBreak($e)) {
- return $this->close()->execute($sql, $bind, $query);
- }
- throw $e;
- } catch (\Exception $e) {
- if ($this->isBreak($e)) {
- return $this->close()->execute($sql, $bind, $query);
- }
- throw $e;
- }
- }
-
- public function getRealSql($sql, array $bind = [])
- {
- if (is_array($sql)) {
- $sql = implode(';', $sql);
- }
- foreach ($bind as $key => $val) {
- $value = is_array($val) ? $val[0] : $val;
- $type = is_array($val) ? $val[1] : PDO::PARAM_STR;
- if (PDO::PARAM_STR == $type) {
- $value = $this->quote($value);
- } elseif (PDO::PARAM_INT == $type) {
- $value = (float) $value;
- }
-
- $sql = is_numeric($key) ?
- substr_replace($sql, $value, strpos($sql, '?'), 1) :
- str_replace(
- [':' . $key . ')', ':' . $key . ',', ':' . $key . ' ', ':' . $key . PHP_EOL],
- [$value . ')', $value . ',', $value . ' ', $value . PHP_EOL],
- $sql . ' ');
- }
- return rtrim($sql);
- }
-
- protected function bindValue(array $bind = [])
- {
- foreach ($bind as $key => $val) {
-
- $param = is_numeric($key) ? $key + 1 : ':' . $key;
- if (is_array($val)) {
- if (PDO::PARAM_INT == $val[1] && '' === $val[0]) {
- $val[0] = 0;
- }
- $result = $this->PDOStatement->bindValue($param, $val[0], $val[1]);
- } else {
- $result = $this->PDOStatement->bindValue($param, $val);
- }
- if (!$result) {
- throw new BindParamException(
- "Error occurred when binding parameters '{$param}'",
- $this->config,
- $this->getLastsql(),
- $bind
- );
- }
- }
- }
-
- protected function bindParam($bind)
- {
- foreach ($bind as $key => $val) {
- $param = is_numeric($key) ? $key + 1 : ':' . $key;
- if (is_array($val)) {
- array_unshift($val, $param);
- $result = call_user_func_array([$this->PDOStatement, 'bindParam'], $val);
- } else {
- $result = $this->PDOStatement->bindValue($param, $val);
- }
- if (!$result) {
- $param = array_shift($val);
- throw new BindParamException(
- "Error occurred when binding parameters '{$param}'",
- $this->config,
- $this->getLastsql(),
- $bind
- );
- }
- }
- }
-
- protected function getResult($pdo = false, $procedure = false)
- {
- if ($pdo) {
-
- return $this->PDOStatement;
- }
- if ($procedure) {
-
- return $this->procedure();
- }
- $result = $this->PDOStatement->fetchAll($this->fetchType);
- $this->numRows = count($result);
- return $result;
- }
-
- protected function procedure()
- {
- $item = [];
- do {
- $result = $this->getResult();
- if ($result) {
- $item[] = $result;
- }
- } while ($this->PDOStatement->nextRowset());
- $this->numRows = count($item);
- return $item;
- }
-
- public function transaction($callback)
- {
- $this->startTrans();
- try {
- $result = null;
- if (is_callable($callback)) {
- $result = call_user_func_array($callback, [$this]);
- }
- $this->commit();
- return $result;
- } catch (\Exception $e) {
- $this->rollback();
- throw $e;
- } catch (\Throwable $e) {
- $this->rollback();
- throw $e;
- }
- }
-
- public function startTrans()
- {
- $this->initConnect(true);
- if (!$this->linkID) {
- return false;
- }
- ++$this->transTimes;
- try {
- if (1 == $this->transTimes) {
- $this->linkID->beginTransaction();
- } elseif ($this->transTimes > 1 && $this->supportSavepoint()) {
- $this->linkID->exec(
- $this->parseSavepoint('trans' . $this->transTimes)
- );
- }
- } catch (\Exception $e) {
- if ($this->isBreak($e)) {
- --$this->transTimes;
- return $this->close()->startTrans();
- }
- throw $e;
- } catch (\Error $e) {
- if ($this->isBreak($e)) {
- --$this->transTimes;
- return $this->close()->startTrans();
- }
- throw $e;
- }
- }
-
- public function commit()
- {
- $this->initConnect(true);
- if (1 == $this->transTimes) {
- $this->linkID->commit();
- }
- --$this->transTimes;
- }
-
- public function rollback()
- {
- $this->initConnect(true);
- if (1 == $this->transTimes) {
- $this->linkID->rollBack();
- } elseif ($this->transTimes > 1 && $this->supportSavepoint()) {
- $this->linkID->exec(
- $this->parseSavepointRollBack('trans' . $this->transTimes)
- );
- }
- $this->transTimes = max(0, $this->transTimes - 1);
- }
-
- protected function supportSavepoint()
- {
- return false;
- }
-
- protected function parseSavepoint($name)
- {
- return 'SAVEPOINT ' . $name;
- }
-
- protected function parseSavepointRollBack($name)
- {
- return 'ROLLBACK TO SAVEPOINT ' . $name;
- }
-
- public function batchQuery($sqlArray = [], $bind = [], Query $query = null)
- {
- if (!is_array($sqlArray)) {
- return false;
- }
-
- $this->startTrans();
- try {
- foreach ($sqlArray as $sql) {
- $this->execute($sql, $bind, $query);
- }
-
- $this->commit();
- } catch (\Exception $e) {
- $this->rollback();
- throw $e;
- }
- return true;
- }
-
- public function getQueryTimes($execute = false)
- {
- return $execute ? Db::$queryTimes + Db::$executeTimes : Db::$queryTimes;
- }
-
- public function getExecuteTimes()
- {
- return Db::$executeTimes;
- }
-
- public function close()
- {
- $this->linkID = null;
- $this->linkWrite = null;
- $this->linkRead = null;
- $this->links = [];
-
- $this->free();
- return $this;
- }
-
- protected function isBreak($e)
- {
- if (!$this->config['break_reconnect']) {
- return false;
- }
- $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',
- 'failed with errno',
- 'send of 33 bytes failed with errno=32 Broken pipe',
- 'send of 93 bytes failed with errno=110 Connection timed out'
- ];
- $error = $e->getMessage();
- foreach ($info as $msg) {
- if (false !== stripos($error, $msg)) {
- return true;
- }
- }
- return false;
- }
-
- public function getLastSql()
- {
- return $this->getRealSql($this->queryStr, $this->bind);
- }
-
- public function getLastInsID($sequence = null)
- {
- return $this->linkID->lastInsertId($sequence);
- }
-
- public function getNumRows()
- {
- return $this->numRows;
- }
-
- public function getError()
- {
- if ($this->PDOStatement) {
- $error = $this->PDOStatement->errorInfo();
- $error = $error[1] . ':' . $error[2];
- } else {
- $error = '';
- }
- if ('' != $this->queryStr) {
- $error .= "\n [ SQL语句 ] : " . $this->getLastsql();
- }
- return $error;
- }
-
- public function quote($str, $master = true)
- {
- $this->initConnect($master);
- return $this->linkID ? $this->linkID->quote($str) : $str;
- }
-
- protected function debug($start, $sql = '', $master = false)
- {
- if (!empty($this->config['debug'])) {
-
- if ($start) {
- Debug::remark('queryStartTime', 'time');
- } else {
-
- Debug::remark('queryEndTime', 'time');
- $runtime = Debug::getRangeTime('queryStartTime', 'queryEndTime');
- $sql = $sql ?: $this->getLastsql();
- $result = [];
-
- if ($this->config['sql_explain'] && 0 === stripos(trim($sql), 'select')) {
- $result = $this->getExplain($sql);
- }
-
- $this->trigger($sql, $runtime, $result, $master);
- }
- }
- }
-
- public function listen($callback)
- {
- self::$event[] = $callback;
- }
-
- protected function trigger($sql, $runtime, $explain = [], $master = false)
- {
- if (!empty(self::$event)) {
- foreach (self::$event as $callback) {
- if (is_callable($callback)) {
- call_user_func_array($callback, [$sql, $runtime, $explain, $master]);
- }
- }
- } else {
-
- if ($this->config['deploy']) {
-
- $master = $master ? 'master|' : 'slave|';
- } else {
- $master = '';
- }
- Log::record('[ SQL ] ' . $sql . ' [ ' . $master . 'RunTime:' . $runtime . 's ]', 'sql');
- if (!empty($explain)) {
- Log::record('[ EXPLAIN : ' . var_export($explain, true) . ' ]', 'sql');
- }
- }
- }
-
- protected function initConnect($master = true)
- {
- if (!empty($this->config['deploy'])) {
-
- if ($master || $this->transTimes) {
- if (!$this->linkWrite) {
- $this->linkWrite = $this->multiConnect(true);
- }
- $this->linkID = $this->linkWrite;
- } else {
- if (!$this->linkRead) {
- $this->linkRead = $this->multiConnect(false);
- }
- $this->linkID = $this->linkRead;
- }
- } elseif (!$this->linkID) {
-
- $this->linkID = $this->connect();
- }
- }
-
- protected function multiConnect($master = false)
- {
- $_config = [];
-
- foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
- $_config[$name] = explode(',', $this->config[$name]);
- }
-
- $m = floor(mt_rand(0, $this->config['master_num'] - 1));
- if ($this->config['rw_separate']) {
-
- if ($master)
- {
- $r = $m;
- } elseif (is_numeric($this->config['slave_no'])) {
-
- $r = $this->config['slave_no'];
- } else {
-
- $r = floor(mt_rand($this->config['master_num'], count($_config['hostname']) - 1));
- }
- } else {
-
- $r = floor(mt_rand(0, count($_config['hostname']) - 1));
- }
- $dbMaster = false;
- if ($m != $r) {
- $dbMaster = [];
- foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
- $dbMaster[$name] = isset($_config[$name][$m]) ? $_config[$name][$m] : $_config[$name][0];
- }
- }
- $dbConfig = [];
- foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
- $dbConfig[$name] = isset($_config[$name][$r]) ? $_config[$name][$r] : $_config[$name][0];
- }
- return $this->connect($dbConfig, $r, $r == $m ? false : $dbMaster);
- }
-
- public function __destruct()
- {
-
- if ($this->PDOStatement) {
- $this->free();
- }
-
- $this->close();
- }
- }
|