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.

548 lines
19KB

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