12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193 |
- <?php
- namespace yii\db;
- use PDO;
- use Yii;
- use yii\base\Component;
- use yii\base\InvalidConfigException;
- use yii\base\NotSupportedException;
- use yii\caching\CacheInterface;
- class Connection extends Component
- {
-
- const EVENT_AFTER_OPEN = 'afterOpen';
-
- const EVENT_BEGIN_TRANSACTION = 'beginTransaction';
-
- const EVENT_COMMIT_TRANSACTION = 'commitTransaction';
-
- const EVENT_ROLLBACK_TRANSACTION = 'rollbackTransaction';
-
- public $dsn;
-
- public $username;
-
- public $password;
-
- public $attributes;
-
- public $pdo;
-
- public $enableSchemaCache = false;
-
- public $schemaCacheDuration = 3600;
-
- public $schemaCacheExclude = [];
-
- public $schemaCache = 'cache';
-
- public $enableQueryCache = true;
-
- public $queryCacheDuration = 3600;
-
- public $queryCache = 'cache';
-
- public $charset;
-
- public $emulatePrepare;
-
- public $tablePrefix = '';
-
- public $schemaMap = [
- 'pgsql' => 'yii\db\pgsql\Schema',
- 'mysqli' => 'yii\db\mysql\Schema',
- 'mysql' => 'yii\db\mysql\Schema',
- 'sqlite' => 'yii\db\sqlite\Schema',
- 'sqlite2' => 'yii\db\sqlite\Schema',
- 'sqlsrv' => 'yii\db\mssql\Schema',
- 'oci' => 'yii\db\oci\Schema',
- 'mssql' => 'yii\db\mssql\Schema',
- 'dblib' => 'yii\db\mssql\Schema',
- 'cubrid' => 'yii\db\cubrid\Schema',
- ];
-
- public $pdoClass;
-
- public $commandClass = 'yii\db\Command';
-
- public $commandMap = [
- 'pgsql' => 'yii\db\Command',
- 'mysqli' => 'yii\db\Command',
- 'mysql' => 'yii\db\Command',
- 'sqlite' => 'yii\db\sqlite\Command',
- 'sqlite2' => 'yii\db\sqlite\Command',
- 'sqlsrv' => 'yii\db\Command',
- 'oci' => 'yii\db\Command',
- 'mssql' => 'yii\db\Command',
- 'dblib' => 'yii\db\Command',
- 'cubrid' => 'yii\db\Command',
- ];
-
- public $enableSavepoint = true;
-
- public $serverStatusCache = 'cache';
-
- public $serverRetryInterval = 600;
-
- public $enableSlaves = true;
-
- public $slaves = [];
-
- public $slaveConfig = [];
-
- public $masters = [];
-
- public $masterConfig = [];
-
- public $shuffleMasters = true;
-
- public $enableLogging = true;
-
- public $enableProfiling = true;
-
- private $_transaction;
-
- private $_schema;
-
- private $_driverName;
-
- private $_master = false;
-
- private $_slave = false;
-
- private $_queryCacheInfo = [];
-
- private $_quotedTableNames;
-
- private $_quotedColumnNames;
-
- public function getIsActive()
- {
- return $this->pdo !== null;
- }
-
- public function cache(callable $callable, $duration = null, $dependency = null)
- {
- $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
- try {
- $result = call_user_func($callable, $this);
- array_pop($this->_queryCacheInfo);
- return $result;
- } catch (\Exception $e) {
- array_pop($this->_queryCacheInfo);
- throw $e;
- } catch (\Throwable $e) {
- array_pop($this->_queryCacheInfo);
- throw $e;
- }
- }
-
- public function noCache(callable $callable)
- {
- $this->_queryCacheInfo[] = false;
- try {
- $result = call_user_func($callable, $this);
- array_pop($this->_queryCacheInfo);
- return $result;
- } catch (\Exception $e) {
- array_pop($this->_queryCacheInfo);
- throw $e;
- } catch (\Throwable $e) {
- array_pop($this->_queryCacheInfo);
- throw $e;
- }
- }
-
- public function getQueryCacheInfo($duration, $dependency)
- {
- if (!$this->enableQueryCache) {
- return null;
- }
- $info = end($this->_queryCacheInfo);
- if (is_array($info)) {
- if ($duration === null) {
- $duration = $info[0];
- }
- if ($dependency === null) {
- $dependency = $info[1];
- }
- }
- if ($duration === 0 || $duration > 0) {
- if (is_string($this->queryCache) && Yii::$app) {
- $cache = Yii::$app->get($this->queryCache, false);
- } else {
- $cache = $this->queryCache;
- }
- if ($cache instanceof CacheInterface) {
- return [$cache, $duration, $dependency];
- }
- }
- return null;
- }
-
- public function open()
- {
- if ($this->pdo !== null) {
- return;
- }
- if (!empty($this->masters)) {
- $db = $this->getMaster();
- if ($db !== null) {
- $this->pdo = $db->pdo;
- return;
- }
- throw new InvalidConfigException('None of the master DB servers is available.');
- }
- if (empty($this->dsn)) {
- throw new InvalidConfigException('Connection::dsn cannot be empty.');
- }
- $token = 'Opening DB connection: ' . $this->dsn;
- $enableProfiling = $this->enableProfiling;
- try {
- Yii::info($token, __METHOD__);
- if ($enableProfiling) {
- Yii::beginProfile($token, __METHOD__);
- }
- $this->pdo = $this->createPdoInstance();
- $this->initConnection();
- if ($enableProfiling) {
- Yii::endProfile($token, __METHOD__);
- }
- } catch (\PDOException $e) {
- if ($enableProfiling) {
- Yii::endProfile($token, __METHOD__);
- }
- throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
- }
- }
-
- public function close()
- {
- if ($this->_master) {
- if ($this->pdo === $this->_master->pdo) {
- $this->pdo = null;
- }
- $this->_master->close();
- $this->_master = false;
- }
- if ($this->pdo !== null) {
- Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
- $this->pdo = null;
- $this->_schema = null;
- $this->_transaction = null;
- }
- if ($this->_slave) {
- $this->_slave->close();
- $this->_slave = false;
- }
- }
-
- protected function createPdoInstance()
- {
- $pdoClass = $this->pdoClass;
- if ($pdoClass === null) {
- $pdoClass = 'PDO';
- if ($this->_driverName !== null) {
- $driver = $this->_driverName;
- } elseif (($pos = strpos($this->dsn, ':')) !== false) {
- $driver = strtolower(substr($this->dsn, 0, $pos));
- }
- if (isset($driver)) {
- if ($driver === 'mssql' || $driver === 'dblib') {
- $pdoClass = 'yii\db\mssql\PDO';
- } elseif ($driver === 'sqlsrv') {
- $pdoClass = 'yii\db\mssql\SqlsrvPDO';
- }
- }
- }
- $dsn = $this->dsn;
- if (strncmp('sqlite:@', $dsn, 8) === 0) {
- $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
- }
- return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
- }
-
- protected function initConnection()
- {
- $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
- if ($this->driverName !== 'sqlsrv') {
- $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
- }
- }
- if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
- $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
- }
- $this->trigger(self::EVENT_AFTER_OPEN);
- }
-
- public function createCommand($sql = null, $params = [])
- {
- $driver = $this->getDriverName();
- $config = ['class' => 'yii\db\Command'];
- if ($this->commandClass !== $config['class']) {
- $config['class'] = $this->commandClass;
- } elseif (isset($this->commandMap[$driver])) {
- $config = !is_array($this->commandMap[$driver]) ? ['class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
- }
- $config['db'] = $this;
- $config['sql'] = $sql;
-
- $command = Yii::createObject($config);
- return $command->bindValues($params);
- }
-
- public function getTransaction()
- {
- return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
- }
-
- public function beginTransaction($isolationLevel = null)
- {
- $this->open();
- if (($transaction = $this->getTransaction()) === null) {
- $transaction = $this->_transaction = new Transaction(['db' => $this]);
- }
- $transaction->begin($isolationLevel);
- return $transaction;
- }
-
- public function transaction(callable $callback, $isolationLevel = null)
- {
- $transaction = $this->beginTransaction($isolationLevel);
- $level = $transaction->level;
- try {
- $result = call_user_func($callback, $this);
- if ($transaction->isActive && $transaction->level === $level) {
- $transaction->commit();
- }
- } catch (\Exception $e) {
- $this->rollbackTransactionOnLevel($transaction, $level);
- throw $e;
- } catch (\Throwable $e) {
- $this->rollbackTransactionOnLevel($transaction, $level);
- throw $e;
- }
- return $result;
- }
-
- private function rollbackTransactionOnLevel($transaction, $level)
- {
- if ($transaction->isActive && $transaction->level === $level) {
-
- try {
- $transaction->rollBack();
- } catch (\Exception $e) {
- \Yii::error($e, __METHOD__);
-
- }
- }
- }
-
- public function getSchema()
- {
- if ($this->_schema !== null) {
- return $this->_schema;
- }
- $driver = $this->getDriverName();
- if (isset($this->schemaMap[$driver])) {
- $config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
- $config['db'] = $this;
- return $this->_schema = Yii::createObject($config);
- }
- throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
- }
-
- public function getQueryBuilder()
- {
- return $this->getSchema()->getQueryBuilder();
- }
-
- public function setQueryBuilder($value)
- {
- Yii::configure($this->getQueryBuilder(), $value);
- }
-
- public function getTableSchema($name, $refresh = false)
- {
- return $this->getSchema()->getTableSchema($name, $refresh);
- }
-
- public function getLastInsertID($sequenceName = '')
- {
- return $this->getSchema()->getLastInsertID($sequenceName);
- }
-
- public function quoteValue($value)
- {
- return $this->getSchema()->quoteValue($value);
- }
-
- public function quoteTableName($name)
- {
- if (isset($this->_quotedTableNames[$name])) {
- return $this->_quotedTableNames[$name];
- }
- return $this->_quotedTableNames[$name] = $this->getSchema()->quoteTableName($name);
- }
-
- public function quoteColumnName($name)
- {
- if (isset($this->_quotedColumnNames[$name])) {
- return $this->_quotedColumnNames[$name];
- }
- return $this->_quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name);
- }
-
- public function quoteSql($sql)
- {
- return preg_replace_callback(
- '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
- function ($matches) {
- if (isset($matches[3])) {
- return $this->quoteColumnName($matches[3]);
- }
- return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
- },
- $sql
- );
- }
-
- public function getDriverName()
- {
- if ($this->_driverName === null) {
- if (($pos = strpos($this->dsn, ':')) !== false) {
- $this->_driverName = strtolower(substr($this->dsn, 0, $pos));
- } else {
- $this->_driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
- }
- }
- return $this->_driverName;
- }
-
- public function setDriverName($driverName)
- {
- $this->_driverName = strtolower($driverName);
- }
-
- public function getServerVersion()
- {
- return $this->getSchema()->getServerVersion();
- }
-
- public function getSlavePdo($fallbackToMaster = true)
- {
- $db = $this->getSlave(false);
- if ($db === null) {
- return $fallbackToMaster ? $this->getMasterPdo() : null;
- }
- return $db->pdo;
- }
-
- public function getMasterPdo()
- {
- $this->open();
- return $this->pdo;
- }
-
- public function getSlave($fallbackToMaster = true)
- {
- if (!$this->enableSlaves) {
- return $fallbackToMaster ? $this : null;
- }
- if ($this->_slave === false) {
- $this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
- }
- return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
- }
-
- public function getMaster()
- {
- if ($this->_master === false) {
- $this->_master = $this->shuffleMasters
- ? $this->openFromPool($this->masters, $this->masterConfig)
- : $this->openFromPoolSequentially($this->masters, $this->masterConfig);
- }
- return $this->_master;
- }
-
- public function useMaster(callable $callback)
- {
- if ($this->enableSlaves) {
- $this->enableSlaves = false;
- try {
- $result = call_user_func($callback, $this);
- } catch (\Exception $e) {
- $this->enableSlaves = true;
- throw $e;
- } catch (\Throwable $e) {
- $this->enableSlaves = true;
- throw $e;
- }
-
- $this->enableSlaves = true;
- } else {
- $result = call_user_func($callback, $this);
- }
- return $result;
- }
-
- protected function openFromPool(array $pool, array $sharedConfig)
- {
- shuffle($pool);
- return $this->openFromPoolSequentially($pool, $sharedConfig);
- }
-
- protected function openFromPoolSequentially(array $pool, array $sharedConfig)
- {
- if (empty($pool)) {
- return null;
- }
- if (!isset($sharedConfig['class'])) {
- $sharedConfig['class'] = get_class($this);
- }
- $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
- foreach ($pool as $config) {
- $config = array_merge($sharedConfig, $config);
- if (empty($config['dsn'])) {
- throw new InvalidConfigException('The "dsn" option must be specified.');
- }
- $key = [__METHOD__, $config['dsn']];
- if ($cache instanceof CacheInterface && $cache->get($key)) {
-
- continue;
- }
-
- $db = Yii::createObject($config);
- try {
- $db->open();
- return $db;
- } catch (\Exception $e) {
- Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
- if ($cache instanceof CacheInterface) {
-
- $cache->set($key, 1, $this->serverRetryInterval);
- }
- }
- }
- return null;
- }
-
- public function __sleep()
- {
- $fields = (array) $this;
- unset($fields['pdo']);
- unset($fields["\000" . __CLASS__ . "\000" . '_master']);
- unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
- unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
- unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
- return array_keys($fields);
- }
-
- public function __clone()
- {
- parent::__clone();
- $this->_master = false;
- $this->_slave = false;
- $this->_schema = null;
- $this->_transaction = null;
- if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
-
- $this->pdo = null;
- }
- }
- }
|