Connection.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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 array An array of [[setQueryBuilder()]] calls, holding the passed arguments.
  424. * Is used to restore a QueryBuilder configuration after the connection close/open cycle.
  425. *
  426. * @see restoreQueryBuilderConfiguration()
  427. */
  428. private $_queryBuilderConfigurations = [];
  429. /**
  430. * @var Transaction the currently active transaction
  431. */
  432. private $_transaction;
  433. /**
  434. * @var Schema the database schema
  435. */
  436. private $_schema;
  437. /**
  438. * @var string driver name
  439. */
  440. private $_driverName;
  441. /**
  442. * @var Connection|false the currently active master connection
  443. */
  444. private $_master = false;
  445. /**
  446. * @var Connection|false the currently active slave connection
  447. */
  448. private $_slave = false;
  449. /**
  450. * @var array query cache parameters for the [[cache()]] calls
  451. */
  452. private $_queryCacheInfo = [];
  453. /**
  454. * @var string[] quoted table name cache for [[quoteTableName()]] calls
  455. */
  456. private $_quotedTableNames;
  457. /**
  458. * @var string[] quoted column name cache for [[quoteColumnName()]] calls
  459. */
  460. private $_quotedColumnNames;
  461. /**
  462. * Returns a value indicating whether the DB connection is established.
  463. * @return bool whether the DB connection is established
  464. */
  465. public function getIsActive()
  466. {
  467. return $this->pdo !== null;
  468. }
  469. /**
  470. * Uses query cache for the queries performed with the callable.
  471. *
  472. * When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache),
  473. * queries performed within the callable will be cached and their results will be fetched from cache if available.
  474. * For example,
  475. *
  476. * ```php
  477. * // The customer will be fetched from cache if available.
  478. * // If not, the query will be made against DB and cached for use next time.
  479. * $customer = $db->cache(function (Connection $db) {
  480. * return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
  481. * });
  482. * ```
  483. *
  484. * Note that query cache is only meaningful for queries that return results. For queries performed with
  485. * [[Command::execute()]], query cache will not be used.
  486. *
  487. * @param callable $callable a PHP callable that contains DB queries which will make use of query cache.
  488. * The signature of the callable is `function (Connection $db)`.
  489. * @param int $duration the number of seconds that query results can remain valid in the cache. If this is
  490. * not set, the value of [[queryCacheDuration]] will be used instead.
  491. * Use 0 to indicate that the cached data will never expire.
  492. * @param \yii\caching\Dependency $dependency the cache dependency associated with the cached query results.
  493. * @return mixed the return result of the callable
  494. * @throws \Exception|\Throwable if there is any exception during query
  495. * @see enableQueryCache
  496. * @see queryCache
  497. * @see noCache()
  498. */
  499. public function cache(callable $callable, $duration = null, $dependency = null)
  500. {
  501. $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
  502. try {
  503. $result = call_user_func($callable, $this);
  504. array_pop($this->_queryCacheInfo);
  505. return $result;
  506. } catch (\Exception $e) {
  507. array_pop($this->_queryCacheInfo);
  508. throw $e;
  509. } catch (\Throwable $e) {
  510. array_pop($this->_queryCacheInfo);
  511. throw $e;
  512. }
  513. }
  514. /**
  515. * Disables query cache temporarily.
  516. *
  517. * Queries performed within the callable will not use query cache at all. For example,
  518. *
  519. * ```php
  520. * $db->cache(function (Connection $db) {
  521. *
  522. * // ... queries that use query cache ...
  523. *
  524. * return $db->noCache(function (Connection $db) {
  525. * // this query will not use query cache
  526. * return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
  527. * });
  528. * });
  529. * ```
  530. *
  531. * @param callable $callable a PHP callable that contains DB queries which should not use query cache.
  532. * The signature of the callable is `function (Connection $db)`.
  533. * @return mixed the return result of the callable
  534. * @throws \Exception|\Throwable if there is any exception during query
  535. * @see enableQueryCache
  536. * @see queryCache
  537. * @see cache()
  538. */
  539. public function noCache(callable $callable)
  540. {
  541. $this->_queryCacheInfo[] = false;
  542. try {
  543. $result = call_user_func($callable, $this);
  544. array_pop($this->_queryCacheInfo);
  545. return $result;
  546. } catch (\Exception $e) {
  547. array_pop($this->_queryCacheInfo);
  548. throw $e;
  549. } catch (\Throwable $e) {
  550. array_pop($this->_queryCacheInfo);
  551. throw $e;
  552. }
  553. }
  554. /**
  555. * Returns the current query cache information.
  556. * This method is used internally by [[Command]].
  557. * @param int $duration the preferred caching duration. If null, it will be ignored.
  558. * @param \yii\caching\Dependency $dependency the preferred caching dependency. If null, it will be ignored.
  559. * @return array the current query cache information, or null if query cache is not enabled.
  560. * @internal
  561. */
  562. public function getQueryCacheInfo($duration, $dependency)
  563. {
  564. if (!$this->enableQueryCache) {
  565. return null;
  566. }
  567. $info = end($this->_queryCacheInfo);
  568. if (is_array($info)) {
  569. if ($duration === null) {
  570. $duration = $info[0];
  571. }
  572. if ($dependency === null) {
  573. $dependency = $info[1];
  574. }
  575. }
  576. if ($duration === 0 || $duration > 0) {
  577. if (is_string($this->queryCache) && Yii::$app) {
  578. $cache = Yii::$app->get($this->queryCache, false);
  579. } else {
  580. $cache = $this->queryCache;
  581. }
  582. if ($cache instanceof CacheInterface) {
  583. return [$cache, $duration, $dependency];
  584. }
  585. }
  586. return null;
  587. }
  588. /**
  589. * Establishes a DB connection.
  590. * It does nothing if a DB connection has already been established.
  591. * @throws Exception if connection fails
  592. */
  593. public function open()
  594. {
  595. if ($this->pdo !== null) {
  596. return;
  597. }
  598. if (!empty($this->masters)) {
  599. $db = $this->getMaster();
  600. if ($db !== null) {
  601. $this->pdo = $db->pdo;
  602. return;
  603. }
  604. throw new InvalidConfigException('None of the master DB servers is available.');
  605. }
  606. if (empty($this->dsn)) {
  607. throw new InvalidConfigException('Connection::dsn cannot be empty.');
  608. }
  609. $token = 'Opening DB connection: ' . $this->dsn;
  610. $enableProfiling = $this->enableProfiling;
  611. try {
  612. if ($this->enableLogging) {
  613. Yii::info($token, __METHOD__);
  614. }
  615. if ($enableProfiling) {
  616. Yii::beginProfile($token, __METHOD__);
  617. }
  618. $this->pdo = $this->createPdoInstance();
  619. $this->initConnection();
  620. if ($enableProfiling) {
  621. Yii::endProfile($token, __METHOD__);
  622. }
  623. } catch (\PDOException $e) {
  624. if ($enableProfiling) {
  625. Yii::endProfile($token, __METHOD__);
  626. }
  627. throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
  628. }
  629. }
  630. /**
  631. * Closes the currently active DB connection.
  632. * It does nothing if the connection is already closed.
  633. */
  634. public function close()
  635. {
  636. if ($this->_master) {
  637. if ($this->pdo === $this->_master->pdo) {
  638. $this->pdo = null;
  639. }
  640. $this->_master->close();
  641. $this->_master = false;
  642. }
  643. if ($this->pdo !== null) {
  644. Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
  645. $this->pdo = null;
  646. }
  647. if ($this->_slave) {
  648. $this->_slave->close();
  649. $this->_slave = false;
  650. }
  651. $this->_schema = null;
  652. $this->_transaction = null;
  653. $this->_driverName = null;
  654. $this->_queryCacheInfo = [];
  655. $this->_quotedTableNames = null;
  656. $this->_quotedColumnNames = null;
  657. }
  658. /**
  659. * Creates the PDO instance.
  660. * This method is called by [[open]] to establish a DB connection.
  661. * The default implementation will create a PHP PDO instance.
  662. * You may override this method if the default PDO needs to be adapted for certain DBMS.
  663. * @return PDO the pdo instance
  664. */
  665. protected function createPdoInstance()
  666. {
  667. $pdoClass = $this->pdoClass;
  668. if ($pdoClass === null) {
  669. $driver = null;
  670. if ($this->_driverName !== null) {
  671. $driver = $this->_driverName;
  672. } elseif (($pos = strpos($this->dsn, ':')) !== false) {
  673. $driver = strtolower(substr($this->dsn, 0, $pos));
  674. }
  675. switch ($driver) {
  676. case 'mssql':
  677. $pdoClass = 'yii\db\mssql\PDO';
  678. break;
  679. case 'dblib':
  680. $pdoClass = 'yii\db\mssql\DBLibPDO';
  681. break;
  682. case 'sqlsrv':
  683. $pdoClass = 'yii\db\mssql\SqlsrvPDO';
  684. break;
  685. default:
  686. $pdoClass = 'PDO';
  687. }
  688. }
  689. $dsn = $this->dsn;
  690. if (strncmp('sqlite:@', $dsn, 8) === 0) {
  691. $dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
  692. }
  693. return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
  694. }
  695. /**
  696. * Initializes the DB connection.
  697. * This method is invoked right after the DB connection is established.
  698. * The default implementation turns on `PDO::ATTR_EMULATE_PREPARES`
  699. * if [[emulatePrepare]] is true, and sets the database [[charset]] if it is not empty.
  700. * It then triggers an [[EVENT_AFTER_OPEN]] event.
  701. */
  702. protected function initConnection()
  703. {
  704. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  705. if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
  706. if ($this->driverName !== 'sqlsrv') {
  707. $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
  708. }
  709. }
  710. if (!$this->isSybase && in_array($this->getDriverName(), ['mssql', 'dblib'], true)) {
  711. $this->pdo->exec('SET ANSI_NULL_DFLT_ON ON');
  712. }
  713. if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
  714. $this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
  715. }
  716. $this->trigger(self::EVENT_AFTER_OPEN);
  717. }
  718. /**
  719. * Creates a command for execution.
  720. * @param string $sql the SQL statement to be executed
  721. * @param array $params the parameters to be bound to the SQL statement
  722. * @return Command the DB command
  723. */
  724. public function createCommand($sql = null, $params = [])
  725. {
  726. $driver = $this->getDriverName();
  727. $config = ['class' => 'yii\db\Command'];
  728. if ($this->commandClass !== $config['class']) {
  729. $config['class'] = $this->commandClass;
  730. } elseif (isset($this->commandMap[$driver])) {
  731. $config = !is_array($this->commandMap[$driver]) ? ['class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
  732. }
  733. $config['db'] = $this;
  734. $config['sql'] = $sql;
  735. /** @var Command $command */
  736. $command = Yii::createObject($config);
  737. return $command->bindValues($params);
  738. }
  739. /**
  740. * Returns the currently active transaction.
  741. * @return Transaction|null the currently active transaction. Null if no active transaction.
  742. */
  743. public function getTransaction()
  744. {
  745. return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
  746. }
  747. /**
  748. * Starts a transaction.
  749. * @param string|null $isolationLevel The isolation level to use for this transaction.
  750. * See [[Transaction::begin()]] for details.
  751. * @return Transaction the transaction initiated
  752. */
  753. public function beginTransaction($isolationLevel = null)
  754. {
  755. $this->open();
  756. if (($transaction = $this->getTransaction()) === null) {
  757. $transaction = $this->_transaction = new Transaction(['db' => $this]);
  758. }
  759. $transaction->begin($isolationLevel);
  760. return $transaction;
  761. }
  762. /**
  763. * Executes callback provided in a transaction.
  764. *
  765. * @param callable $callback a valid PHP callback that performs the job. Accepts connection instance as parameter.
  766. * @param string|null $isolationLevel The isolation level to use for this transaction.
  767. * See [[Transaction::begin()]] for details.
  768. * @throws \Exception|\Throwable if there is any exception during query. In this case the transaction will be rolled back.
  769. * @return mixed result of callback function
  770. */
  771. public function transaction(callable $callback, $isolationLevel = null)
  772. {
  773. $transaction = $this->beginTransaction($isolationLevel);
  774. $level = $transaction->level;
  775. try {
  776. $result = call_user_func($callback, $this);
  777. if ($transaction->isActive && $transaction->level === $level) {
  778. $transaction->commit();
  779. }
  780. } catch (\Exception $e) {
  781. $this->rollbackTransactionOnLevel($transaction, $level);
  782. throw $e;
  783. } catch (\Throwable $e) {
  784. $this->rollbackTransactionOnLevel($transaction, $level);
  785. throw $e;
  786. }
  787. return $result;
  788. }
  789. /**
  790. * Rolls back given [[Transaction]] object if it's still active and level match.
  791. * In some cases rollback can fail, so this method is fail safe. Exception thrown
  792. * from rollback will be caught and just logged with [[\Yii::error()]].
  793. * @param Transaction $transaction Transaction object given from [[beginTransaction()]].
  794. * @param int $level Transaction level just after [[beginTransaction()]] call.
  795. */
  796. private function rollbackTransactionOnLevel($transaction, $level)
  797. {
  798. if ($transaction->isActive && $transaction->level === $level) {
  799. // https://github.com/yiisoft/yii2/pull/13347
  800. try {
  801. $transaction->rollBack();
  802. } catch (\Exception $e) {
  803. \Yii::error($e, __METHOD__);
  804. // hide this exception to be able to continue throwing original exception outside
  805. }
  806. }
  807. }
  808. /**
  809. * Returns the schema information for the database opened by this connection.
  810. * @return Schema the schema information for the database opened by this connection.
  811. * @throws NotSupportedException if there is no support for the current driver type
  812. */
  813. public function getSchema()
  814. {
  815. if ($this->_schema !== null) {
  816. return $this->_schema;
  817. }
  818. $driver = $this->getDriverName();
  819. if (isset($this->schemaMap[$driver])) {
  820. $config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
  821. $config['db'] = $this;
  822. $this->_schema = Yii::createObject($config);
  823. $this->restoreQueryBuilderConfiguration();
  824. return $this->_schema;
  825. }
  826. throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
  827. }
  828. /**
  829. * Returns the query builder for the current DB connection.
  830. * @return QueryBuilder the query builder for the current DB connection.
  831. */
  832. public function getQueryBuilder()
  833. {
  834. return $this->getSchema()->getQueryBuilder();
  835. }
  836. /**
  837. * Can be used to set [[QueryBuilder]] configuration via Connection configuration array.
  838. *
  839. * @param array $value the [[QueryBuilder]] properties to be configured.
  840. * @since 2.0.14
  841. */
  842. public function setQueryBuilder($value)
  843. {
  844. Yii::configure($this->getQueryBuilder(), $value);
  845. $this->_queryBuilderConfigurations[] = $value;
  846. }
  847. /**
  848. * Restores custom QueryBuilder configuration after the connection close/open cycle
  849. */
  850. private function restoreQueryBuilderConfiguration()
  851. {
  852. if ($this->_queryBuilderConfigurations === []) {
  853. return;
  854. }
  855. $queryBuilderConfigurations = $this->_queryBuilderConfigurations;
  856. $this->_queryBuilderConfigurations = [];
  857. foreach ($queryBuilderConfigurations as $queryBuilderConfiguration) {
  858. $this->setQueryBuilder($queryBuilderConfiguration);
  859. }
  860. }
  861. /**
  862. * Obtains the schema information for the named table.
  863. * @param string $name table name.
  864. * @param bool $refresh whether to reload the table schema even if it is found in the cache.
  865. * @return TableSchema|null table schema information. Null if the named table does not exist.
  866. */
  867. public function getTableSchema($name, $refresh = false)
  868. {
  869. return $this->getSchema()->getTableSchema($name, $refresh);
  870. }
  871. /**
  872. * Returns the ID of the last inserted row or sequence value.
  873. * @param string $sequenceName name of the sequence object (required by some DBMS)
  874. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  875. * @see https://secure.php.net/manual/en/pdo.lastinsertid.php
  876. */
  877. public function getLastInsertID($sequenceName = '')
  878. {
  879. return $this->getSchema()->getLastInsertID($sequenceName);
  880. }
  881. /**
  882. * Quotes a string value for use in a query.
  883. * Note that if the parameter is not a string, it will be returned without change.
  884. * @param string $value string to be quoted
  885. * @return string the properly quoted string
  886. * @see https://secure.php.net/manual/en/pdo.quote.php
  887. */
  888. public function quoteValue($value)
  889. {
  890. return $this->getSchema()->quoteValue($value);
  891. }
  892. /**
  893. * Quotes a table name for use in a query.
  894. * If the table name contains schema prefix, the prefix will also be properly quoted.
  895. * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
  896. * then this method will do nothing.
  897. * @param string $name table name
  898. * @return string the properly quoted table name
  899. */
  900. public function quoteTableName($name)
  901. {
  902. if (isset($this->_quotedTableNames[$name])) {
  903. return $this->_quotedTableNames[$name];
  904. }
  905. return $this->_quotedTableNames[$name] = $this->getSchema()->quoteTableName($name);
  906. }
  907. /**
  908. * Quotes a column name for use in a query.
  909. * If the column name contains prefix, the prefix will also be properly quoted.
  910. * If the column name is already quoted or contains special characters including '(', '[[' and '{{',
  911. * then this method will do nothing.
  912. * @param string $name column name
  913. * @return string the properly quoted column name
  914. */
  915. public function quoteColumnName($name)
  916. {
  917. if (isset($this->_quotedColumnNames[$name])) {
  918. return $this->_quotedColumnNames[$name];
  919. }
  920. return $this->_quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name);
  921. }
  922. /**
  923. * Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
  924. * Tokens enclosed within double curly brackets are treated as table names, while
  925. * tokens enclosed within double square brackets are column names. They will be quoted accordingly.
  926. * Also, the percentage character "%" at the beginning or ending of a table name will be replaced
  927. * with [[tablePrefix]].
  928. * @param string $sql the SQL to be quoted
  929. * @return string the quoted SQL
  930. */
  931. public function quoteSql($sql)
  932. {
  933. return preg_replace_callback(
  934. '/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
  935. function ($matches) {
  936. if (isset($matches[3])) {
  937. return $this->quoteColumnName($matches[3]);
  938. }
  939. return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
  940. },
  941. $sql
  942. );
  943. }
  944. /**
  945. * Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly
  946. * by an end user.
  947. * @return string name of the DB driver
  948. */
  949. public function getDriverName()
  950. {
  951. if ($this->_driverName === null) {
  952. if (($pos = strpos($this->dsn, ':')) !== false) {
  953. $this->_driverName = strtolower(substr($this->dsn, 0, $pos));
  954. } else {
  955. $this->_driverName = strtolower($this->getSlavePdo()->getAttribute(PDO::ATTR_DRIVER_NAME));
  956. }
  957. }
  958. return $this->_driverName;
  959. }
  960. /**
  961. * Changes the current driver name.
  962. * @param string $driverName name of the DB driver
  963. */
  964. public function setDriverName($driverName)
  965. {
  966. $this->_driverName = strtolower($driverName);
  967. }
  968. /**
  969. * Returns a server version as a string comparable by [[\version_compare()]].
  970. * @return string server version as a string.
  971. * @since 2.0.14
  972. */
  973. public function getServerVersion()
  974. {
  975. return $this->getSchema()->getServerVersion();
  976. }
  977. /**
  978. * Returns the PDO instance for the currently active slave connection.
  979. * When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance
  980. * will be returned by this method.
  981. * @param bool $fallbackToMaster whether to return a master PDO in case none of the slave connections is available.
  982. * @return PDO the PDO instance for the currently active slave connection. `null` is returned if no slave connection
  983. * is available and `$fallbackToMaster` is false.
  984. */
  985. public function getSlavePdo($fallbackToMaster = true)
  986. {
  987. $db = $this->getSlave(false);
  988. if ($db === null) {
  989. return $fallbackToMaster ? $this->getMasterPdo() : null;
  990. }
  991. return $db->pdo;
  992. }
  993. /**
  994. * Returns the PDO instance for the currently active master connection.
  995. * This method will open the master DB connection and then return [[pdo]].
  996. * @return PDO the PDO instance for the currently active master connection.
  997. */
  998. public function getMasterPdo()
  999. {
  1000. $this->open();
  1001. return $this->pdo;
  1002. }
  1003. /**
  1004. * Returns the currently active slave connection.
  1005. * If this method is called for the first time, it will try to open a slave connection when [[enableSlaves]] is true.
  1006. * @param bool $fallbackToMaster whether to return a master connection in case there is no slave connection available.
  1007. * @return Connection the currently active slave connection. `null` is returned if there is no slave available and
  1008. * `$fallbackToMaster` is false.
  1009. */
  1010. public function getSlave($fallbackToMaster = true)
  1011. {
  1012. if (!$this->enableSlaves) {
  1013. return $fallbackToMaster ? $this : null;
  1014. }
  1015. if ($this->_slave === false) {
  1016. $this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
  1017. }
  1018. return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
  1019. }
  1020. /**
  1021. * Returns the currently active master connection.
  1022. * If this method is called for the first time, it will try to open a master connection.
  1023. * @return Connection the currently active master connection. `null` is returned if there is no master available.
  1024. * @since 2.0.11
  1025. */
  1026. public function getMaster()
  1027. {
  1028. if ($this->_master === false) {
  1029. $this->_master = $this->shuffleMasters
  1030. ? $this->openFromPool($this->masters, $this->masterConfig)
  1031. : $this->openFromPoolSequentially($this->masters, $this->masterConfig);
  1032. }
  1033. return $this->_master;
  1034. }
  1035. /**
  1036. * Executes the provided callback by using the master connection.
  1037. *
  1038. * This method is provided so that you can temporarily force using the master connection to perform
  1039. * DB operations even if they are read queries. For example,
  1040. *
  1041. * ```php
  1042. * $result = $db->useMaster(function ($db) {
  1043. * return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
  1044. * });
  1045. * ```
  1046. *
  1047. * @param callable $callback a PHP callable to be executed by this method. Its signature is
  1048. * `function (Connection $db)`. Its return value will be returned by this method.
  1049. * @return mixed the return value of the callback
  1050. * @throws \Exception|\Throwable if there is any exception thrown from the callback
  1051. */
  1052. public function useMaster(callable $callback)
  1053. {
  1054. if ($this->enableSlaves) {
  1055. $this->enableSlaves = false;
  1056. try {
  1057. $result = call_user_func($callback, $this);
  1058. } catch (\Exception $e) {
  1059. $this->enableSlaves = true;
  1060. throw $e;
  1061. } catch (\Throwable $e) {
  1062. $this->enableSlaves = true;
  1063. throw $e;
  1064. }
  1065. // TODO: use "finally" keyword when miminum required PHP version is >= 5.5
  1066. $this->enableSlaves = true;
  1067. } else {
  1068. $result = call_user_func($callback, $this);
  1069. }
  1070. return $result;
  1071. }
  1072. /**
  1073. * Opens the connection to a server in the pool.
  1074. *
  1075. * This method implements load balancing and failover among the given list of the servers.
  1076. * Connections will be tried in random order.
  1077. * For details about the failover behavior, see [[openFromPoolSequentially]].
  1078. *
  1079. * @param array $pool the list of connection configurations in the server pool
  1080. * @param array $sharedConfig the configuration common to those given in `$pool`.
  1081. * @return Connection the opened DB connection, or `null` if no server is available
  1082. * @throws InvalidConfigException if a configuration does not specify "dsn"
  1083. * @see openFromPoolSequentially
  1084. */
  1085. protected function openFromPool(array $pool, array $sharedConfig)
  1086. {
  1087. shuffle($pool);
  1088. return $this->openFromPoolSequentially($pool, $sharedConfig);
  1089. }
  1090. /**
  1091. * Opens the connection to a server in the pool.
  1092. *
  1093. * This method implements failover among the given list of servers.
  1094. * Connections will be tried in sequential order. The first successful connection will return.
  1095. *
  1096. * If [[serverStatusCache]] is configured, this method will cache information about
  1097. * unreachable servers and does not try to connect to these for the time configured in [[serverRetryInterval]].
  1098. * This helps to keep the application stable when some servers are unavailable. Avoiding
  1099. * connection attempts to unavailable servers saves time when the connection attempts fail due to timeout.
  1100. *
  1101. * If none of the servers are available the status cache is ignored and connection attempts are made to all
  1102. * servers (Since version 2.0.35). This is to avoid downtime when all servers are unavailable for a short time.
  1103. * After a successful connection attempt the server is marked as available again.
  1104. *
  1105. * @param array $pool the list of connection configurations in the server pool
  1106. * @param array $sharedConfig the configuration common to those given in `$pool`.
  1107. * @return Connection the opened DB connection, or `null` if no server is available
  1108. * @throws InvalidConfigException if a configuration does not specify "dsn"
  1109. * @since 2.0.11
  1110. * @see openFromPool
  1111. * @see serverStatusCache
  1112. */
  1113. protected function openFromPoolSequentially(array $pool, array $sharedConfig)
  1114. {
  1115. if (empty($pool)) {
  1116. return null;
  1117. }
  1118. if (!isset($sharedConfig['class'])) {
  1119. $sharedConfig['class'] = get_class($this);
  1120. }
  1121. $cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
  1122. foreach ($pool as $i => $config) {
  1123. $pool[$i] = $config = array_merge($sharedConfig, $config);
  1124. if (empty($config['dsn'])) {
  1125. throw new InvalidConfigException('The "dsn" option must be specified.');
  1126. }
  1127. $key = [__METHOD__, $config['dsn']];
  1128. if ($cache instanceof CacheInterface && $cache->get($key)) {
  1129. // should not try this dead server now
  1130. continue;
  1131. }
  1132. /* @var $db Connection */
  1133. $db = Yii::createObject($config);
  1134. try {
  1135. $db->open();
  1136. return $db;
  1137. } catch (\Exception $e) {
  1138. Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
  1139. if ($cache instanceof CacheInterface) {
  1140. // mark this server as dead and only retry it after the specified interval
  1141. $cache->set($key, 1, $this->serverRetryInterval);
  1142. }
  1143. // exclude server from retry below
  1144. unset($pool[$i]);
  1145. }
  1146. }
  1147. if ($cache instanceof CacheInterface) {
  1148. // if server status cache is enabled and no server is available
  1149. // ignore the cache and try to connect anyway
  1150. // $pool now only contains servers we did not already try in the loop above
  1151. foreach ($pool as $config) {
  1152. /* @var $db Connection */
  1153. $db = Yii::createObject($config);
  1154. try {
  1155. $db->open();
  1156. } catch (\Exception $e) {
  1157. Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
  1158. continue;
  1159. }
  1160. // mark this server as available again after successful connection
  1161. $cache->delete([__METHOD__, $config['dsn']]);
  1162. return $db;
  1163. }
  1164. }
  1165. return null;
  1166. }
  1167. /**
  1168. * Close the connection before serializing.
  1169. * @return array
  1170. */
  1171. public function __sleep()
  1172. {
  1173. $fields = (array) $this;
  1174. unset($fields['pdo']);
  1175. unset($fields["\000" . __CLASS__ . "\000" . '_master']);
  1176. unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
  1177. unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
  1178. unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
  1179. return array_keys($fields);
  1180. }
  1181. /**
  1182. * Reset the connection after cloning.
  1183. */
  1184. public function __clone()
  1185. {
  1186. parent::__clone();
  1187. $this->_master = false;
  1188. $this->_slave = false;
  1189. $this->_schema = null;
  1190. $this->_transaction = null;
  1191. if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
  1192. // reset PDO connection, unless its sqlite in-memory, which can only have one connection
  1193. $this->pdo = null;
  1194. }
  1195. }
  1196. }