No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

Schema.php 23KB

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