You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Schema.php 23KB

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