Schema.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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\GroupDependency;
  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. *
  26. * @author Qiang Xue <[email protected]>
  27. * @since 2.0
  28. */
  29. abstract class Schema extends Object
  30. {
  31. /**
  32. * The followings are the supported abstract column data types.
  33. */
  34. const TYPE_PK = 'pk';
  35. const TYPE_BIGPK = 'bigpk';
  36. const TYPE_STRING = 'string';
  37. const TYPE_TEXT = 'text';
  38. const TYPE_SMALLINT = 'smallint';
  39. const TYPE_INTEGER = 'integer';
  40. const TYPE_BIGINT = 'bigint';
  41. const TYPE_FLOAT = 'float';
  42. const TYPE_DECIMAL = 'decimal';
  43. const TYPE_DATETIME = 'datetime';
  44. const TYPE_TIMESTAMP = 'timestamp';
  45. const TYPE_TIME = 'time';
  46. const TYPE_DATE = 'date';
  47. const TYPE_BINARY = 'binary';
  48. const TYPE_BOOLEAN = 'boolean';
  49. const TYPE_MONEY = 'money';
  50. /**
  51. * @var Connection the database connection
  52. */
  53. public $db;
  54. /**
  55. * @var string the default schema name used for the current session.
  56. */
  57. public $defaultSchema;
  58. /**
  59. * @var array list of ALL table names in the database
  60. */
  61. private $_tableNames = [];
  62. /**
  63. * @var array list of loaded table metadata (table name => TableSchema)
  64. */
  65. private $_tables = [];
  66. /**
  67. * @var QueryBuilder the query builder for this database
  68. */
  69. private $_builder;
  70. /**
  71. * Loads the metadata for the specified table.
  72. * @param string $name table name
  73. * @return TableSchema DBMS-dependent table metadata, null if the table does not exist.
  74. */
  75. abstract protected function loadTableSchema($name);
  76. /**
  77. * Obtains the metadata for the named table.
  78. * @param string $name table name. The table name may contain schema name if any. Do not quote the table name.
  79. * @param boolean $refresh whether to reload the table schema even if it is found in the cache.
  80. * @return TableSchema table metadata. Null if the named table does not exist.
  81. */
  82. public function getTableSchema($name, $refresh = false)
  83. {
  84. if (isset($this->_tables[$name]) && !$refresh) {
  85. return $this->_tables[$name];
  86. }
  87. $db = $this->db;
  88. $realName = $this->getRawTableName($name);
  89. if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) {
  90. /** @var Cache $cache */
  91. $cache = is_string($db->schemaCache) ? Yii::$app->getComponent($db->schemaCache) : $db->schemaCache;
  92. if ($cache instanceof Cache) {
  93. $key = $this->getCacheKey($name);
  94. if ($refresh || ($table = $cache->get($key)) === false) {
  95. $table = $this->loadTableSchema($realName);
  96. if ($table !== null) {
  97. $cache->set($key, $table, $db->schemaCacheDuration, new GroupDependency([
  98. 'group' => $this->getCacheGroup(),
  99. ]));
  100. }
  101. }
  102. return $this->_tables[$name] = $table;
  103. }
  104. }
  105. return $this->_tables[$name] = $table = $this->loadTableSchema($realName);
  106. }
  107. /**
  108. * Returns the cache key for the specified table name.
  109. * @param string $name the table name
  110. * @return mixed the cache key
  111. */
  112. protected function getCacheKey($name)
  113. {
  114. return [
  115. __CLASS__,
  116. $this->db->dsn,
  117. $this->db->username,
  118. $name,
  119. ];
  120. }
  121. /**
  122. * Returns the cache group name.
  123. * This allows [[refresh()]] to invalidate all cached table schemas.
  124. * @return string the cache group name
  125. */
  126. protected function getCacheGroup()
  127. {
  128. return md5(serialize([
  129. __CLASS__,
  130. $this->db->dsn,
  131. $this->db->username,
  132. ]));
  133. }
  134. /**
  135. * Returns the metadata for all tables in the database.
  136. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
  137. * @param boolean $refresh whether to fetch the latest available table schemas. If this is false,
  138. * cached data may be returned if available.
  139. * @return TableSchema[] the metadata for all tables in the database.
  140. * Each array element is an instance of [[TableSchema]] or its child class.
  141. */
  142. public function getTableSchemas($schema = '', $refresh = false)
  143. {
  144. $tables = [];
  145. foreach ($this->getTableNames($schema, $refresh) as $name) {
  146. if ($schema !== '') {
  147. $name = $schema . '.' . $name;
  148. }
  149. if (($table = $this->getTableSchema($name, $refresh)) !== null) {
  150. $tables[] = $table;
  151. }
  152. }
  153. return $tables;
  154. }
  155. /**
  156. * Returns all table names in the database.
  157. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema name.
  158. * If not empty, the returned table names will be prefixed with the schema name.
  159. * @param boolean $refresh whether to fetch the latest available table names. If this is false,
  160. * table names fetched previously (if available) will be returned.
  161. * @return string[] all table names in the database.
  162. */
  163. public function getTableNames($schema = '', $refresh = false)
  164. {
  165. if (!isset($this->_tableNames[$schema]) || $refresh) {
  166. $this->_tableNames[$schema] = $this->findTableNames($schema);
  167. }
  168. return $this->_tableNames[$schema];
  169. }
  170. /**
  171. * @return QueryBuilder the query builder for this connection.
  172. */
  173. public function getQueryBuilder()
  174. {
  175. if ($this->_builder === null) {
  176. $this->_builder = $this->createQueryBuilder();
  177. }
  178. return $this->_builder;
  179. }
  180. /**
  181. * Determines the PDO type for the given PHP data value.
  182. * @param mixed $data the data whose PDO type is to be determined
  183. * @return integer the PDO type
  184. * @see http://www.php.net/manual/en/pdo.constants.php
  185. */
  186. public function getPdoType($data)
  187. {
  188. static $typeMap = [
  189. // php type => PDO type
  190. 'boolean' => \PDO::PARAM_BOOL,
  191. 'integer' => \PDO::PARAM_INT,
  192. 'string' => \PDO::PARAM_STR,
  193. 'resource' => \PDO::PARAM_LOB,
  194. 'NULL' => \PDO::PARAM_NULL,
  195. ];
  196. $type = gettype($data);
  197. return isset($typeMap[$type]) ? $typeMap[$type] : \PDO::PARAM_STR;
  198. }
  199. /**
  200. * Refreshes the schema.
  201. * This method cleans up all cached table schemas so that they can be re-created later
  202. * to reflect the database schema change.
  203. */
  204. public function refresh()
  205. {
  206. /** @var Cache $cache */
  207. $cache = is_string($this->db->schemaCache) ? Yii::$app->getComponent($this->db->schemaCache) : $this->db->schemaCache;
  208. if ($this->db->enableSchemaCache && $cache instanceof Cache) {
  209. GroupDependency::invalidate($cache, $this->getCacheGroup());
  210. }
  211. $this->_tableNames = [];
  212. $this->_tables = [];
  213. }
  214. /**
  215. * Creates a query builder for the database.
  216. * This method may be overridden by child classes to create a DBMS-specific query builder.
  217. * @return QueryBuilder query builder instance
  218. */
  219. public function createQueryBuilder()
  220. {
  221. return new QueryBuilder($this->db);
  222. }
  223. /**
  224. * Returns all table names in the database.
  225. * This method should be overridden by child classes in order to support this feature
  226. * because the default implementation simply throws an exception.
  227. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  228. * @return array all table names in the database. The names have NO schema name prefix.
  229. * @throws NotSupportedException if this method is called
  230. */
  231. protected function findTableNames($schema = '')
  232. {
  233. throw new NotSupportedException(get_class($this) . ' does not support fetching all table names.');
  234. }
  235. /**
  236. * Returns all unique indexes for the given table.
  237. * Each array element is of the following structure:
  238. *
  239. * ~~~
  240. * [
  241. * 'IndexName1' => ['col1' [, ...]],
  242. * 'IndexName2' => ['col2' [, ...]],
  243. * ]
  244. * ~~~
  245. *
  246. * This method should be overridden by child classes in order to support this feature
  247. * because the default implementation simply throws an exception
  248. * @param TableSchema $table the table metadata
  249. * @return array all unique indexes for the given table.
  250. * @throws NotSupportedException if this method is called
  251. */
  252. public function findUniqueIndexes($table)
  253. {
  254. throw new NotSupportedException(get_class($this) . ' does not support getting unique indexes information.');
  255. }
  256. /**
  257. * Returns the ID of the last inserted row or sequence value.
  258. * @param string $sequenceName name of the sequence object (required by some DBMS)
  259. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  260. * @throws InvalidCallException if the DB connection is not active
  261. * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php
  262. */
  263. public function getLastInsertID($sequenceName = '')
  264. {
  265. if ($this->db->isActive) {
  266. return $this->db->pdo->lastInsertId($sequenceName);
  267. } else {
  268. throw new InvalidCallException('DB Connection is not active.');
  269. }
  270. }
  271. /**
  272. * Quotes a string value for use in a query.
  273. * Note that if the parameter is not a string, it will be returned without change.
  274. * @param string $str string to be quoted
  275. * @return string the properly quoted string
  276. * @see http://www.php.net/manual/en/function.PDO-quote.php
  277. */
  278. public function quoteValue($str)
  279. {
  280. if (!is_string($str)) {
  281. return $str;
  282. }
  283. $this->db->open();
  284. if (($value = $this->db->pdo->quote($str)) !== false) {
  285. return $value;
  286. } else { // the driver doesn't support quote (e.g. oci)
  287. return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
  288. }
  289. }
  290. /**
  291. * Quotes a table name for use in a query.
  292. * If the table name contains schema prefix, the prefix will also be properly quoted.
  293. * If the table name is already quoted or contains '(' or '{{',
  294. * then this method will do nothing.
  295. * @param string $name table name
  296. * @return string the properly quoted table name
  297. * @see quoteSimpleTableName()
  298. */
  299. public function quoteTableName($name)
  300. {
  301. if (strpos($name, '(') !== false || strpos($name, '{{') !== false) {
  302. return $name;
  303. }
  304. if (strpos($name, '.') === false) {
  305. return $this->quoteSimpleTableName($name);
  306. }
  307. $parts = explode('.', $name);
  308. foreach ($parts as $i => $part) {
  309. $parts[$i] = $this->quoteSimpleTableName($part);
  310. }
  311. return implode('.', $parts);
  312. }
  313. /**
  314. * Quotes a column name for use in a query.
  315. * If the column name contains prefix, the prefix will also be properly quoted.
  316. * If the column name is already quoted or contains '(', '[[' or '{{',
  317. * then this method will do nothing.
  318. * @param string $name column name
  319. * @return string the properly quoted column name
  320. * @see quoteSimpleColumnName()
  321. */
  322. public function quoteColumnName($name)
  323. {
  324. if (strpos($name, '(') !== false || strpos($name, '[[') !== false || strpos($name, '{{') !== false) {
  325. return $name;
  326. }
  327. if (($pos = strrpos($name, '.')) !== false) {
  328. $prefix = $this->quoteTableName(substr($name, 0, $pos)) . '.';
  329. $name = substr($name, $pos + 1);
  330. } else {
  331. $prefix = '';
  332. }
  333. return $prefix . $this->quoteSimpleColumnName($name);
  334. }
  335. /**
  336. * Quotes a simple table name for use in a query.
  337. * A simple table name should contain the table name only without any schema prefix.
  338. * If the table name is already quoted, this method will do nothing.
  339. * @param string $name table name
  340. * @return string the properly quoted table name
  341. */
  342. public function quoteSimpleTableName($name)
  343. {
  344. return strpos($name, "'") !== false ? $name : "'" . $name . "'";
  345. }
  346. /**
  347. * Quotes a simple column name for use in a query.
  348. * A simple column name should contain the column name only without any prefix.
  349. * If the column name is already quoted or is the asterisk character '*', this method will do nothing.
  350. * @param string $name column name
  351. * @return string the properly quoted column name
  352. */
  353. public function quoteSimpleColumnName($name)
  354. {
  355. return strpos($name, '"') !== false || $name === '*' ? $name : '"' . $name . '"';
  356. }
  357. /**
  358. * Returns the actual name of a given table name.
  359. * This method will strip off curly brackets from the given table name
  360. * and replace the percentage character '%' with [[Connection::tablePrefix]].
  361. * @param string $name the table name to be converted
  362. * @return string the real name of the given table name
  363. */
  364. public function getRawTableName($name)
  365. {
  366. if (strpos($name, '{{') !== false) {
  367. $name = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $name);
  368. return str_replace('%', $this->db->tablePrefix, $name);
  369. } else {
  370. return $name;
  371. }
  372. }
  373. /**
  374. * Extracts the PHP type from abstract DB type.
  375. * @param ColumnSchema $column the column schema information
  376. * @return string PHP type name
  377. */
  378. protected function getColumnPhpType($column)
  379. {
  380. static $typeMap = [ // abstract type => php type
  381. 'smallint' => 'integer',
  382. 'integer' => 'integer',
  383. 'bigint' => 'integer',
  384. 'boolean' => 'boolean',
  385. 'float' => 'double',
  386. ];
  387. if (isset($typeMap[$column->type])) {
  388. if ($column->type === 'bigint') {
  389. return PHP_INT_SIZE == 8 && !$column->unsigned ? 'integer' : 'string';
  390. } elseif ($column->type === 'integer') {
  391. return PHP_INT_SIZE == 4 && $column->unsigned ? 'string' : 'integer';
  392. } else {
  393. return $typeMap[$column->type];
  394. }
  395. } else {
  396. return 'string';
  397. }
  398. }
  399. }