Connection.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db;
  8. use PDO;
  9. use Yii;
  10. use yii\base\Component;
  11. use yii\base\InvalidConfigException;
  12. use yii\base\NotSupportedException;
  13. use yii\caching\CacheInterface;
  14. /**
  15. * Connection represents a connection to a database via [PDO](https://secure.php.net/manual/en/book.pdo.php).
  16. *
  17. * Connection works together with [[Command]], [[DataReader]] and [[Transaction]]
  18. * to provide data access to various DBMS in a common set of APIs. They are a thin wrapper
  19. * of the [PDO PHP extension](https://secure.php.net/manual/en/book.pdo.php).
  20. *
  21. * Connection supports database replication and read-write splitting. In particular, a Connection component
  22. * can be configured with multiple [[masters]] and [[slaves]]. It will do load balancing and failover by choosing
  23. * appropriate servers. It will also automatically direct read operations to the slaves and write operations to
  24. * the masters.
  25. *
  26. * To establish a DB connection, set [[dsn]], [[username]] and [[password]], and then
  27. * call [[open()]] to connect to the database server. The current state of the connection can be checked using [[$isActive]].
  28. *
  29. * The following example shows how to create a Connection instance and establish
  30. * the DB connection:
  31. *
  32. * ```php
  33. * $connection = new \yii\db\Connection([
  34. * 'dsn' => $dsn,
  35. * 'username' => $username,
  36. * 'password' => $password,
  37. * ]);
  38. * $connection->open();
  39. * ```
  40. *
  41. * After the DB connection is established, one can execute SQL statements like the following:
  42. *
  43. * ```php
  44. * $command = $connection->createCommand('SELECT * FROM post');
  45. * $posts = $command->queryAll();
  46. * $command = $connection->createCommand('UPDATE post SET status=1');
  47. * $command->execute();
  48. * ```
  49. *
  50. * One can also do prepared SQL execution and bind parameters to the prepared SQL.
  51. * When the parameters are coming from user input, you should use this approach
  52. * to prevent SQL injection attacks. The following is an example:
  53. *
  54. * ```php
  55. * $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
  56. * $command->bindValue(':id', $_GET['id']);
  57. * $post = $command->query();
  58. * ```
  59. *
  60. * For more information about how to perform various DB queries, please refer to [[Command]].
  61. *
  62. * If the underlying DBMS supports transactions, you can perform transactional SQL queries
  63. * like the following:
  64. *
  65. * ```php
  66. * $transaction = $connection->beginTransaction();
  67. * try {
  68. * $connection->createCommand($sql1)->execute();
  69. * $connection->createCommand($sql2)->execute();
  70. * // ... executing other SQL statements ...
  71. * $transaction->commit();
  72. * } catch (Exception $e) {
  73. * $transaction->rollBack();
  74. * }
  75. * ```
  76. *
  77. * You also can use shortcut for the above like the following:
  78. *
  79. * ```php
  80. * $connection->transaction(function () {
  81. * $order = new Order($customer);
  82. * $order->save();
  83. * $order->addItems($items);
  84. * });
  85. * ```
  86. *
  87. * If needed you can pass transaction isolation level as a second parameter:
  88. *
  89. * ```php
  90. * $connection->transaction(function (Connection $db) {
  91. * //return $db->...
  92. * }, Transaction::READ_UNCOMMITTED);
  93. * ```
  94. *
  95. * Connection is often used as an application component and configured in the application
  96. * configuration like the following:
  97. *
  98. * ```php
  99. * 'components' => [
  100. * 'db' => [
  101. * 'class' => '\yii\db\Connection',
  102. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  103. * 'username' => 'root',
  104. * 'password' => '',
  105. * 'charset' => 'utf8',
  106. * ],
  107. * ],
  108. * ```
  109. *
  110. * @property string $driverName Name of the DB driver.
  111. * @property-read bool $isActive Whether the DB connection is established. This property is read-only.
  112. * @property-read string $lastInsertID The row ID of the last row inserted, or the last value retrieved from
  113. * the sequence object. This property is read-only.
  114. * @property-read Connection $master The currently active master connection. `null` is returned if there is no
  115. * master available. This property is read-only.
  116. * @property-read PDO $masterPdo The PDO instance for the currently active master connection. This property is
  117. * read-only.
  118. * @property QueryBuilder $queryBuilder The query builder for the current DB connection. Note that the type of
  119. * this property differs in getter and setter. See [[getQueryBuilder()]] and [[setQueryBuilder()]] for details.
  120. * @property-read Schema $schema The schema information for the database opened by this connection. This
  121. * property is read-only.
  122. * @property-read string $serverVersion Server version as a string. This property is read-only.
  123. * @property-read Connection $slave The currently active slave connection. `null` is returned if there is no
  124. * slave available and `$fallbackToMaster` is false. This property is read-only.
  125. * @property-read PDO $slavePdo The PDO instance for the currently active slave connection. `null` is returned
  126. * if no slave connection is available and `$fallbackToMaster` is false. This property is read-only.
  127. * @property-read Transaction|null $transaction The currently active transaction. Null if no active
  128. * transaction. This property is read-only.
  129. *
  130. * @author Qiang Xue <qiang.xue@gmail.com>
  131. * @since 2.0
  132. */
  133. class Connection extends Component
  134. {
  135. /**
  136. * @event yii\base\Event an event that is triggered after a DB connection is established
  137. */
  138. const EVENT_AFTER_OPEN = 'afterOpen';
  139. /**
  140. * @event yii\base\Event an event that is triggered right before a top-level transaction is started
  141. */
  142. const EVENT_BEGIN_TRANSACTION = 'beginTransaction';
  143. /**
  144. * @event yii\base\Event an event that is triggered right after a top-level transaction is committed
  145. */
  146. const EVENT_COMMIT_TRANSACTION = 'commitTransaction';
  147. /**
  148. * @event yii\base\Event an event that is triggered right after a top-level transaction is rolled back
  149. */
  150. const EVENT_ROLLBACK_TRANSACTION = 'rollbackTransaction';
  151. /**
  152. * @var string the Data Source Name, or DSN, contains the information required to connect to the database.
  153. * Please refer to the [PHP manual](https://secure.php.net/manual/en/pdo.construct.php) on
  154. * the format of the DSN string.
  155. *
  156. * For [SQLite](https://secure.php.net/manual/en/ref.pdo-sqlite.connection.php) you may use a [path alias](guide:concept-aliases)
  157. * for specifying the database path, e.g. `sqlite:@app/data/db.sql`.
  158. *
  159. * @see charset
  160. */
  161. public $dsn;
  162. /**
  163. * @var string the username for establishing DB connection. Defaults to `null` meaning no username to use.
  164. */
  165. public $username;
  166. /**
  167. * @var string the password for establishing DB connection. Defaults to `null` meaning no password to use.
  168. */
  169. public $password;
  170. /**
  171. * @var array PDO attributes (name => value) that should be set when calling [[open()]]
  172. * to establish a DB connection. Please refer to the
  173. * [PHP manual](https://secure.php.net/manual/en/pdo.setattribute.php) for
  174. * details about available attributes.
  175. */
  176. public $attributes;
  177. /**
  178. * @var PDO the PHP PDO instance associated with this DB connection.
  179. * This property is mainly managed by [[open()]] and [[close()]] methods.
  180. * When a DB connection is active, this property will represent a PDO instance;
  181. * otherwise, it will be null.
  182. * @see pdoClass
  183. */
  184. public $pdo;
  185. /**
  186. * @var bool whether to enable schema caching.
  187. * Note that in order to enable truly schema caching, a valid cache component as specified
  188. * by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
  189. * @see schemaCacheDuration
  190. * @see schemaCacheExclude
  191. * @see schemaCache
  192. */
  193. public $enableSchemaCache = false;
  194. /**
  195. * @var int number of seconds that table metadata can remain valid in cache.
  196. * Use 0 to indicate that the cached data will never expire.
  197. * @see enableSchemaCache
  198. */
  199. public $schemaCacheDuration = 3600;
  200. /**
  201. * @var array list of tables whose metadata should NOT be cached. Defaults to empty array.
  202. * The table names may contain schema prefix, if any. Do not quote the table names.
  203. * @see enableSchemaCache
  204. */
  205. public $schemaCacheExclude = [];
  206. /**
  207. * @var CacheInterface|string the cache object or the ID of the cache application component that
  208. * is used to cache the table metadata.
  209. * @see enableSchemaCache
  210. */
  211. public $schemaCache = 'cache';
  212. /**
  213. * @var bool whether to enable query caching.
  214. * Note that in order to enable query caching, a valid cache component as specified
  215. * by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true.
  216. * Also, only the results of the queries enclosed within [[cache()]] will be cached.
  217. * @see queryCache
  218. * @see cache()
  219. * @see noCache()
  220. */
  221. public $enableQueryCache = true;
  222. /**
  223. * @var int the default number of seconds that query results can remain valid in cache.
  224. * Defaults to 3600, meaning 3600 seconds, or one hour. Use 0 to indicate that the cached data will never expire.
  225. * The value of this property will be used when [[cache()]] is called without a cache duration.
  226. * @see enableQueryCache
  227. * @see cache()
  228. */
  229. public $queryCacheDuration = 3600;
  230. /**
  231. * @var CacheInterface|string the cache object or the ID of the cache application component
  232. * that is used for query caching.
  233. * @see enableQueryCache
  234. */
  235. public $queryCache = 'cache';
  236. /**
  237. * @var string the charset used for database connection. The property is only used
  238. * for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset
  239. * as configured by the database.
  240. *
  241. * For Oracle Database, the charset must be specified in the [[dsn]], for example for UTF-8 by appending `;charset=UTF-8`
  242. * to the DSN string.
  243. *
  244. * The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to
  245. * specify charset via [[dsn]] like `'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'`.
  246. */
  247. public $charset;
  248. /**
  249. * @var bool whether to turn on prepare emulation. Defaults to false, meaning PDO
  250. * will use the native prepare support if available. For some databases (such as MySQL),
  251. * this may need to be set true so that PDO can emulate the prepare support to bypass
  252. * the buggy native prepare support.
  253. * The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
  254. */
  255. public $emulatePrepare;
  256. /**
  257. * @var string the common prefix or suffix for table names. If a table name is given
  258. * as `{{%TableName}}`, then the percentage character `%` will be replaced with this
  259. * property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
  260. */
  261. public $tablePrefix = '';
  262. /**
  263. * @var array mapping between PDO driver names and [[Schema]] classes.
  264. * The keys of the array are PDO driver names while the values are either the corresponding
  265. * schema class names or configurations. Please refer to [[Yii::createObject()]] for
  266. * details on how to specify a configuration.
  267. *
  268. * This property is mainly used by [[getSchema()]] when fetching the database schema information.
  269. * You normally do not need to set this property unless you want to use your own
  270. * [[Schema]] class to support DBMS that is not supported by Yii.
  271. */
  272. public $schemaMap = [
  273. 'pgsql' => 'yii\db\pgsql\Schema', // PostgreSQL
  274. 'mysqli' => 'yii\db\mysql\Schema', // MySQL
  275. 'mysql' => 'yii\db\mysql\Schema', // MySQL
  276. 'sqlite' => 'yii\db\sqlite\Schema', // sqlite 3
  277. 'sqlite2' => 'yii\db\sqlite\Schema', // sqlite 2
  278. 'sqlsrv' => 'yii\db\mssql\Schema', // newer MSSQL driver on MS Windows hosts
  279. 'oci' => 'yii\db\oci\Schema', // Oracle driver
  280. 'mssql' => 'yii\db\mssql\Schema', // older MSSQL driver on MS Windows hosts
  281. 'dblib' => 'yii\db\mssql\Schema', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
  282. 'cubrid' => 'yii\db\cubrid\Schema', // CUBRID
  283. ];
  284. /**
  285. * @var string Custom PDO wrapper class. If not set, it will use [[PDO]] or [[\yii\db\mssql\PDO]] when MSSQL is used.
  286. * @see pdo
  287. */
  288. public $pdoClass;
  289. /**
  290. * @var string the class used to create new database [[Command]] objects. If you want to extend the [[Command]] class,
  291. * you may configure this property to use your extended version of the class.
  292. * Since version 2.0.14 [[$commandMap]] is used if this property is set to its default value.
  293. * @see createCommand
  294. * @since 2.0.7
  295. * @deprecated since 2.0.14. Use [[$commandMap]] for precise configuration.
  296. */
  297. public $commandClass = 'yii\db\Command';
  298. /**
  299. * @var array mapping between PDO driver names and [[Command]] classes.
  300. * The keys of the array are PDO driver names while the values are either the corresponding
  301. * command class names or configurations. Please refer to [[Yii::createObject()]] for
  302. * details on how to specify a configuration.
  303. *
  304. * This property is mainly used by [[createCommand()]] to create new database [[Command]] objects.
  305. * You normally do not need to set this property unless you want to use your own
  306. * [[Command]] class or support DBMS that is not supported by Yii.
  307. * @since 2.0.14
  308. */
  309. public $commandMap = [
  310. 'pgsql' => 'yii\db\Command', // PostgreSQL
  311. 'mysqli' => 'yii\db\Command', // MySQL
  312. 'mysql' => 'yii\db\Command', // MySQL
  313. 'sqlite' => 'yii\db\sqlite\Command', // sqlite 3
  314. 'sqlite2' => 'yii\db\sqlite\Command', // sqlite 2
  315. 'sqlsrv' => 'yii\db\Command', // newer MSSQL driver on MS Windows hosts
  316. 'oci' => 'yii\db\oci\Command', // Oracle driver
  317. 'mssql' => 'yii\db\Command', // older MSSQL driver on MS Windows hosts
  318. 'dblib' => 'yii\db\Command', // dblib drivers on GNU/Linux (and maybe other OSes) hosts
  319. 'cubrid' => 'yii\db\Command', // CUBRID
  320. ];
  321. /**
  322. * @var bool whether to enable [savepoint](http://en.wikipedia.org/wiki/Savepoint).
  323. * Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
  324. */
  325. public $enableSavepoint = true;
  326. /**
  327. * @var CacheInterface|string|false the cache object or the ID of the cache application component that is used to store
  328. * the health status of the DB servers specified in [[masters]] and [[slaves]].
  329. * This is used only when read/write splitting is enabled or [[masters]] is not empty.
  330. * Set boolean `false` to disabled server status caching.
  331. * @see openFromPoolSequentially() for details about the failover behavior.
  332. * @see serverRetryInterval
  333. */
  334. public $serverStatusCache = 'cache';
  335. /**
  336. * @var int the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]].
  337. * This is used together with [[serverStatusCache]].
  338. */
  339. public $serverRetryInterval = 600;
  340. /**
  341. * @var bool whether to enable read/write splitting by using [[slaves]] to read data.
  342. * Note that if [[slaves]] is empty, read/write splitting will NOT be enabled no matter what value this property takes.
  343. */
  344. public $enableSlaves = true;
  345. /**
  346. * @var array list of slave connection configurations. Each configuration is used to create a slave DB connection.
  347. * When [[enableSlaves]] is true, one of these configurations will be chosen and used to create a DB connection
  348. * for performing read queries only.
  349. * @see enableSlaves
  350. * @see slaveConfig
  351. */
  352. public $slaves = [];
  353. /**
  354. * @var array the configuration that should be merged with every slave configuration listed in [[slaves]].
  355. * For example,
  356. *
  357. * ```php
  358. * [
  359. * 'username' => 'slave',
  360. * 'password' => 'slave',
  361. * 'attributes' => [
  362. * // use a smaller connection timeout
  363. * PDO::ATTR_TIMEOUT => 10,
  364. * ],
  365. * ]
  366. * ```
  367. */
  368. public $slaveConfig = [];
  369. /**
  370. * @var array list of master connection configurations. Each configuration is used to create a master DB connection.
  371. * When [[open()]] is called, one of these configurations will be chosen and used to create a DB connection
  372. * which will be used by this object.
  373. * Note that when this property is not empty, the connection setting (e.g. "dsn", "username") of this object will
  374. * be ignored.
  375. * @see masterConfig
  376. * @see shuffleMasters
  377. */
  378. public $masters = [];
  379. /**
  380. * @var array the configuration that should be merged with every master configuration listed in [[masters]].
  381. * For example,
  382. *
  383. * ```php
  384. * [
  385. * 'username' => 'master',
  386. * 'password' => 'master',
  387. * 'attributes' => [
  388. * // use a smaller connection timeout
  389. * PDO::ATTR_TIMEOUT => 10,
  390. * ],
  391. * ]
  392. * ```
  393. */
  394. public $masterConfig = [];
  395. /**
  396. * @var bool whether to shuffle [[masters]] before getting one.
  397. * @since 2.0.11
  398. * @see masters
  399. */
  400. public $shuffleMasters = true;
  401. /**
  402. * @var bool whether to enable logging of database queries. Defaults to true.
  403. * You may want to disable this option in a production environment to gain performance
  404. * if you do not need the information being logged.
  405. * @since 2.0.12
  406. * @see enableProfiling
  407. */
  408. public $enableLogging = true;
  409. /**
  410. * @var bool whether to enable profiling of opening database connection and database queries. Defaults to true.
  411. * You may want to disable this option in a production environment to gain performance
  412. * if you do not need the information being logged.
  413. * @since 2.0.12
  414. * @see enableLogging
  415. */
  416. public $enableProfiling = true;
  417. /**
  418. * @var bool If the database connected via pdo_dblib is SyBase.
  419. * @since 2.0.38
  420. */
  421. public $isSybase = false;
  422. /**
  423. * @var Transaction the currently active transaction
  424. */
  425. private $_transaction;
  426. /**
  427. * @var Schema the database schema
  428. */
  429. private $_schema;
  430. /**
  431. * @var string driver name
  432. */
  433. private $_driverName;
  434. /**
  435. * @var Connection|false the currently active master connection
  436. */
  437. private $_master = false;
  438. /**
  439. * @var Connection|false the currently active slave connection
  440. */
  441. private $_slave = false;
  442. /**
  443. * @var array query cache parameters for the [[cache()]] calls
  444. */
  445. private $_queryCacheInfo = [];
  446. /**
  447. * @var string[] quoted table name cache for [[quoteTableName()]] calls
  448. */
  449. private $_quotedTableNames;
  450. /**
  451. * @var string[] quoted column name cache for [[quoteColumnName()]] calls
  452. */
  453. private $_quotedColumnNames;
  454. /**
  455. * Returns a value indicating whether the DB connection is established.
  456. * @return bool whether the DB connection is established
  457. */
  458. public function getIsActive()
  459. {
  460. return $this->pdo !== null;
  461. }
  462. /**
  463. * Uses query cache for the queries performed with the callable.
  464. *
  465. * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
  466. * queries performed within the callable will be cached and their results will be fetched from cache if available.
  467. * For example,
  468. *
  469. * ```php
  470. * // The customer will be fetched from cache if available.
  471. * // If not, the query will be made against DB and cached for use next time.
  472. * $customer = $db->cache(function (Connection $db) {
  473. * return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
  474. * });
  475. * ```
  476. *
  477. * Note that query cache is only meaningful for queries that return results. For queries performed with
  478. * [[Command::execute()]], query cache will not be used.
  479. *
  480. * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
  481. * The signature of the callable is `function (Connection $db)`.
  482. * @param int $duration the number of seconds that query results can remain valid in the cache. If this is
  483. * not set, the value of [[queryCacheDuration]] will be used instead.
  484. * Use 0 to indicate that the cached data will never expire.
  485. * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query results.
  486. * @return mixed the return result of the callable
  487. * @throws \Exception|\Throwable if there is any exception during query
  488. * @see enableQueryCache
  489. * @see queryCache
  490. * @see noCache()
  491. */
  492. public function cache(callable $callable, $duration = null, $dependency = null)
  493. {
  494. $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
  495. try {
  496. $result = call_user_func($callable, $this);
  497. array_pop($this->_queryCacheInfo);
  498. return $result;
  499. } catch (\Exception $e) {
  500. array_pop($this->_queryCacheInfo);
  501. throw $e;
  502. } catch (\Throwable $e) {
  503. array_pop($this->_queryCacheInfo);
  504. throw $e;
  505. }
  506. }
  507. /**
  508. * Disables query cache temporarily.
  509. *
  510. * Queries performed within the callable will not use query cache at all. For example,
  511. *
  512. * ```php
  513. * $db->cache(function (Connection $db) {
  514. *
  515. * // ... queries that use query cache ...
  516. *
  517. * return $db->noCache(function (Connection $db) {
  518. * // this query will not use query cache
  519. * return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
  520. * });
  521. * });
  522. * ```
  523. *
  524. * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
  525. * The signature of the callable is `function (Connection $db)`.
  526. * @return mixed the return result of the callable
  527. * @throws \Exception|\Throwable if there is any exception during query
  528. * @see enableQueryCache
  529. * @see queryCache
  530. * @see cache()
  531. */
  532. public function noCache(callable $callable)
  533. {
  534. $this->_queryCacheInfo[] = false;
  535. try {
  536. $result = call_user_func($callable, $this);
  537. array_pop($this->_queryCacheInfo);
  538. return $result;
  539. } catch (\Exception $e) {
  540. array_pop($this->_queryCacheInfo);
  541. throw $e;
  542. } catch (\Throwable $e) {
  543. array_pop($this->_queryCacheInfo);
  544. throw $e;
  545. }
  546. }
  547. /**
  548. * Returns the current query cache information.
  549. * This method is used internally by [[Command]].
  550. * @param int $duration the preferred caching duration. If null, it will be ignored.
  551. * @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
  552. * @return array the current query cache information, or null if query cache is not enabled.
  553. * @internal
  554. */
  555. public function getQueryCacheInfo($duration, $dependency)
  556. {
  557. if (!$this->enableQueryCache) {
  558. return null;
  559. }
  560. $info = end($this->_queryCacheInfo);
  561. if (is_array($info)) {
  562. if ($duration === null) {
  563. $duration = $info[0];
  564. }
  565. if ($dependency === null) {
  566. $dependency = $info[1];
  567. }
  568. }
  569. if ($duration === 0 || $duration > 0) {
  570. if (is_string($this->queryCache) && Yii::$app) {
  571. $cache = Yii::$app->get($this->queryCache, false);
  572. } else {
  573. $cache = $this->queryCache;
  574. }
  575. if ($cache instanceof CacheInterface) {
  576. return [$cache, $duration, $dependency];
  577. }
  578. }
  579. return null;
  580. }
  581. /**
  582. * Establishes a DB connection.
  583. * It does nothing if a DB connection has already been established.
  584. * @throws Exception if connection fails
  585. */
  586. public function open()
  587. {
  588. if ($this->pdo !== null) {
  589. return;
  590. }
  591. if (!empty($this->masters)) {
  592. $db = $this->getMaster();
  593. if ($db !== null) {
  594. $this->pdo = $db->pdo;
  595. return;
  596. }
  597. throw new InvalidConfigException('None of the master DB servers is available.');
  598. }
  599. if (empty($this->dsn)) {
  600. throw new InvalidConfigException('Connection::dsn cannot be empty.');
  601. }
  602. $token = 'Opening DB connection: ' . $this->dsn;
  603. $enableProfiling = $this->enableProfiling;
  604. try {
  605. if ($this->enableLogging) {
  606. Yii::info($token, __METHOD__);
  607. }
  608. if ($enableProfiling) {
  609. Yii::beginProfile($token, __METHOD__);
  610. }
  611. $this->pdo = $this->createPdoInstance();
  612. $this->initConnection();
  613. if ($enableProfiling) {
  614. Yii::endProfile($token, __METHOD__);
  615. }
  616. } catch (\PDOException $e) {
  617. if ($enableProfiling) {
  618. Yii::endProfile($token, __METHOD__);
  619. }
  620. throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
  621. }
  622. }
  623. /**
  624. * Closes the currently active DB connection.
  625. * It does nothing if the connection is already closed.
  626. */
  627. public function close()
  628. {
  629. if ($this->_master) {
  630. if ($this->pdo === $this->_master->pdo) {
  631. $this->pdo = null;
  632. }
  633. $this->_master->close();
  634. $this->_master = false;
  635. }
  636. if ($this->pdo !== null) {
  637. Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
  638. $this->pdo = null;
  639. }
  640. if ($this->_slave) {
  641. $this->_slave->close();
  642. $this->_slave = false;
  643. }
  644. $this->_schema = null;
  645. $this->_transaction = null;
  646. $this->_driverName = null;
  647. $this->_queryCacheInfo = [];
  648. $this->_quotedTableNames = null;
  649. $this->_quotedColumnNames = null;
  650. }
  651. /**
  652. * Creates the PDO instance.
  653. * This method is called by [[open]] to establish a DB connection.
  654. * The default implementation will create a PHP PDO instance.
  655. * You may override this method if the default PDO needs to be adapted for certain DBMS.
  656. * @return PDO the pdo instance
  657. */
  658. protected function createPdoInstance()
  659. {
  660. $pdoClass = $this->pdoClass;
  661. if ($pdoClass === null) {
  662. $pdoClass = 'PDO';
  663. if ($this->_driverName !== null) {
  664. $driver = $this->_driverName;
  665. } elseif (($pos = strpos($this->dsn, ':')) !== false) {
  666. $driver = strtolower(substr($this->dsn, 0, $pos));
  667. }
  668. if (isset($driver)) {
  669. if ($driver === 'mssql') {
  670. $pdoClass = 'yii\db\mssql\PDO';
  671. } elseif ($driver === 'dblib') {
  672. $pdoClass = 'yii\db\mssql\DBLibPDO';
  673. } elseif ($driver === 'sqlsrv') {
  674. $pdoClass = 'yii\db\mssql\SqlsrvPDO';
  675. }
  676. }
  677. }
  678. $dsn = $this->dsn;
  679. if (strncmp('sqlite:@', $dsn, 8) === 0) {
  680. $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
  681. }
  682. return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
  683. }
  684. /**
  685. * Initializes the DB connection.
  686. * This method is invoked right after the DB connection is established.
  687. * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
  688. * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
  689. * It then triggers an [[EVENT_AFTER_OPEN]] event.
  690. */
  691. protected function initConnection()
  692. {
  693. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  694. if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
  695. if ($this->driverName !== 'sqlsrv') {
  696. $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
  697. }
  698. }
  699. if (!$this->isSybase && in_array($this->getDriverName(), ['mssql', 'dblib'], true)) {
  700. $this->pdo->exec('SET ANSI_NULL_DFLT_ON ON');
  701. }
  702. if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
  703. $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
  704. }
  705. $this->trigger(self::EVENT_AFTER_OPEN);
  706. }
  707. /**
  708. * Creates a command for execution.
  709. * @param string $sql the SQL statement to be executed
  710. * @param array $params the parameters to be bound to the SQL statement
  711. * @return Command the DB command
  712. */
  713. public function createCommand($sql = null, $params = [])
  714. {
  715. $driver = $this->getDriverName();
  716. $config = ['class' => 'yii\db\Command'];
  717. if ($this->commandClass !== $config['class']) {
  718. $config['class'] = $this->commandClass;
  719. } elseif (isset($this->commandMap[$driver])) {
  720. $config = !is_array($this->commandMap[$driver]) ? ['class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
  721. }
  722. $config['db'] = $this;
  723. $config['sql'] = $sql;
  724. /** @var Command $command */
  725. $command = Yii::createObject($config);
  726. return $command->bindValues($params);
  727. }
  728. /**
  729. * Returns the currently active transaction.
  730. * @return Transaction|null the currently active transaction. Null if no active transaction.
  731. */
  732. public function getTransaction()
  733. {
  734. return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
  735. }
  736. /**
  737. * Starts a transaction.
  738. * @param string|null $isolationLevel The isolation level to use for this transaction.
  739. * See [[Transaction::begin()]] for details.
  740. * @return Transaction the transaction initiated
  741. */
  742. public function beginTransaction($isolationLevel = null)
  743. {
  744. $this->open();
  745. if (($transaction = $this->getTransaction()) === null) {
  746. $transaction = $this->_transaction = new Transaction(['db' => $this]);
  747. }
  748. $transaction->begin($isolationLevel);
  749. return $transaction;
  750. }
  751. /**
  752. * Executes callback provided in a transaction.
  753. *
  754. * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
  755. * @param string|null $isolationLevel The isolation level to use for this transaction.
  756. * See [[Transaction::begin()]] for details.
  757. * @throws \Exception|\Throwable if there is any exception during query. In this case the transaction will be rolled back.
  758. * @return mixed result of callback function
  759. */
  760. public function transaction(callable $callback, $isolationLevel = null)
  761. {
  762. $transaction = $this->beginTransaction($isolationLevel);
  763. $level = $transaction->level;
  764. try {
  765. $result = call_user_func($callback, $this);
  766. if ($transaction->isActive && $transaction->level === $level) {
  767. $transaction->commit();
  768. }
  769. } catch (\Exception $e) {
  770. $this->rollbackTransactionOnLevel($transaction, $level);
  771. throw $e;
  772. } catch (\Throwable $e) {
  773. $this->rollbackTransactionOnLevel($transaction, $level);
  774. throw $e;
  775. }
  776. return $result;
  777. }
  778. /**
  779. * Rolls back given [[Transaction]] object if it's still active and level match.
  780. * In some cases rollback can fail, so this method is fail safe. Exception thrown
  781. * from rollback will be caught and just logged with [[\Yii::error()]].
  782. * @param Transaction $transaction Transaction object given from [[beginTransaction()]].
  783. * @param int $level Transaction level just after [[beginTransaction()]] call.
  784. */
  785. private function rollbackTransactionOnLevel($transaction, $level)
  786. {
  787. if ($transaction->isActive && $transaction->level === $level) {
  788. // https://github.com/yiisoft/yii2/pull/13347
  789. try {
  790. $transaction->rollBack();
  791. } catch (\Exception $e) {
  792. \Yii::error($e, __METHOD__);
  793. // hide this exception to be able to continue throwing original exception outside
  794. }
  795. }
  796. }
  797. /**
  798. * Returns the schema information for the database opened by this connection.
  799. * @return Schema the schema information for the database opened by this connection.
  800. * @throws NotSupportedException if there is no support for the current driver type
  801. */
  802. public function getSchema()
  803. {
  804. if ($this->_schema !== null) {
  805. return $this->_schema;
  806. }
  807. $driver = $this->getDriverName();
  808. if (isset($this->schemaMap[$driver])) {
  809. $config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
  810. $config['db'] = $this;
  811. return $this->_schema = Yii::createObject($config);
  812. }
  813. throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
  814. }
  815. /**
  816. * Returns the query builder for the current DB connection.
  817. * @return QueryBuilder the query builder for the current DB connection.
  818. */
  819. public function getQueryBuilder()
  820. {
  821. return $this->getSchema()->getQueryBuilder();
  822. }
  823. /**
  824. * Can be used to set [[QueryBuilder]] configuration via Connection configuration array.
  825. *
  826. * @param array $value the [[QueryBuilder]] properties to be configured.
  827. * @since 2.0.14
  828. */
  829. public function setQueryBuilder($value)
  830. {
  831. Yii::configure($this->getQueryBuilder(), $value);
  832. }
  833. /**
  834. * Obtains the schema information for the named table.
  835. * @param string $name table name.
  836. * @param bool $refresh whether to reload the table schema even if it is found in the cache.
  837. * @return TableSchema table schema information. Null if the named table does not exist.
  838. */
  839. public function getTableSchema($name, $refresh = false)
  840. {
  841. return $this->getSchema()->getTableSchema($name, $refresh);
  842. }
  843. /**
  844. * Returns the ID of the last inserted row or sequence value.
  845. * @param string $sequenceName name of the sequence object (required by some DBMS)
  846. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  847. * @see https://secure.php.net/manual/en/pdo.lastinsertid.php
  848. */
  849. public function getLastInsertID($sequenceName = '')
  850. {
  851. return $this->getSchema()->getLastInsertID($sequenceName);
  852. }
  853. /**
  854. * Quotes a string value for use in a query.
  855. * Note that if the parameter is not a string, it will be returned without change.
  856. * @param string $value string to be quoted
  857. * @return string the properly quoted string
  858. * @see https://secure.php.net/manual/en/pdo.quote.php
  859. */
  860. public function quoteValue($value)
  861. {
  862. return $this->getSchema()->quoteValue($value);
  863. }
  864. /**
  865. * Quotes a table name for use in a query.
  866. * If the table name contains schema prefix, the prefix will also be properly quoted.
  867. * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
  868. * then this method will do nothing.
  869. * @param string $name table name
  870. * @return string the properly quoted table name
  871. */
  872. public function quoteTableName($name)
  873. {
  874. if (isset($this->_quotedTableNames[$name])) {
  875. return $this->_quotedTableNames[$name];
  876. }
  877. return $this->_quotedTableNames[$name] = $this->getSchema()->quoteTableName($name);
  878. }
  879. /**
  880. * Quotes a column name for use in a query.
  881. * If the column name contains prefix, the prefix will also be properly quoted.
  882. * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
  883. * then this method will do nothing.
  884. * @param string $name column name
  885. * @return string the properly quoted column name
  886. */
  887. public function quoteColumnName($name)
  888. {
  889. if (isset($this->_quotedColumnNames[$name])) {
  890. return $this->_quotedColumnNames[$name];
  891. }
  892. return $this->_quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name);
  893. }
  894. /**
  895. * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
  896. * Tokens enclosed within double curly brackets are treated as table names, while
  897. * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
  898. * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
  899. * with [[tablePrefix]].
  900. * @param string $sql the SQL to be quoted
  901. * @return string the quoted SQL
  902. */
  903. public function quoteSql($sql)
  904. {
  905. return preg_replace_callback(
  906. '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
  907. function ($matches) {
  908. if (isset($matches[3])) {
  909. return $this->quoteColumnName($matches[3]);
  910. }
  911. return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
  912. },
  913. $sql
  914. );
  915. }
  916. /**
  917. * Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly
  918. * by an end user.
  919. * @return string name of the DB driver
  920. */
  921. public function getDriverName()
  922. {
  923. if ($this->_driverName === null) {
  924. if (($pos = strpos($this->dsn, ':')) !== false) {
  925. $this->_driverName = strtolower(substr($this->dsn, 0, $pos));
  926. } else {
  927. $this->_driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
  928. }
  929. }
  930. return $this->_driverName;
  931. }
  932. /**
  933. * Changes the current driver name.
  934. * @param string $driverName name of the DB driver
  935. */
  936. public function setDriverName($driverName)
  937. {
  938. $this->_driverName = strtolower($driverName);
  939. }
  940. /**
  941. * Returns a server version as a string comparable by [[\version_compare()]].
  942. * @return string server version as a string.
  943. * @since 2.0.14
  944. */
  945. public function getServerVersion()
  946. {
  947. return $this->getSchema()->getServerVersion();
  948. }
  949. /**
  950. * Returns the PDO instance for the currently active slave connection.
  951. * When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance
  952. * will be returned by this method.
  953. * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
  954. * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
  955. * is available and `$fallbackToMaster` is false.
  956. */
  957. public function getSlavePdo($fallbackToMaster = true)
  958. {
  959. $db = $this->getSlave(false);
  960. if ($db === null) {
  961. return $fallbackToMaster ? $this->getMasterPdo() : null;
  962. }
  963. return $db->pdo;
  964. }
  965. /**
  966. * Returns the PDO instance for the currently active master connection.
  967. * This method will open the master DB connection and then return [[pdo]].
  968. * @return PDO the PDO instance for the currently active master connection.
  969. */
  970. public function getMasterPdo()
  971. {
  972. $this->open();
  973. return $this->pdo;
  974. }
  975. /**
  976. * Returns the currently active slave connection.
  977. * If this method is called for the first time, it will try to open a slave connection when [[enableSlaves]] is true.
  978. * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection available.
  979. * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
  980. * `$fallbackToMaster` is false.
  981. */
  982. public function getSlave($fallbackToMaster = true)
  983. {
  984. if (!$this->enableSlaves) {
  985. return $fallbackToMaster ? $this : null;
  986. }
  987. if ($this->_slave === false) {
  988. $this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
  989. }
  990. return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
  991. }
  992. /**
  993. * Returns the currently active master connection.
  994. * If this method is called for the first time, it will try to open a master connection.
  995. * @return Connection the currently active master connection. `null` is returned if there is no master available.
  996. * @since 2.0.11
  997. */
  998. public function getMaster()
  999. {
  1000. if ($this->_master === false) {
  1001. $this->_master = $this->shuffleMasters
  1002. ? $this->openFromPool($this->masters, $this->masterConfig)
  1003. : $this->openFromPoolSequentially($this->masters, $this->masterConfig);
  1004. }
  1005. return $this->_master;
  1006. }
  1007. /**
  1008. * Executes the provided callback by using the master connection.
  1009. *
  1010. * This method is provided so that you can temporarily force using the master connection to perform
  1011. * DB operations even if they are read queries. For example,
  1012. *
  1013. * ```php
  1014. * $result = $db->useMaster(function ($db) {
  1015. * return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
  1016. * });
  1017. * ```
  1018. *
  1019. * @param callable $callback a PHP callable to be executed by this method. Its signature is
  1020. * `function (Connection $db)`. Its return value will be returned by this method.
  1021. * @return mixed the return value of the callback
  1022. * @throws \Exception|\Throwable if there is any exception thrown from the callback
  1023. */
  1024. public function useMaster(callable $callback)
  1025. {
  1026. if ($this->enableSlaves) {
  1027. $this->enableSlaves = false;
  1028. try {
  1029. $result = call_user_func($callback, $this);
  1030. } catch (\Exception $e) {
  1031. $this->enableSlaves = true;
  1032. throw $e;
  1033. } catch (\Throwable $e) {
  1034. $this->enableSlaves = true;
  1035. throw $e;
  1036. }
  1037. // TODO: use "finally" keyword when miminum required PHP version is >= 5.5
  1038. $this->enableSlaves = true;
  1039. } else {
  1040. $result = call_user_func($callback, $this);
  1041. }
  1042. return $result;
  1043. }
  1044. /**
  1045. * Opens the connection to a server in the pool.
  1046. *
  1047. * This method implements load balancing and failover among the given list of the servers.
  1048. * Connections will be tried in random order.
  1049. * For details about the failover behavior, see [[openFromPoolSequentially]].
  1050. *
  1051. * @param array $pool the list of connection configurations in the server pool
  1052. * @param array $sharedConfig the configuration common to those given in `$pool`.
  1053. * @return Connection the opened DB connection, or `null` if no server is available
  1054. * @throws InvalidConfigException if a configuration does not specify "dsn"
  1055. * @see openFromPoolSequentially
  1056. */
  1057. protected function openFromPool(array $pool, array $sharedConfig)
  1058. {
  1059. shuffle($pool);
  1060. return $this->openFromPoolSequentially($pool, $sharedConfig);
  1061. }
  1062. /**
  1063. * Opens the connection to a server in the pool.
  1064. *
  1065. * This method implements failover among the given list of servers.
  1066. * Connections will be tried in sequential order. The first successful connection will return.
  1067. *
  1068. * If [[serverStatusCache]] is configured, this method will cache information about
  1069. * unreachable servers and does not try to connect to these for the time configured in [[serverRetryInterval]].
  1070. * This helps to keep the application stable when some servers are unavailable. Avoiding
  1071. * connection attempts to unavailable servers saves time when the connection attempts fail due to timeout.
  1072. *
  1073. * If none of the servers are available the status cache is ignored and connection attempts are made to all
  1074. * servers (Since version 2.0.35). This is to avoid downtime when all servers are unavailable for a short time.
  1075. * After a successful connection attempt the server is marked as available again.
  1076. *
  1077. * @param array $pool the list of connection configurations in the server pool
  1078. * @param array $sharedConfig the configuration common to those given in `$pool`.
  1079. * @return Connection the opened DB connection, or `null` if no server is available
  1080. * @throws InvalidConfigException if a configuration does not specify "dsn"
  1081. * @since 2.0.11
  1082. * @see openFromPool
  1083. * @see serverStatusCache
  1084. */
  1085. protected function openFromPoolSequentially(array $pool, array $sharedConfig)
  1086. {
  1087. if (empty($pool)) {
  1088. return null;
  1089. }
  1090. if (!isset($sharedConfig['class'])) {
  1091. $sharedConfig['class'] = get_class($this);
  1092. }
  1093. $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
  1094. foreach ($pool as $i => $config) {
  1095. $pool[$i] = $config = array_merge($sharedConfig, $config);
  1096. if (empty($config['dsn'])) {
  1097. throw new InvalidConfigException('The "dsn" option must be specified.');
  1098. }
  1099. $key = [__METHOD__, $config['dsn']];
  1100. if ($cache instanceof CacheInterface && $cache->get($key)) {
  1101. // should not try this dead server now
  1102. continue;
  1103. }
  1104. /* @var $db Connection */
  1105. $db = Yii::createObject($config);
  1106. try {
  1107. $db->open();
  1108. return $db;
  1109. } catch (\Exception $e) {
  1110. Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
  1111. if ($cache instanceof CacheInterface) {
  1112. // mark this server as dead and only retry it after the specified interval
  1113. $cache->set($key, 1, $this->serverRetryInterval);
  1114. }
  1115. // exclude server from retry below
  1116. unset($pool[$i]);
  1117. }
  1118. }
  1119. if ($cache instanceof CacheInterface) {
  1120. // if server status cache is enabled and no server is available
  1121. // ignore the cache and try to connect anyway
  1122. // $pool now only contains servers we did not already try in the loop above
  1123. foreach ($pool as $config) {
  1124. /* @var $db Connection */
  1125. $db = Yii::createObject($config);
  1126. try {
  1127. $db->open();
  1128. } catch (\Exception $e) {
  1129. Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
  1130. continue;
  1131. }
  1132. // mark this server as available again after successful connection
  1133. $cache->delete([__METHOD__, $config['dsn']]);
  1134. return $db;
  1135. }
  1136. }
  1137. return null;
  1138. }
  1139. /**
  1140. * Close the connection before serializing.
  1141. * @return array
  1142. */
  1143. public function __sleep()
  1144. {
  1145. $fields = (array) $this;
  1146. unset($fields['pdo']);
  1147. unset($fields["\000" . __CLASS__ . "\000" . '_master']);
  1148. unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
  1149. unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
  1150. unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
  1151. return array_keys($fields);
  1152. }
  1153. /**
  1154. * Reset the connection after cloning.
  1155. */
  1156. public function __clone()
  1157. {
  1158. parent::__clone();
  1159. $this->_master = false;
  1160. $this->_slave = false;
  1161. $this->_schema = null;
  1162. $this->_transaction = null;
  1163. if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
  1164. // reset PDO connection, unless its sqlite in-memory, which can only have one connection
  1165. $this->pdo = null;
  1166. }
  1167. }
  1168. }