Connection.php 48 KB

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