Schema.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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\Object;
  10. use yii\base\NotSupportedException;
  11. use yii\base\InvalidCallException;
  12. use yii\caching\Cache;
  13. use yii\caching\TagDependency;
  14. /**
  15. * Schema is the base class for concrete DBMS-specific schema classes.
  16. *
  17. * Schema represents the database schema information that is DBMS specific.
  18. *
  19. * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
  20. * sequence object. This property is read-only.
  21. * @property QueryBuilder $queryBuilder The query builder for this connection. This property is read-only.
  22. * @property string[] $schemaNames All schema names in the database, except system schemas. This property is
  23. * read-only.
  24. * @property string[] $tableNames All table names in the database. This property is read-only.
  25. * @property TableSchema[] $tableSchemas The metadata for all tables in the database. Each array element is an
  26. * instance of [[TableSchema]] or its child class. This property is read-only.
  27. * @property string $transactionIsolationLevel The transaction isolation level to use for this transaction.
  28. * This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]],
  29. * [[Transaction::REPEATABLE_READ]] and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific
  30. * syntax to be used after `SET TRANSACTION ISOLATION LEVEL`. This property is write-only.
  31. *
  32. * @author Qiang Xue <qiang.xue@gmail.com>
  33. * @since 2.0
  34. */
  35. abstract class Schema extends Object
  36. {
  37. // The following are the supported abstract column data types.
  38. const TYPE_PK = 'pk';
  39. const TYPE_UPK = 'upk';
  40. const TYPE_BIGPK = 'bigpk';
  41. const TYPE_UBIGPK = 'ubigpk';
  42. const TYPE_CHAR = 'char';
  43. const TYPE_STRING = 'string';
  44. const TYPE_TEXT = 'text';
  45. const TYPE_SMALLINT = 'smallint';
  46. const TYPE_INTEGER = 'integer';
  47. const TYPE_BIGINT = 'bigint';
  48. const TYPE_FLOAT = 'float';
  49. const TYPE_DOUBLE = 'double';
  50. const TYPE_DECIMAL = 'decimal';
  51. const TYPE_DATETIME = 'datetime';
  52. const TYPE_TIMESTAMP = 'timestamp';
  53. const TYPE_TIME = 'time';
  54. const TYPE_DATE = 'date';
  55. const TYPE_BINARY = 'binary';
  56. const TYPE_BOOLEAN = 'boolean';
  57. const TYPE_MONEY = 'money';
  58. /**
  59. * @var Connection the database connection
  60. */
  61. public $db;
  62. /**
  63. * @var string the default schema name used for the current session.
  64. */
  65. public $defaultSchema;
  66. /**
  67. * @var array map of DB errors and corresponding exceptions
  68. * If left part is found in DB error message exception class from the right part is used.
  69. */
  70. public $exceptionMap = [
  71. 'SQLSTATE[23' => 'yii\db\IntegrityException',
  72. ];
  73. /**
  74. * @var string column schema class
  75. * @since 2.0.11
  76. */
  77. public $columnSchemaClass = 'yii\db\ColumnSchema';
  78. /**
  79. * @var array list of ALL schema names in the database, except system schemas
  80. */
  81. private $_schemaNames;
  82. /**
  83. * @var array list of ALL table names in the database
  84. */
  85. private $_tableNames = [];
  86. /**
  87. * @var array list of loaded table metadata (table name => TableSchema)
  88. */
  89. private $_tables = [];
  90. /**
  91. * @var QueryBuilder the query builder for this database
  92. */
  93. private $_builder;
  94. /**
  95. * @return \yii\db\ColumnSchema
  96. * @throws \yii\base\InvalidConfigException
  97. */
  98. protected function createColumnSchema()
  99. {
  100. return Yii::createObject($this->columnSchemaClass);
  101. }
  102. /**
  103. * Loads the metadata for the specified table.
  104. * @param string $name table name
  105. * @return null|TableSchema DBMS-dependent table metadata, null if the table does not exist.
  106. */
  107. abstract protected function loadTableSchema($name);
  108. /**
  109. * Obtains the metadata for the named table.
  110. * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
  111. * @param bool $refresh whether to reload the table schema even if it is found in the cache.
  112. * @return null|TableSchema table metadata. Null if the named table does not exist.
  113. */
  114. public function getTableSchema($name, $refresh = false)
  115. {
  116. if (array_key_exists($name, $this->_tables) && !$refresh) {
  117. return $this->_tables[$name];
  118. }
  119. $db = $this->db;
  120. $realName = $this->getRawTableName($name);
  121. if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) {
  122. /* @var $cache Cache */
  123. $cache = is_string($db->schemaCache) ? Yii::$app->get($db->schemaCache, false) : $db->schemaCache;
  124. if ($cache instanceof Cache) {
  125. $key = $this->getCacheKey($name);
  126. if ($refresh || ($table = $cache->get($key)) === false) {
  127. $this->_tables[$name] = $table = $this->loadTableSchema($realName);
  128. if ($table !== null) {
  129. $cache->set($key, $table, $db->schemaCacheDuration, new TagDependency([
  130. 'tags' => $this->getCacheTag(),
  131. ]));
  132. }
  133. } else {
  134. $this->_tables[$name] = $table;
  135. }
  136. return $this->_tables[$name];
  137. }
  138. }
  139. return $this->_tables[$name] = $this->loadTableSchema($realName);
  140. }
  141. /**
  142. * Returns the cache key for the specified table name.
  143. * @param string $name the table name
  144. * @return mixed the cache key
  145. */
  146. protected function getCacheKey($name)
  147. {
  148. return [
  149. __CLASS__,
  150. $this->db->dsn,
  151. $this->db->username,
  152. $name,
  153. ];
  154. }
  155. /**
  156. * Returns the cache tag name.
  157. * This allows [[refresh()]] to invalidate all cached table schemas.
  158. * @return string the cache tag name
  159. */
  160. protected function getCacheTag()
  161. {
  162. return md5(serialize([
  163. __CLASS__,
  164. $this->db->dsn,
  165. $this->db->username,
  166. ]));
  167. }
  168. /**
  169. * Returns the metadata for all tables in the database.
  170. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
  171. * @param bool $refresh whether to fetch the latest available table schemas. If this is false,
  172. * cached data may be returned if available.
  173. * @return TableSchema[] the metadata for all tables in the database.
  174. * Each array element is an instance of [[TableSchema]] or its child class.
  175. */
  176. public function getTableSchemas($schema = '', $refresh = false)
  177. {
  178. $tables = [];
  179. foreach ($this->getTableNames($schema, $refresh) as $name) {
  180. if ($schema !== '') {
  181. $name = $schema . '.' . $name;
  182. }
  183. if (($table = $this->getTableSchema($name, $refresh)) !== null) {
  184. $tables[] = $table;
  185. }
  186. }
  187. return $tables;
  188. }
  189. /**
  190. * Returns all schema names in the database, except system schemas.
  191. * @param bool $refresh whether to fetch the latest available schema names. If this is false,
  192. * schema names fetched previously (if available) will be returned.
  193. * @return string[] all schema names in the database, except system schemas.
  194. * @since 2.0.4
  195. */
  196. public function getSchemaNames($refresh = false)
  197. {
  198. if ($this->_schemaNames === null || $refresh) {
  199. $this->_schemaNames = $this->findSchemaNames();
  200. }
  201. return $this->_schemaNames;
  202. }
  203. /**
  204. * Returns all table names in the database.
  205. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
  206. * If not empty, the returned table names will be prefixed with the schema name.
  207. * @param bool $refresh whether to fetch the latest available table names. If this is false,
  208. * table names fetched previously (if available) will be returned.
  209. * @return string[] all table names in the database.
  210. */
  211. public function getTableNames($schema = '', $refresh = false)
  212. {
  213. if (!isset($this->_tableNames[$schema]) || $refresh) {
  214. $this->_tableNames[$schema] = $this->findTableNames($schema);
  215. }
  216. return $this->_tableNames[$schema];
  217. }
  218. /**
  219. * @return QueryBuilder the query builder for this connection.
  220. */
  221. public function getQueryBuilder()
  222. {
  223. if ($this->_builder === null) {
  224. $this->_builder = $this->createQueryBuilder();
  225. }
  226. return $this->_builder;
  227. }
  228. /**
  229. * Determines the PDO type for the given PHP data value.
  230. * @param mixed $data the data whose PDO type is to be determined
  231. * @return int the PDO type
  232. * @see http://www.php.net/manual/en/pdo.constants.php
  233. */
  234. public function getPdoType($data)
  235. {
  236. static $typeMap = [
  237. // php type => PDO type
  238. 'boolean' => \PDO::PARAM_BOOL,
  239. 'integer' => \PDO::PARAM_INT,
  240. 'string' => \PDO::PARAM_STR,
  241. 'resource' => \PDO::PARAM_LOB,
  242. 'NULL' => \PDO::PARAM_NULL,
  243. ];
  244. $type = gettype($data);
  245. return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
  246. }
  247. /**
  248. * Refreshes the schema.
  249. * This method cleans up all cached table schemas so that they can be re-created later
  250. * to reflect the database schema change.
  251. */
  252. public function refresh()
  253. {
  254. /* @var $cache Cache */
  255. $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
  256. if ($this->db->enableSchemaCache && $cache instanceof Cache) {
  257. TagDependency::invalidate($cache, $this->getCacheTag());
  258. }
  259. $this->_tableNames = [];
  260. $this->_tables = [];
  261. }
  262. /**
  263. * Refreshes the particular table schema.
  264. * This method cleans up cached table schema so that it can be re-created later
  265. * to reflect the database schema change.
  266. * @param string $name table name.
  267. * @since 2.0.6
  268. */
  269. public function refreshTableSchema($name)
  270. {
  271. unset($this->_tables[$name]);
  272. $this->_tableNames = [];
  273. /* @var $cache Cache */
  274. $cache = is_string($this->db->schemaCache) ? Yii::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
  275. if ($this->db->enableSchemaCache && $cache instanceof Cache) {
  276. $cache->delete($this->getCacheKey($name));
  277. }
  278. }
  279. /**
  280. * Creates a query builder for the database.
  281. * This method may be overridden by child classes to create a DBMS-specific query builder.
  282. * @return QueryBuilder query builder instance
  283. */
  284. public function createQueryBuilder()
  285. {
  286. return new QueryBuilder($this->db);
  287. }
  288. /**
  289. * Create a column schema builder instance giving the type and value precision.
  290. *
  291. * This method may be overridden by child classes to create a DBMS-specific column schema builder.
  292. *
  293. * @param string $type type of the column. See [[ColumnSchemaBuilder::$type]].
  294. * @param int|string|array $length length or precision of the column. See [[ColumnSchemaBuilder::$length]].
  295. * @return ColumnSchemaBuilder column schema builder instance
  296. * @since 2.0.6
  297. */
  298. public function createColumnSchemaBuilder($type, $length = null)
  299. {
  300. return new ColumnSchemaBuilder($type, $length);
  301. }
  302. /**
  303. * Returns all schema names in the database, including the default one but not system schemas.
  304. * This method should be overridden by child classes in order to support this feature
  305. * because the default implementation simply throws an exception.
  306. * @return array all schema names in the database, except system schemas
  307. * @throws NotSupportedException if this method is called
  308. * @since 2.0.4
  309. */
  310. protected function findSchemaNames()
  311. {
  312. throw new NotSupportedException(get_class($this) . ' does not support fetching all schema names.');
  313. }
  314. /**
  315. * Returns all table names in the database.
  316. * This method should be overridden by child classes in order to support this feature
  317. * because the default implementation simply throws an exception.
  318. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  319. * @return array all table names in the database. The names have NO schema name prefix.
  320. * @throws NotSupportedException if this method is called
  321. */
  322. protected function findTableNames($schema = '')
  323. {
  324. throw new NotSupportedException(get_class($this) . ' does not support fetching all table names.');
  325. }
  326. /**
  327. * Returns all unique indexes for the given table.
  328. * Each array element is of the following structure:
  329. *
  330. * ```php
  331. * [
  332. * 'IndexName1' => ['col1' [, ...]],
  333. * 'IndexName2' => ['col2' [, ...]],
  334. * ]
  335. * ```
  336. *
  337. * This method should be overridden by child classes in order to support this feature
  338. * because the default implementation simply throws an exception
  339. * @param TableSchema $table the table metadata
  340. * @return array all unique indexes for the given table.
  341. * @throws NotSupportedException if this method is called
  342. */
  343. public function findUniqueIndexes($table)
  344. {
  345. throw new NotSupportedException(get_class($this) . ' does not support getting unique indexes information.');
  346. }
  347. /**
  348. * Returns the ID of the last inserted row or sequence value.
  349. * @param string $sequenceName name of the sequence object (required by some DBMS)
  350. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  351. * @throws InvalidCallException if the DB connection is not active
  352. * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
  353. */
  354. public function getLastInsertID($sequenceName = '')
  355. {
  356. if ($this->db->isActive) {
  357. return $this->db->pdo->lastInsertId($sequenceName === '' ? null : $this->quoteTableName($sequenceName));
  358. } else {
  359. throw new InvalidCallException('DB Connection is not active.');
  360. }
  361. }
  362. /**
  363. * @return bool whether this DBMS supports [savepoint](http://en.wikipedia.org/wiki/Savepoint).
  364. */
  365. public function supportsSavepoint()
  366. {
  367. return $this->db->enableSavepoint;
  368. }
  369. /**
  370. * Creates a new savepoint.
  371. * @param string $name the savepoint name
  372. */
  373. public function createSavepoint($name)
  374. {
  375. $this->db->createCommand("SAVEPOINT $name")->execute();
  376. }
  377. /**
  378. * Releases an existing savepoint.
  379. * @param string $name the savepoint name
  380. */
  381. public function releaseSavepoint($name)
  382. {
  383. $this->db->createCommand("RELEASE SAVEPOINT $name")->execute();
  384. }
  385. /**
  386. * Rolls back to a previously created savepoint.
  387. * @param string $name the savepoint name
  388. */
  389. public function rollBackSavepoint($name)
  390. {
  391. $this->db->createCommand("ROLLBACK TO SAVEPOINT $name")->execute();
  392. }
  393. /**
  394. * Sets the isolation level of the current transaction.
  395. * @param string $level The transaction isolation level to use for this transaction.
  396. * This can be one of [[Transaction::READ_UNCOMMITTED]], [[Transaction::READ_COMMITTED]], [[Transaction::REPEATABLE_READ]]
  397. * and [[Transaction::SERIALIZABLE]] but also a string containing DBMS specific syntax to be used
  398. * after `SET TRANSACTION ISOLATION LEVEL`.
  399. * @see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels
  400. */
  401. public function setTransactionIsolationLevel($level)
  402. {
  403. $this->db->createCommand("SET TRANSACTION ISOLATION LEVEL $level")->execute();
  404. }
  405. /**
  406. * Executes the INSERT command, returning primary key values.
  407. * @param string $table the table that new rows will be inserted into.
  408. * @param array $columns the column data (name => value) to be inserted into the table.
  409. * @return array|false primary key values or false if the command fails
  410. * @since 2.0.4
  411. */
  412. public function insert($table, $columns)
  413. {
  414. $command = $this->db->createCommand()->insert($table, $columns);
  415. if (!$command->execute()) {
  416. return false;
  417. }
  418. $tableSchema = $this->getTableSchema($table);
  419. $result = [];
  420. foreach ($tableSchema->primaryKey as $name) {
  421. if ($tableSchema->columns[$name]->autoIncrement) {
  422. $result[$name] = $this->getLastInsertID($tableSchema->sequenceName);
  423. break;
  424. } else {
  425. $result[$name] = isset($columns[$name]) ? $columns[$name] : $tableSchema->columns[$name]->defaultValue;
  426. }
  427. }
  428. return $result;
  429. }
  430. /**
  431. * Quotes a string value for use in a query.
  432. * Note that if the parameter is not a string, it will be returned without change.
  433. * @param string $str string to be quoted
  434. * @return string the properly quoted string
  435. * @see http://www.php.net/manual/en/function.PDO-quote.php
  436. */
  437. public function quoteValue($str)
  438. {
  439. if (!is_string($str)) {
  440. return $str;
  441. }
  442. if (($value = $this->db->getSlavePdo()->quote($str)) !== false) {
  443. return $value;
  444. } else {
  445. // the driver doesn't support quote (e.g. oci)
  446. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  447. }
  448. }
  449. /**
  450. * Quotes a table name for use in a query.
  451. * If the table name contains schema prefix, the prefix will also be properly quoted.
  452. * If the table name is already quoted or contains '(' or '{{',
  453. * then this method will do nothing.
  454. * @param string $name table name
  455. * @return string the properly quoted table name
  456. * @see quoteSimpleTableName()
  457. */
  458. public function quoteTableName($name)
  459. {
  460. if (strpos($name, '(') !== false || strpos($name, '{{') !== false) {
  461. return $name;
  462. }
  463. if (strpos($name, '.') === false) {
  464. return $this->quoteSimpleTableName($name);
  465. }
  466. $parts = explode('.', $name);
  467. foreach ($parts as $i => $part) {
  468. $parts[$i] = $this->quoteSimpleTableName($part);
  469. }
  470. return implode('.', $parts);
  471. }
  472. /**
  473. * Quotes a column name for use in a query.
  474. * If the column name contains prefix, the prefix will also be properly quoted.
  475. * If the column name is already quoted or contains '(', '[[' or '{{',
  476. * then this method will do nothing.
  477. * @param string $name column name
  478. * @return string the properly quoted column name
  479. * @see quoteSimpleColumnName()
  480. */
  481. public function quoteColumnName($name)
  482. {
  483. if (strpos($name, '(') !== false || strpos($name, '[[') !== false) {
  484. return $name;
  485. }
  486. if (($pos = strrpos($name, '.')) !== false) {
  487. $prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
  488. $name = substr($name, $pos + 1);
  489. } else {
  490. $prefix = '';
  491. }
  492. if (strpos($name, '{{') !== false) {
  493. return $name;
  494. }
  495. return $prefix . $this->quoteSimpleColumnName($name);
  496. }
  497. /**
  498. * Quotes a simple table name for use in a query.
  499. * A simple table name should contain the table name only without any schema prefix.
  500. * If the table name is already quoted, this method will do nothing.
  501. * @param string $name table name
  502. * @return string the properly quoted table name
  503. */
  504. public function quoteSimpleTableName($name)
  505. {
  506. return strpos($name, "'") !== false ? $name : "'" . $name . "'";
  507. }
  508. /**
  509. * Quotes a simple column name for use in a query.
  510. * A simple column name should contain the column name only without any prefix.
  511. * If the column name is already quoted or is the asterisk character '*', this method will do nothing.
  512. * @param string $name column name
  513. * @return string the properly quoted column name
  514. */
  515. public function quoteSimpleColumnName($name)
  516. {
  517. return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
  518. }
  519. /**
  520. * Returns the actual name of a given table name.
  521. * This method will strip off curly brackets from the given table name
  522. * and replace the percentage character '%' with [[Connection::tablePrefix]].
  523. * @param string $name the table name to be converted
  524. * @return string the real name of the given table name
  525. */
  526. public function getRawTableName($name)
  527. {
  528. if (strpos($name, '{{') !== false) {
  529. $name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
  530. return str_replace('%', $this->db->tablePrefix, $name);
  531. } else {
  532. return $name;
  533. }
  534. }
  535. /**
  536. * Extracts the PHP type from abstract DB type.
  537. * @param ColumnSchema $column the column schema information
  538. * @return string PHP type name
  539. */
  540. protected function getColumnPhpType($column)
  541. {
  542. static $typeMap = [
  543. // abstract type => php type
  544. 'smallint' => 'integer',
  545. 'integer' => 'integer',
  546. 'bigint' => 'integer',
  547. 'boolean' => 'boolean',
  548. 'float' => 'double',
  549. 'double' => 'double',
  550. 'binary' => 'resource',
  551. ];
  552. if (isset($typeMap[$column->type])) {
  553. if ($column->type === 'bigint') {
  554. return PHP_INT_SIZE === 8 && !$column->unsigned ? 'integer' : 'string';
  555. } elseif ($column->type === 'integer') {
  556. return PHP_INT_SIZE === 4 && $column->unsigned ? 'string' : 'integer';
  557. } else {
  558. return $typeMap[$column->type];
  559. }
  560. } else {
  561. return 'string';
  562. }
  563. }
  564. /**
  565. * Converts a DB exception to a more concrete one if possible.
  566. *
  567. * @param \Exception $e
  568. * @param string $rawSql SQL that produced exception
  569. * @return Exception
  570. */
  571. public function convertException(\Exception $e, $rawSql)
  572. {
  573. if ($e instanceof Exception) {
  574. return $e;
  575. }
  576. $exceptionClass = '\yii\db\Exception';
  577. foreach ($this->exceptionMap as $error => $class) {
  578. if (strpos($e->getMessage(), $error) !== false) {
  579. $exceptionClass = $class;
  580. }
  581. }
  582. $message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
  583. $errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
  584. return new $exceptionClass($message, $errorInfo, (int) $e->getCode(), $e);
  585. }
  586. /**
  587. * Returns a value indicating whether a SQL statement is for read purpose.
  588. * @param string $sql the SQL statement
  589. * @return bool whether a SQL statement is for read purpose.
  590. */
  591. public function isReadQuery($sql)
  592. {
  593. $pattern = '/^\s*(SELECT|SHOW|DESCRIBE)\b/i';
  594. return preg_match($pattern, $sql) > 0;
  595. }
  596. }