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