Schema.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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, '(') === 0 && strpos($name, ')') === strlen($name) - 1) {
  441. return $name;
  442. }
  443. if (strpos($name, '{{') !== false) {
  444. return $name;
  445. }
  446. if (strpos($name, '.') === false) {
  447. return $this->quoteSimpleTableName($name);
  448. }
  449. $parts = $this->getTableNameParts($name);
  450. foreach ($parts as $i => $part) {
  451. $parts[$i] = $this->quoteSimpleTableName($part);
  452. }
  453. return implode('.', $parts);
  454. }
  455. /**
  456. * Splits full table name into parts
  457. * @param string $name
  458. * @return array
  459. * @since 2.0.22
  460. */
  461. protected function getTableNameParts($name)
  462. {
  463. return explode('.', $name);
  464. }
  465. /**
  466. * Quotes a column name for use in a query.
  467. * If the column name contains prefix, the prefix will also be properly quoted.
  468. * If the column name is already quoted or contains '(', '[[' or '{{',
  469. * then this method will do nothing.
  470. * @param string $name column name
  471. * @return string the properly quoted column name
  472. * @see quoteSimpleColumnName()
  473. */
  474. public function quoteColumnName($name)
  475. {
  476. if (strpos($name, '(') !== false || strpos($name, '[[') !== false) {
  477. return $name;
  478. }
  479. if (($pos = strrpos($name, '.')) !== false) {
  480. $prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
  481. $name = substr($name, $pos + 1);
  482. } else {
  483. $prefix = '';
  484. }
  485. if (strpos($name, '{{') !== false) {
  486. return $name;
  487. }
  488. return $prefix . $this->quoteSimpleColumnName($name);
  489. }
  490. /**
  491. * Quotes a simple table name for use in a query.
  492. * A simple table name should contain the table name only without any schema prefix.
  493. * If the table name is already quoted, this method will do nothing.
  494. * @param string $name table name
  495. * @return string the properly quoted table name
  496. */
  497. public function quoteSimpleTableName($name)
  498. {
  499. if (is_string($this->tableQuoteCharacter)) {
  500. $startingCharacter = $endingCharacter = $this->tableQuoteCharacter;
  501. } else {
  502. list($startingCharacter, $endingCharacter) = $this->tableQuoteCharacter;
  503. }
  504. return strpos($name, $startingCharacter) !== false ? $name : $startingCharacter . $name . $endingCharacter;
  505. }
  506. /**
  507. * Quotes a simple column name for use in a query.
  508. * A simple column name should contain the column name only without any prefix.
  509. * If the column name is already quoted or is the asterisk character '*', this method will do nothing.
  510. * @param string $name column name
  511. * @return string the properly quoted column name
  512. */
  513. public function quoteSimpleColumnName($name)
  514. {
  515. if (is_string($this->columnQuoteCharacter)) {
  516. $startingCharacter = $endingCharacter = $this->columnQuoteCharacter;
  517. } else {
  518. list($startingCharacter, $endingCharacter) = $this->columnQuoteCharacter;
  519. }
  520. return $name === '*' || strpos($name, $startingCharacter) !== false ? $name : $startingCharacter . $name . $endingCharacter;
  521. }
  522. /**
  523. * Unquotes a simple table name.
  524. * A simple table name should contain the table name only without any schema prefix.
  525. * If the table name is not quoted, this method will do nothing.
  526. * @param string $name table name.
  527. * @return string unquoted table name.
  528. * @since 2.0.14
  529. */
  530. public function unquoteSimpleTableName($name)
  531. {
  532. if (is_string($this->tableQuoteCharacter)) {
  533. $startingCharacter = $this->tableQuoteCharacter;
  534. } else {
  535. $startingCharacter = $this->tableQuoteCharacter[0];
  536. }
  537. return strpos($name, $startingCharacter) === false ? $name : substr($name, 1, -1);
  538. }
  539. /**
  540. * Unquotes a simple column name.
  541. * A simple column name should contain the column name only without any prefix.
  542. * If the column name is not quoted or is the asterisk character '*', this method will do nothing.
  543. * @param string $name column name.
  544. * @return string unquoted column name.
  545. * @since 2.0.14
  546. */
  547. public function unquoteSimpleColumnName($name)
  548. {
  549. if (is_string($this->columnQuoteCharacter)) {
  550. $startingCharacter = $this->columnQuoteCharacter;
  551. } else {
  552. $startingCharacter = $this->columnQuoteCharacter[0];
  553. }
  554. return strpos($name, $startingCharacter) === false ? $name : substr($name, 1, -1);
  555. }
  556. /**
  557. * Returns the actual name of a given table name.
  558. * This method will strip off curly brackets from the given table name
  559. * and replace the percentage character '%' with [[Connection::tablePrefix]].
  560. * @param string $name the table name to be converted
  561. * @return string the real name of the given table name
  562. */
  563. public function getRawTableName($name)
  564. {
  565. if (strpos($name, '{{') !== false) {
  566. $name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
  567. return str_replace('%', $this->db->tablePrefix, $name);
  568. }
  569. return $name;
  570. }
  571. /**
  572. * Extracts the PHP type from abstract DB type.
  573. * @param ColumnSchema $column the column schema information
  574. * @return string PHP type name
  575. */
  576. protected function getColumnPhpType($column)
  577. {
  578. static $typeMap = [
  579. // abstract type => php type
  580. self::TYPE_TINYINT => 'integer',
  581. self::TYPE_SMALLINT => 'integer',
  582. self::TYPE_INTEGER => 'integer',
  583. self::TYPE_BIGINT => 'integer',
  584. self::TYPE_BOOLEAN => 'boolean',
  585. self::TYPE_FLOAT => 'double',
  586. self::TYPE_DOUBLE => 'double',
  587. self::TYPE_BINARY => 'resource',
  588. self::TYPE_JSON => 'array',
  589. ];
  590. if (isset($typeMap[$column->type])) {
  591. if ($column->type === 'bigint') {
  592. return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string';
  593. } elseif ($column->type === 'integer') {
  594. return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer';
  595. }
  596. return $typeMap[$column->type];
  597. }
  598. return 'string';
  599. }
  600. /**
  601. * Converts a DB exception to a more concrete one if possible.
  602. *
  603. * @param \Exception $e
  604. * @param string $rawSql SQL that produced exception
  605. * @return Exception
  606. */
  607. public function convertException(\Exception $e, $rawSql)
  608. {
  609. if ($e instanceof Exception) {
  610. return $e;
  611. }
  612. $exceptionClass = '\yii\db\Exception';
  613. foreach ($this->exceptionMap as $error => $class) {
  614. if (strpos($e->getMessage(), $error) !== false) {
  615. $exceptionClass = $class;
  616. }
  617. }
  618. $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
  619. $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
  620. return new $exceptionClass($message, $errorInfo, $e->getCode(), $e);
  621. }
  622. /**
  623. * Returns a value indicating whether a SQL statement is for read purpose.
  624. * @param string $sql the SQL statement
  625. * @return bool whether a SQL statement is for read purpose.
  626. */
  627. public function isReadQuery($sql)
  628. {
  629. $pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
  630. return preg_match($pattern, $sql) > 0;
  631. }
  632. /**
  633. * Returns a server version as a string comparable by [[\version_compare()]].
  634. * @return string server version as a string.
  635. * @since 2.0.14
  636. */
  637. public function getServerVersion()
  638. {
  639. if ($this->_serverVersion === null) {
  640. $this->_serverVersion = $this->db->getSlavePdo()->getAttribute(\PDO::ATTR_SERVER_VERSION);
  641. }
  642. return $this->_serverVersion;
  643. }
  644. /**
  645. * Returns the cache key for the specified table name.
  646. * @param string $name the table name.
  647. * @return mixed the cache key.
  648. */
  649. protected function getCacheKey($name)
  650. {
  651. return [
  652. __CLASS__,
  653. $this->db->dsn,
  654. $this->db->username,
  655. $this->getRawTableName($name),
  656. ];
  657. }
  658. /**
  659. * Returns the cache tag name.
  660. * This allows [[refresh()]] to invalidate all cached table schemas.
  661. * @return string the cache tag name
  662. */
  663. protected function getCacheTag()
  664. {
  665. return md5(serialize([
  666. __CLASS__,
  667. $this->db->dsn,
  668. $this->db->username,
  669. ]));
  670. }
  671. /**
  672. * Returns the metadata of the given type for the given table.
  673. * If there's no metadata in the cache, this method will call
  674. * a `'loadTable' . ucfirst($type)` named method with the table name to obtain the metadata.
  675. * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
  676. * @param string $type metadata type.
  677. * @param bool $refresh whether to reload the table metadata even if it is found in the cache.
  678. * @return mixed metadata.
  679. * @since 2.0.13
  680. */
  681. protected function getTableMetadata($name, $type, $refresh)
  682. {
  683. $cache = null;
  684. if ($this->db->enableSchemaCache && !in_array($name, $this->db->schemaCacheExclude, true)) {
  685. $schemaCache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
  686. if ($schemaCache instanceof CacheInterface) {
  687. $cache = $schemaCache;
  688. }
  689. }
  690. $rawName = $this->getRawTableName($name);
  691. if (!isset($this->_tableMetadata[$rawName])) {
  692. $this->loadTableMetadataFromCache($cache, $rawName);
  693. }
  694. if ($refresh || !array_key_exists($type, $this->_tableMetadata[$rawName])) {
  695. $this->_tableMetadata[$rawName][$type] = $this->{'loadTable' . ucfirst($type)}($rawName);
  696. $this->saveTableMetadataToCache($cache, $rawName);
  697. }
  698. return $this->_tableMetadata[$rawName][$type];
  699. }
  700. /**
  701. * Returns the metadata of the given type for all tables in the given schema.
  702. * This method will call a `'getTable' . ucfirst($type)` named method with the table name
  703. * and the refresh flag to obtain the metadata.
  704. * @param string $schema the schema of the metadata. Defaults to empty string, meaning the current or default schema name.
  705. * @param string $type metadata type.
  706. * @param bool $refresh whether to fetch the latest available table metadata. If this is `false`,
  707. * cached data may be returned if available.
  708. * @return array array of metadata.
  709. * @since 2.0.13
  710. */
  711. protected function getSchemaMetadata($schema, $type, $refresh)
  712. {
  713. $metadata = [];
  714. $methodName = 'getTable' . ucfirst($type);
  715. foreach ($this->getTableNames($schema, $refresh) as $name) {
  716. if ($schema !== '') {
  717. $name = $schema . '.' . $name;
  718. }
  719. $tableMetadata = $this->$methodName($name, $refresh);
  720. if ($tableMetadata !== null) {
  721. $metadata[] = $tableMetadata;
  722. }
  723. }
  724. return $metadata;
  725. }
  726. /**
  727. * Sets the metadata of the given type for the given table.
  728. * @param string $name table name.
  729. * @param string $type metadata type.
  730. * @param mixed $data metadata.
  731. * @since 2.0.13
  732. */
  733. protected function setTableMetadata($name, $type, $data)
  734. {
  735. $this->_tableMetadata[$this->getRawTableName($name)][$type] = $data;
  736. }
  737. /**
  738. * Changes row's array key case to lower if PDO's one is set to uppercase.
  739. * @param array $row row's array or an array of row's arrays.
  740. * @param bool $multiple whether multiple rows or a single row passed.
  741. * @return array normalized row or rows.
  742. * @since 2.0.13
  743. */
  744. protected function normalizePdoRowKeyCase(array $row, $multiple)
  745. {
  746. if ($this->db->getSlavePdo()->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_UPPER) {
  747. return $row;
  748. }
  749. if ($multiple) {
  750. return array_map(function (array $row) {
  751. return array_change_key_case($row, CASE_LOWER);
  752. }, $row);
  753. }
  754. return array_change_key_case($row, CASE_LOWER);
  755. }
  756. /**
  757. * Tries to load and populate table metadata from cache.
  758. * @param Cache|null $cache
  759. * @param string $name
  760. */
  761. private function loadTableMetadataFromCache($cache, $name)
  762. {
  763. if ($cache === null) {
  764. $this->_tableMetadata[$name] = [];
  765. return;
  766. }
  767. $metadata = $cache->get($this->getCacheKey($name));
  768. if (!is_array($metadata) || !isset($metadata['cacheVersion']) || $metadata['cacheVersion'] !== static::SCHEMA_CACHE_VERSION) {
  769. $this->_tableMetadata[$name] = [];
  770. return;
  771. }
  772. unset($metadata['cacheVersion']);
  773. $this->_tableMetadata[$name] = $metadata;
  774. }
  775. /**
  776. * Saves table metadata to cache.
  777. * @param Cache|null $cache
  778. * @param string $name
  779. */
  780. private function saveTableMetadataToCache($cache, $name)
  781. {
  782. if ($cache === null) {
  783. return;
  784. }
  785. $metadata = $this->_tableMetadata[$name];
  786. $metadata['cacheVersion'] = static::SCHEMA_CACHE_VERSION;
  787. $cache->set(
  788. $this->getCacheKey($name),
  789. $metadata,
  790. $this->db->schemaCacheDuration,
  791. new TagDependency(['tags' => $this->getCacheTag()])
  792. );
  793. }
  794. }