Connection.php 47 KB

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