Schema.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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 Yii;
  9. use yii\base\BaseObject;
  10. use yii\base\InvalidCallException;
  11. use yii\base\InvalidConfigException;
  12. use yii\base\NotSupportedException;
  13. use yii\caching\Cache;
  14. use yii\caching\CacheInterface;
  15. use yii\caching\TagDependency;
  16. /**
  17. * Schema is the base class for concrete DBMS-specific schema classes.
  18. *
  19. * Schema represents the database schema information that is DBMS specific.
  20. *
  21. * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
  22. * sequence object. This property is read-only.
  23. * @property QueryBuilder $queryBuilder The query builder for this connection. This property is read-only.
  24. * @property string[] $schemaNames All schema names in the database, except system schemas. This property is
  25. * read-only.
  26. * @property string $serverVersion Server version as a string. This property is read-only.
  27. * @property string[] $tableNames All table names in the database. This property is read-only.
  28. * @property TableSchema[] $tableSchemas The metadata for all tables in the database. Each array element is an
  29. * instance of [[TableSchema]] or its child class. This property is read-only.
  30. * @property string $transactionIsolationLevel The transaction isolation level to use for this transaction.
  31. * This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]],
  32. * [[Transaction::REPEATABLE_READ]] and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific
  33. * syntax to be used after `SET TRANSACTION ISOLATION LEVEL`. This property is write-only.
  34. *
  35. * @author Qiang Xue <qiang.xue@gmail.com>
  36. * @author Sergey Makinen <sergey@makinen.ru>
  37. * @since 2.0
  38. */
  39. abstract class Schema extends BaseObject
  40. {
  41. // The following are the supported abstract column data types.
  42. const TYPE_PK = 'pk';
  43. const TYPE_UPK = 'upk';
  44. const TYPE_BIGPK = 'bigpk';
  45. const TYPE_UBIGPK = 'ubigpk';
  46. const TYPE_CHAR = 'char';
  47. const TYPE_STRING = 'string';
  48. const TYPE_TEXT = 'text';
  49. const TYPE_TINYINT = 'tinyint';
  50. const TYPE_SMALLINT = 'smallint';
  51. const TYPE_INTEGER = 'integer';
  52. const TYPE_BIGINT = 'bigint';
  53. const TYPE_FLOAT = 'float';
  54. const TYPE_DOUBLE = 'double';
  55. const TYPE_DECIMAL = 'decimal';
  56. const TYPE_DATETIME = 'datetime';
  57. const TYPE_TIMESTAMP = 'timestamp';
  58. const TYPE_TIME = 'time';
  59. const TYPE_DATE = 'date';
  60. const TYPE_BINARY = 'binary';
  61. const TYPE_BOOLEAN = 'boolean';
  62. const TYPE_MONEY = 'money';
  63. const TYPE_JSON = 'json';
  64. /**
  65. * Schema cache version, to detect incompatibilities in cached values when the
  66. * data format of the cache changes.
  67. */
  68. const SCHEMA_CACHE_VERSION = 1;
  69. /**
  70. * @var Connection the database connection
  71. */
  72. public $db;
  73. /**
  74. * @var string the default schema name used for the current session.
  75. */
  76. public $defaultSchema;
  77. /**
  78. * @var array map of DB errors and corresponding exceptions
  79. * If left part is found in DB error message exception class from the right part is used.
  80. */
  81. public $exceptionMap = [
  82. 'SQLSTATE[23' => 'yii\db\IntegrityException',
  83. ];
  84. /**
  85. * @var string|array column schema class or class config
  86. * @since 2.0.11
  87. */
  88. public $columnSchemaClass = 'yii\db\ColumnSchema';
  89. /**
  90. * @var string|string[] character used to quote schema, table, etc. names.
  91. * An array of 2 characters can be used in case starting and ending characters are different.
  92. * @since 2.0.14
  93. */
  94. protected $tableQuoteCharacter = "'";
  95. /**
  96. * @var string|string[] character used to quote column names.
  97. * An array of 2 characters can be used in case starting and ending characters are different.
  98. * @since 2.0.14
  99. */
  100. protected $columnQuoteCharacter = '"';
  101. /**
  102. * @var array list of ALL schema names in the database, except system schemas
  103. */
  104. private $_schemaNames;
  105. /**
  106. * @var array list of ALL table names in the database
  107. */
  108. private $_tableNames = [];
  109. /**
  110. * @var array list of loaded table metadata (table name => metadata type => metadata).
  111. */
  112. private $_tableMetadata = [];
  113. /**
  114. * @var QueryBuilder the query builder for this database
  115. */
  116. private $_builder;
  117. /**
  118. * @var string server version as a string.
  119. */
  120. private $_serverVersion;
  121. /**
  122. * Resolves the table name and schema name (if any).
  123. * @param string $name the table name
  124. * @return TableSchema [[TableSchema]] with resolved table, schema, etc. names.
  125. * @throws NotSupportedException if this method is not supported by the DBMS.
  126. * @since 2.0.13
  127. */
  128. protected function resolveTableName($name)
  129. {
  130. throw new NotSupportedException(get_class($this) . ' does not support resolving table names.');
  131. }
  132. /**
  133. * Returns all schema names in the database, including the default one but not system schemas.
  134. * This method should be overridden by child classes in order to support this feature
  135. * because the default implementation simply throws an exception.
  136. * @return array all schema names in the database, except system schemas.
  137. * @throws NotSupportedException if this method is not supported by the DBMS.
  138. * @since 2.0.4
  139. */
  140. protected function findSchemaNames()
  141. {
  142. throw new NotSupportedException(get_class($this) . ' does not support fetching all schema names.');
  143. }
  144. /**
  145. * Returns all table names in the database.
  146. * This method should be overridden by child classes in order to support this feature
  147. * because the default implementation simply throws an exception.
  148. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  149. * @return array all table names in the database. The names have NO schema name prefix.
  150. * @throws NotSupportedException if this method is not supported by the DBMS.
  151. */
  152. protected function findTableNames($schema = '')
  153. {
  154. throw new NotSupportedException(get_class($this) . ' does not support fetching all table names.');
  155. }
  156. /**
  157. * Loads the metadata for the specified table.
  158. * @param string $name table name
  159. * @return TableSchema|null DBMS-dependent table metadata, `null` if the table does not exist.
  160. */
  161. abstract protected function loadTableSchema($name);
  162. /**
  163. * Creates a column schema for the database.
  164. * This method may be overridden by child classes to create a DBMS-specific column schema.
  165. * @return ColumnSchema column schema instance.
  166. * @throws InvalidConfigException if a column schema class cannot be created.
  167. */
  168. protected function createColumnSchema()
  169. {
  170. return Yii::createObject($this->columnSchemaClass);
  171. }
  172. /**
  173. * Obtains the metadata for the named table.
  174. * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
  175. * @param bool $refresh whether to reload the table schema even if it is found in the cache.
  176. * @return TableSchema|null table metadata. `null` if the named table does not exist.
  177. */
  178. public function getTableSchema($name, $refresh = false)
  179. {
  180. return $this->getTableMetadata($name, 'schema', $refresh);
  181. }
  182. /**
  183. * Returns the metadata for all tables in the database.
  184. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
  185. * @param bool $refresh whether to fetch the latest available table schemas. If this is `false`,
  186. * cached data may be returned if available.
  187. * @return TableSchema[] the metadata for all tables in the database.
  188. * Each array element is an instance of [[TableSchema]] or its child class.
  189. */
  190. public function getTableSchemas($schema = '', $refresh = false)
  191. {
  192. return $this->getSchemaMetadata($schema, 'schema', $refresh);
  193. }
  194. /**
  195. * Returns all schema names in the database, except system schemas.
  196. * @param bool $refresh whether to fetch the latest available schema names. If this is false,
  197. * schema names fetched previously (if available) will be returned.
  198. * @return string[] all schema names in the database, except system schemas.
  199. * @since 2.0.4
  200. */
  201. public function getSchemaNames($refresh = false)
  202. {
  203. if ($this->_schemaNames === null || $refresh) {
  204. $this->_schemaNames = $this->findSchemaNames();
  205. }
  206. return $this->_schemaNames;
  207. }
  208. /**
  209. * Returns all table names in the database.
  210. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
  211. * If not empty, the returned table names will be prefixed with the schema name.
  212. * @param bool $refresh whether to fetch the latest available table names. If this is false,
  213. * table names fetched previously (if available) will be returned.
  214. * @return string[] all table names in the database.
  215. */
  216. public function getTableNames($schema = '', $refresh = false)
  217. {
  218. if (!isset($this->_tableNames[$schema]) || $refresh) {
  219. $this->_tableNames[$schema] = $this->findTableNames($schema);
  220. }
  221. return $this->_tableNames[$schema];
  222. }
  223. /**
  224. * @return QueryBuilder the query builder for this connection.
  225. */
  226. public function getQueryBuilder()
  227. {
  228. if ($this->_builder === null) {
  229. $this->_builder = $this->createQueryBuilder();
  230. }
  231. return $this->_builder;
  232. }
  233. /**
  234. * Determines the PDO type for the given PHP data value.
  235. * @param mixed $data the data whose PDO type is to be determined
  236. * @return int the PDO type
  237. * @see https://secure.php.net/manual/en/pdo.constants.php
  238. */
  239. public function getPdoType($data)
  240. {
  241. static $typeMap = [
  242. // php type => PDO type
  243. 'boolean' => \PDO::PARAM_BOOL,
  244. 'integer' => \PDO::PARAM_INT,
  245. 'string' => \PDO::PARAM_STR,
  246. 'resource' => \PDO::PARAM_LOB,
  247. 'NULL' => \PDO::PARAM_NULL,
  248. ];
  249. $type = gettype($data);
  250. return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
  251. }
  252. /**
  253. * Refreshes the schema.
  254. * This method cleans up all cached table schemas so that they can be re-created later
  255. * to reflect the database schema change.
  256. */
  257. public function refresh()
  258. {
  259. /* @var $cache CacheInterface */
  260. $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
  261. if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
  262. TagDependency::invalidate($cache, $this->getCacheTag());
  263. }
  264. $this->_tableNames = [];
  265. $this->_tableMetadata = [];
  266. }
  267. /**
  268. * Refreshes the particular table schema.
  269. * This method cleans up cached table schema so that it can be re-created later
  270. * to reflect the database schema change.
  271. * @param string $name table name.
  272. * @since 2.0.6
  273. */
  274. public function refreshTableSchema($name)
  275. {
  276. $rawName = $this->getRawTableName($name);
  277. unset($this->_tableMetadata[$rawName]);
  278. $this->_tableNames = [];
  279. /* @var $cache CacheInterface */
  280. $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
  281. if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
  282. $cache->delete($this->getCacheKey($rawName));
  283. }
  284. }
  285. /**
  286. * Creates a query builder for the database.
  287. * This method may be overridden by child classes to create a DBMS-specific query builder.
  288. * @return QueryBuilder query builder instance
  289. */
  290. public function createQueryBuilder()
  291. {
  292. return new QueryBuilder($this->db);
  293. }
  294. /**
  295. * Create a column schema builder instance giving the type and value precision.
  296. *
  297. * This method may be overridden by child classes to create a DBMS-specific column schema builder.
  298. *
  299. * @param string $type type of the column. See [[ColumnSchemaBuilder::$type]].
  300. * @param int|string|array $length length or precision of the column. See [[ColumnSchemaBuilder::$length]].
  301. * @return ColumnSchemaBuilder column schema builder instance
  302. * @since 2.0.6
  303. */
  304. public function createColumnSchemaBuilder($type, $length = null)
  305. {
  306. return new ColumnSchemaBuilder($type, $length);
  307. }
  308. /**
  309. * Returns all unique indexes for the given table.
  310. *
  311. * Each array element is of the following structure:
  312. *
  313. * ```php
  314. * [
  315. * 'IndexName1' => ['col1' [, ...]],
  316. * 'IndexName2' => ['col2' [, ...]],
  317. * ]
  318. * ```
  319. *
  320. * This method should be overridden by child classes in order to support this feature
  321. * because the default implementation simply throws an exception
  322. * @param TableSchema $table the table metadata
  323. * @return array all unique indexes for the given table.
  324. * @throws NotSupportedException if this method is called
  325. */
  326. public function findUniqueIndexes($table)
  327. {
  328. throw new NotSupportedException(get_class($this) . ' does not support getting unique indexes information.');
  329. }
  330. /**
  331. * Returns the ID of the last inserted row or sequence value.
  332. * @param string $sequenceName name of the sequence object (required by some DBMS)
  333. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  334. * @throws InvalidCallException if the DB connection is not active
  335. * @see https://secure.php.net/manual/en/function.PDO-lastInsertId.php
  336. */
  337. public function getLastInsertID($sequenceName = '')
  338. {
  339. if ($this->db->isActive) {
  340. return $this->db->pdo->lastInsertId($sequenceName === '' ? null : $this->quoteTableName($sequenceName));
  341. }
  342. throw new InvalidCallException('DB Connection is not active.');
  343. }
  344. /**
  345. * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
  346. */
  347. public function supportsSavepoint()
  348. {
  349. return $this->db->enableSavepoint;
  350. }
  351. /**
  352. * Creates a new savepoint.
  353. * @param string $name the savepoint name
  354. */
  355. public function createSavepoint($name)
  356. {
  357. $this->db->createCommand("SAVEPOINT $name")->execute();
  358. }
  359. /**
  360. * Releases an existing savepoint.
  361. * @param string $name the savepoint name
  362. */
  363. public function releaseSavepoint($name)
  364. {
  365. $this->db->createCommand("RELEASE SAVEPOINT $name")->execute();
  366. }
  367. /**
  368. * Rolls back to a previously created savepoint.
  369. * @param string $name the savepoint name
  370. */
  371. public function rollBackSavepoint($name)
  372. {
  373. $this->db->createCommand("ROLLBACK TO SAVEPOINT $name")->execute();
  374. }
  375. /**
  376. * Sets the isolation level of the current transaction.
  377. * @param string $level The transaction isolation level to use for this transaction.
  378. * This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]], [[Transaction::REPEATABLE_READ]]
  379. * and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific syntax to be used
  380. * after `SET TRANSACTION ISOLATION LEVEL`.
  381. * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
  382. */
  383. public function setTransactionIsolationLevel($level)
  384. {
  385. $this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
  386. }
  387. /**
  388. * Executes the INSERT command, returning primary key values.
  389. * @param string $table the table that new rows will be inserted into.
  390. * @param array $columns the column data (name => value) to be inserted into the table.
  391. * @return array|false primary key values or false if the command fails
  392. * @since 2.0.4
  393. */
  394. public function insert($table, $columns)
  395. {
  396. $command = $this->db->createCommand()->insert($table, $columns);
  397. if (!$command->execute()) {
  398. return false;
  399. }
  400. $tableSchema = $this->getTableSchema($table);
  401. $result = [];
  402. foreach ($tableSchema->primaryKey as $name) {
  403. if ($tableSchema->columns[$name]->autoIncrement) {
  404. $result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
  405. break;
  406. }
  407. $result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue;
  408. }
  409. return $result;
  410. }
  411. /**
  412. * Quotes a string value for use in a query.
  413. * Note that if the parameter is not a string, it will be returned without change.
  414. * @param string $str string to be quoted
  415. * @return string the properly quoted string
  416. * @see https://secure.php.net/manual/en/function.PDO-quote.php
  417. */
  418. public function quoteValue($str)
  419. {
  420. if (!is_string($str)) {
  421. return $str;
  422. }
  423. if (($value = $this->db->getSlavePdo()->quote($str)) !== false) {
  424. return $value;
  425. }
  426. // the driver doesn't support quote (e.g. oci)
  427. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  428. }
  429. /**
  430. * Quotes a table name for use in a query.
  431. * If the table name contains schema prefix, the prefix will also be properly quoted.
  432. * If the table name is already quoted or contains '(' or '{{',
  433. * then this method will do nothing.
  434. * @param string $name table name
  435. * @return string the properly quoted table name
  436. * @see quoteSimpleTableName()
  437. */
  438. public function quoteTableName($name)
  439. {
  440. if (strpos($name, '(') !== false || strpos($name, '{{') !== false) {
  441. return $name;
  442. }
  443. if (strpos($name, '.') === false) {
  444. return $this->quoteSimpleTableName($name);
  445. }
  446. $parts = $this->getTableNameParts($name);
  447. foreach ($parts as $i => $part) {
  448. $parts[$i] = $this->quoteSimpleTableName($part);
  449. }
  450. return implode('.', $parts);
  451. }
  452. /**
  453. * Splits full table name into parts
  454. * @param string $name
  455. * @return array
  456. * @since 2.0.22
  457. */
  458. protected function getTableNameParts($name)
  459. {
  460. return explode('.', $name);
  461. }
  462. /**
  463. * Quotes a column name for use in a query.
  464. * If the column name contains prefix, the prefix will also be properly quoted.
  465. * If the column name is already quoted or contains '(', '[[' or '{{',
  466. * then this method will do nothing.
  467. * @param string $name column name
  468. * @return string the properly quoted column name
  469. * @see quoteSimpleColumnName()
  470. */
  471. public function quoteColumnName($name)
  472. {
  473. if (strpos($name, '(') !== false || strpos($name, '[[') !== false) {
  474. return $name;
  475. }
  476. if (($pos = strrpos($name, '.')) !== false) {
  477. $prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
  478. $name = substr($name, $pos + 1);
  479. } else {
  480. $prefix = '';
  481. }
  482. if (strpos($name, '{{') !== false) {
  483. return $name;
  484. }
  485. return $prefix . $this->quoteSimpleColumnName($name);
  486. }
  487. /**
  488. * Quotes a simple table name for use in a query.
  489. * A simple table name should contain the table name only without any schema prefix.
  490. * If the table name is already quoted, this method will do nothing.
  491. * @param string $name table name
  492. * @return string the properly quoted table name
  493. */
  494. public function quoteSimpleTableName($name)
  495. {
  496. if (is_string($this->tableQuoteCharacter)) {
  497. $startingCharacter = $endingCharacter = $this->tableQuoteCharacter;
  498. } else {
  499. list($startingCharacter, $endingCharacter) = $this->tableQuoteCharacter;
  500. }
  501. return strpos($name, $startingCharacter) !== false ? $name : $startingCharacter . $name . $endingCharacter;
  502. }
  503. /**
  504. * Quotes a simple column name for use in a query.
  505. * A simple column name should contain the column name only without any prefix.
  506. * If the column name is already quoted or is the asterisk character '*', this method will do nothing.
  507. * @param string $name column name
  508. * @return string the properly quoted column name
  509. */
  510. public function quoteSimpleColumnName($name)
  511. {
  512. if (is_string($this->tableQuoteCharacter)) {
  513. $startingCharacter = $endingCharacter = $this->columnQuoteCharacter;
  514. } else {
  515. list($startingCharacter, $endingCharacter) = $this->columnQuoteCharacter;
  516. }
  517. return $name === '*' || strpos($name, $startingCharacter) !== false ? $name : $startingCharacter . $name . $endingCharacter;
  518. }
  519. /**
  520. * Unquotes a simple table name.
  521. * A simple table name should contain the table name only without any schema prefix.
  522. * If the table name is not quoted, this method will do nothing.
  523. * @param string $name table name.
  524. * @return string unquoted table name.
  525. * @since 2.0.14
  526. */
  527. public function unquoteSimpleTableName($name)
  528. {
  529. if (is_string($this->tableQuoteCharacter)) {
  530. $startingCharacter = $this->tableQuoteCharacter;
  531. } else {
  532. $startingCharacter = $this->tableQuoteCharacter[0];
  533. }
  534. return strpos($name, $startingCharacter) === false ? $name : substr($name, 1, -1);
  535. }
  536. /**
  537. * Unquotes a simple column name.
  538. * A simple column name should contain the column name only without any prefix.
  539. * If the column name is not quoted or is the asterisk character '*', this method will do nothing.
  540. * @param string $name column name.
  541. * @return string unquoted column name.
  542. * @since 2.0.14
  543. */
  544. public function unquoteSimpleColumnName($name)
  545. {
  546. if (is_string($this->columnQuoteCharacter)) {
  547. $startingCharacter = $this->columnQuoteCharacter;
  548. } else {
  549. $startingCharacter = $this->columnQuoteCharacter[0];
  550. }
  551. return strpos($name, $startingCharacter) === false ? $name : substr($name, 1, -1);
  552. }
  553. /**
  554. * Returns the actual name of a given table name.
  555. * This method will strip off curly brackets from the given table name
  556. * and replace the percentage character '%' with [[Connection::tablePrefix]].
  557. * @param string $name the table name to be converted
  558. * @return string the real name of the given table name
  559. */
  560. public function getRawTableName($name)
  561. {
  562. if (strpos($name, '{{') !== false) {
  563. $name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
  564. return str_replace('%', $this->db->tablePrefix, $name);
  565. }
  566. return $name;
  567. }
  568. /**
  569. * Extracts the PHP type from abstract DB type.
  570. * @param ColumnSchema $column the column schema information
  571. * @return string PHP type name
  572. */
  573. protected function getColumnPhpType($column)
  574. {
  575. static $typeMap = [
  576. // abstract type => php type
  577. self::TYPE_TINYINT => 'integer',
  578. self::TYPE_SMALLINT => 'integer',
  579. self::TYPE_INTEGER => 'integer',
  580. self::TYPE_BIGINT => 'integer',
  581. self::TYPE_BOOLEAN => 'boolean',
  582. self::TYPE_FLOAT => 'double',
  583. self::TYPE_DOUBLE => 'double',
  584. self::TYPE_BINARY => 'resource',
  585. self::TYPE_JSON => 'array',
  586. ];
  587. if (isset($typeMap[$column->type])) {
  588. if ($column->type === 'bigint') {
  589. return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string';
  590. } elseif ($column->type === 'integer') {
  591. return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer';
  592. }
  593. return $typeMap[$column->type];
  594. }
  595. return 'string';
  596. }
  597. /**
  598. * Converts a DB exception to a more concrete one if possible.
  599. *
  600. * @param \Exception $e
  601. * @param string $rawSql SQL that produced exception
  602. * @return Exception
  603. */
  604. public function convertException(\Exception $e, $rawSql)
  605. {
  606. if ($e instanceof Exception) {
  607. return $e;
  608. }
  609. $exceptionClass = '\yii\db\Exception';
  610. foreach ($this->exceptionMap as $error => $class) {
  611. if (strpos($e->getMessage(), $error) !== false) {
  612. $exceptionClass = $class;
  613. }
  614. }
  615. $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
  616. $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
  617. return new $exceptionClass($message, $errorInfo, (int)$e->getCode(), $e);
  618. }
  619. /**
  620. * Returns a value indicating whether a SQL statement is for read purpose.
  621. * @param string $sql the SQL statement
  622. * @return bool whether a SQL statement is for read purpose.
  623. */
  624. public function isReadQuery($sql)
  625. {
  626. $pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
  627. return preg_match($pattern, $sql) > 0;
  628. }
  629. /**
  630. * Returns a server version as a string comparable by [[\version_compare()]].
  631. * @return string server version as a string.
  632. * @since 2.0.14
  633. */
  634. public function getServerVersion()
  635. {
  636. if ($this->_serverVersion === null) {
  637. $this->_serverVersion = $this->db->getSlavePdo()->getAttribute(\PDO::ATTR_SERVER_VERSION);
  638. }
  639. return $this->_serverVersion;
  640. }
  641. /**
  642. * Returns the cache key for the specified table name.
  643. * @param string $name the table name.
  644. * @return mixed the cache key.
  645. */
  646. protected function getCacheKey($name)
  647. {
  648. return [
  649. __CLASS__,
  650. $this->db->dsn,
  651. $this->db->username,
  652. $this->getRawTableName($name),
  653. ];
  654. }
  655. /**
  656. * Returns the cache tag name.
  657. * This allows [[refresh()]] to invalidate all cached table schemas.
  658. * @return string the cache tag name
  659. */
  660. protected function getCacheTag()
  661. {
  662. return md5(serialize([
  663. __CLASS__,
  664. $this->db->dsn,
  665. $this->db->username,
  666. ]));
  667. }
  668. /**
  669. * Returns the metadata of the given type for the given table.
  670. * If there's no metadata in the cache, this method will call
  671. * a `'loadTable' . ucfirst($type)` named method with the table name to obtain the metadata.
  672. * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
  673. * @param string $type metadata type.
  674. * @param bool $refresh whether to reload the table metadata even if it is found in the cache.
  675. * @return mixed metadata.
  676. * @since 2.0.13
  677. */
  678. protected function getTableMetadata($name, $type, $refresh)
  679. {
  680. $cache = null;
  681. if ($this->db->enableSchemaCache && !in_array($name, $this->db->schemaCacheExclude, true)) {
  682. $schemaCache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
  683. if ($schemaCache instanceof CacheInterface) {
  684. $cache = $schemaCache;
  685. }
  686. }
  687. $rawName = $this->getRawTableName($name);
  688. if (!isset($this->_tableMetadata[$rawName])) {
  689. $this->loadTableMetadataFromCache($cache, $rawName);
  690. }
  691. if ($refresh || !array_key_exists($type, $this->_tableMetadata[$rawName])) {
  692. $this->_tableMetadata[$rawName][$type] = $this->{'loadTable' . ucfirst($type)}($rawName);
  693. $this->saveTableMetadataToCache($cache, $rawName);
  694. }
  695. return $this->_tableMetadata[$rawName][$type];
  696. }
  697. /**
  698. * Returns the metadata of the given type for all tables in the given schema.
  699. * This method will call a `'getTable' . ucfirst($type)` named method with the table name
  700. * and the refresh flag to obtain the metadata.
  701. * @param string $schema the schema of the metadata. Defaults to empty string, meaning the current or default schema name.
  702. * @param string $type metadata type.
  703. * @param bool $refresh whether to fetch the latest available table metadata. If this is `false`,
  704. * cached data may be returned if available.
  705. * @return array array of metadata.
  706. * @since 2.0.13
  707. */
  708. protected function getSchemaMetadata($schema, $type, $refresh)
  709. {
  710. $metadata = [];
  711. $methodName = 'getTable' . ucfirst($type);
  712. foreach ($this->getTableNames($schema, $refresh) as $name) {
  713. if ($schema !== '') {
  714. $name = $schema . '.' . $name;
  715. }
  716. $tableMetadata = $this->$methodName($name, $refresh);
  717. if ($tableMetadata !== null) {
  718. $metadata[] = $tableMetadata;
  719. }
  720. }
  721. return $metadata;
  722. }
  723. /**
  724. * Sets the metadata of the given type for the given table.
  725. * @param string $name table name.
  726. * @param string $type metadata type.
  727. * @param mixed $data metadata.
  728. * @since 2.0.13
  729. */
  730. protected function setTableMetadata($name, $type, $data)
  731. {
  732. $this->_tableMetadata[$this->getRawTableName($name)][$type] = $data;
  733. }
  734. /**
  735. * Changes row's array key case to lower if PDO's one is set to uppercase.
  736. * @param array $row row's array or an array of row's arrays.
  737. * @param bool $multiple whether multiple rows or a single row passed.
  738. * @return array normalized row or rows.
  739. * @since 2.0.13
  740. */
  741. protected function normalizePdoRowKeyCase(array $row, $multiple)
  742. {
  743. if ($this->db->getSlavePdo()->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_UPPER) {
  744. return $row;
  745. }
  746. if ($multiple) {
  747. return array_map(function (array $row) {
  748. return array_change_key_case($row, CASE_LOWER);
  749. }, $row);
  750. }
  751. return array_change_key_case($row, CASE_LOWER);
  752. }
  753. /**
  754. * Tries to load and populate table metadata from cache.
  755. * @param Cache|null $cache
  756. * @param string $name
  757. */
  758. private function loadTableMetadataFromCache($cache, $name)
  759. {
  760. if ($cache === null) {
  761. $this->_tableMetadata[$name] = [];
  762. return;
  763. }
  764. $metadata = $cache->get($this->getCacheKey($name));
  765. if (!is_array($metadata) || !isset($metadata['cacheVersion']) || $metadata['cacheVersion'] !== static::SCHEMA_CACHE_VERSION) {
  766. $this->_tableMetadata[$name] = [];
  767. return;
  768. }
  769. unset($metadata['cacheVersion']);
  770. $this->_tableMetadata[$name] = $metadata;
  771. }
  772. /**
  773. * Saves table metadata to cache.
  774. * @param Cache|null $cache
  775. * @param string $name
  776. */
  777. private function saveTableMetadataToCache($cache, $name)
  778. {
  779. if ($cache === null) {
  780. return;
  781. }
  782. $metadata = $this->_tableMetadata[$name];
  783. $metadata['cacheVersion'] = static::SCHEMA_CACHE_VERSION;
  784. $cache->set(
  785. $this->getCacheKey($name),
  786. $metadata,
  787. $this->db->schemaCacheDuration,
  788. new TagDependency(['tags' => $this->getCacheTag()])
  789. );
  790. }
  791. }