Connection.php 49 KB

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