Schema.php 31 KB

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