Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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\mysql;
  8. use yii\db\Expression;
  9. use yii\db\TableSchema;
  10. use yii\db\ColumnSchema;
  11. /**
  12. * Schema is the class for retrieving metadata from a MySQL database (version 4.1.x and 5.x).
  13. *
  14. * @author Qiang Xue <qiang.xue@gmail.com>
  15. * @since 2.0
  16. */
  17. class Schema extends \yii\db\Schema
  18. {
  19. /**
  20. * @var array mapping from physical column types (keys) to abstract column types (values)
  21. */
  22. public $typeMap = [
  23. 'tinyint' => self::TYPE_SMALLINT,
  24. 'bit' => self::TYPE_INTEGER,
  25. 'smallint' => self::TYPE_SMALLINT,
  26. 'mediumint' => self::TYPE_INTEGER,
  27. 'int' => self::TYPE_INTEGER,
  28. 'integer' => self::TYPE_INTEGER,
  29. 'bigint' => self::TYPE_BIGINT,
  30. 'float' => self::TYPE_FLOAT,
  31. 'double' => self::TYPE_DOUBLE,
  32. 'real' => self::TYPE_FLOAT,
  33. 'decimal' => self::TYPE_DECIMAL,
  34. 'numeric' => self::TYPE_DECIMAL,
  35. 'tinytext' => self::TYPE_TEXT,
  36. 'mediumtext' => self::TYPE_TEXT,
  37. 'longtext' => self::TYPE_TEXT,
  38. 'longblob' => self::TYPE_BINARY,
  39. 'blob' => self::TYPE_BINARY,
  40. 'text' => self::TYPE_TEXT,
  41. 'varchar' => self::TYPE_STRING,
  42. 'string' => self::TYPE_STRING,
  43. 'char' => self::TYPE_CHAR,
  44. 'datetime' => self::TYPE_DATETIME,
  45. 'year' => self::TYPE_DATE,
  46. 'date' => self::TYPE_DATE,
  47. 'time' => self::TYPE_TIME,
  48. 'timestamp' => self::TYPE_TIMESTAMP,
  49. 'enum' => self::TYPE_STRING,
  50. ];
  51. /**
  52. * Quotes a table name for use in a query.
  53. * A simple table name has no schema prefix.
  54. * @param string $name table name
  55. * @return string the properly quoted table name
  56. */
  57. public function quoteSimpleTableName($name)
  58. {
  59. return strpos($name, '`') !== false ? $name : "`$name`";
  60. }
  61. /**
  62. * Quotes a column name for use in a query.
  63. * A simple column name has no prefix.
  64. * @param string $name column name
  65. * @return string the properly quoted column name
  66. */
  67. public function quoteSimpleColumnName($name)
  68. {
  69. return strpos($name, '`') !== false || $name === '*' ? $name : "`$name`";
  70. }
  71. /**
  72. * Creates a query builder for the MySQL database.
  73. * @return QueryBuilder query builder instance
  74. */
  75. public function createQueryBuilder()
  76. {
  77. return new QueryBuilder($this->db);
  78. }
  79. /**
  80. * Loads the metadata for the specified table.
  81. * @param string $name table name
  82. * @return TableSchema driver dependent table metadata. Null if the table does not exist.
  83. */
  84. protected function loadTableSchema($name)
  85. {
  86. $table = new TableSchema;
  87. $this->resolveTableNames($table, $name);
  88. if ($this->findColumns($table)) {
  89. $this->findConstraints($table);
  90. return $table;
  91. } else {
  92. return null;
  93. }
  94. }
  95. /**
  96. * Resolves the table name and schema name (if any).
  97. * @param TableSchema $table the table metadata object
  98. * @param string $name the table name
  99. */
  100. protected function resolveTableNames($table, $name)
  101. {
  102. $parts = explode('.', str_replace('`', '', $name));
  103. if (isset($parts[1])) {
  104. $table->schemaName = $parts[0];
  105. $table->name = $parts[1];
  106. $table->fullName = $table->schemaName . '.' . $table->name;
  107. } else {
  108. $table->fullName = $table->name = $parts[0];
  109. }
  110. }
  111. /**
  112. * Loads the column information into a [[ColumnSchema]] object.
  113. * @param array $info column information
  114. * @return ColumnSchema the column schema object
  115. */
  116. protected function loadColumnSchema($info)
  117. {
  118. $column = $this->createColumnSchema();
  119. $column->name = $info['field'];
  120. $column->allowNull = $info['null'] === 'YES';
  121. $column->isPrimaryKey = strpos($info['key'], 'PRI') !== false;
  122. $column->autoIncrement = stripos($info['extra'], 'auto_increment') !== false;
  123. $column->comment = $info['comment'];
  124. $column->dbType = $info['type'];
  125. $column->unsigned = stripos($column->dbType, 'unsigned') !== false;
  126. $column->type = self::TYPE_STRING;
  127. if (preg_match('/^(\w+)(?:\(([^\)]+)\))?/', $column->dbType, $matches)) {
  128. $type = strtolower($matches[1]);
  129. if (isset($this->typeMap[$type])) {
  130. $column->type = $this->typeMap[$type];
  131. }
  132. if (!empty($matches[2])) {
  133. if ($type === 'enum') {
  134. $values = explode(',', $matches[2]);
  135. foreach ($values as $i => $value) {
  136. $values[$i] = trim($value, "'");
  137. }
  138. $column->enumValues = $values;
  139. } else {
  140. $values = explode(',', $matches[2]);
  141. $column->size = $column->precision = (int) $values[0];
  142. if (isset($values[1])) {
  143. $column->scale = (int) $values[1];
  144. }
  145. if ($column->size === 1 && $type === 'bit') {
  146. $column->type = 'boolean';
  147. } elseif ($type === 'bit') {
  148. if ($column->size > 32) {
  149. $column->type = 'bigint';
  150. } elseif ($column->size === 32) {
  151. $column->type = 'integer';
  152. }
  153. }
  154. }
  155. }
  156. }
  157. $column->phpType = $this->getColumnPhpType($column);
  158. if (!$column->isPrimaryKey) {
  159. if ($column->type === 'timestamp' && $info['default'] === 'CURRENT_TIMESTAMP') {
  160. $column->defaultValue = new Expression('CURRENT_TIMESTAMP');
  161. } elseif (isset($type) && $type === 'bit') {
  162. $column->defaultValue = bindec(trim($info['default'], 'b\''));
  163. } else {
  164. $column->defaultValue = $column->phpTypecast($info['default']);
  165. }
  166. }
  167. return $column;
  168. }
  169. /**
  170. * Collects the metadata of table columns.
  171. * @param TableSchema $table the table metadata
  172. * @return boolean whether the table exists in the database
  173. * @throws \Exception if DB query fails
  174. */
  175. protected function findColumns($table)
  176. {
  177. $sql = 'SHOW FULL COLUMNS FROM ' . $this->quoteTableName($table->fullName);
  178. try {
  179. $columns = $this->db->createCommand($sql)->queryAll();
  180. } catch (\Exception $e) {
  181. $previous = $e->getPrevious();
  182. if ($previous instanceof \PDOException && strpos($previous->getMessage(), 'SQLSTATE[42S02') !== false) {
  183. // table does not exist
  184. // https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_bad_table_error
  185. return false;
  186. }
  187. throw $e;
  188. }
  189. foreach ($columns as $info) {
  190. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) !== \PDO::CASE_LOWER) {
  191. $info = array_change_key_case($info, CASE_LOWER);
  192. }
  193. $column = $this->loadColumnSchema($info);
  194. $table->columns[$column->name] = $column;
  195. if ($column->isPrimaryKey) {
  196. $table->primaryKey[] = $column->name;
  197. if ($column->autoIncrement) {
  198. $table->sequenceName = '';
  199. }
  200. }
  201. }
  202. return true;
  203. }
  204. /**
  205. * Gets the CREATE TABLE sql string.
  206. * @param TableSchema $table the table metadata
  207. * @return string $sql the result of 'SHOW CREATE TABLE'
  208. */
  209. protected function getCreateTableSql($table)
  210. {
  211. $row = $this->db->createCommand('SHOW CREATE TABLE ' . $this->quoteTableName($table->fullName))->queryOne();
  212. if (isset($row['Create Table'])) {
  213. $sql = $row['Create Table'];
  214. } else {
  215. $row = array_values($row);
  216. $sql = $row[1];
  217. }
  218. return $sql;
  219. }
  220. /**
  221. * Collects the foreign key column details for the given table.
  222. * @param TableSchema $table the table metadata
  223. * @throws \Exception
  224. */
  225. protected function findConstraints($table)
  226. {
  227. $sql = <<<SQL
  228. SELECT
  229. kcu.constraint_name,
  230. kcu.column_name,
  231. kcu.referenced_table_name,
  232. kcu.referenced_column_name
  233. FROM information_schema.referential_constraints AS rc
  234. JOIN information_schema.key_column_usage AS kcu ON
  235. (
  236. kcu.constraint_catalog = rc.constraint_catalog OR
  237. (kcu.constraint_catalog IS NULL AND rc.constraint_catalog IS NULL)
  238. ) AND
  239. kcu.constraint_schema = rc.constraint_schema AND
  240. kcu.constraint_name = rc.constraint_name
  241. WHERE rc.constraint_schema = database() AND kcu.table_schema = database()
  242. AND rc.table_name = :tableName AND kcu.table_name = :tableName1
  243. SQL;
  244. try {
  245. $rows = $this->db->createCommand($sql, [':tableName' => $table->name, ':tableName1' => $table->name])->queryAll();
  246. $constraints = [];
  247. foreach ($rows as $row) {
  248. $constraints[$row['constraint_name']]['referenced_table_name'] = $row['referenced_table_name'];
  249. $constraints[$row['constraint_name']]['columns'][$row['column_name']] = $row['referenced_column_name'];
  250. }
  251. $table->foreignKeys = [];
  252. foreach ($constraints as $constraint) {
  253. $table->foreignKeys[] = array_merge(
  254. [$constraint['referenced_table_name']],
  255. $constraint['columns']
  256. );
  257. }
  258. } catch (\Exception $e) {
  259. $previous = $e->getPrevious();
  260. if (!$previous instanceof \PDOException || strpos($previous->getMessage(), 'SQLSTATE[42S02') === false) {
  261. throw $e;
  262. }
  263. // table does not exist, try to determine the foreign keys using the table creation sql
  264. $sql = $this->getCreateTableSql($table);
  265. $regexp = '/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
  266. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  267. foreach ($matches as $match) {
  268. $fks = array_map('trim', explode(',', str_replace('`', '', $match[1])));
  269. $pks = array_map('trim', explode(',', str_replace('`', '', $match[3])));
  270. $constraint = [str_replace('`', '', $match[2])];
  271. foreach ($fks as $k => $name) {
  272. $constraint[$name] = $pks[$k];
  273. }
  274. $table->foreignKeys[md5(serialize($constraint))] = $constraint;
  275. }
  276. $table->foreignKeys = array_values($table->foreignKeys);
  277. }
  278. }
  279. }
  280. /**
  281. * Returns all unique indexes for the given table.
  282. * Each array element is of the following structure:
  283. *
  284. * ```php
  285. * [
  286. * 'IndexName1' => ['col1' [, ...]],
  287. * 'IndexName2' => ['col2' [, ...]],
  288. * ]
  289. * ```
  290. *
  291. * @param TableSchema $table the table metadata
  292. * @return array all unique indexes for the given table.
  293. */
  294. public function findUniqueIndexes($table)
  295. {
  296. $sql = $this->getCreateTableSql($table);
  297. $uniqueIndexes = [];
  298. $regexp = '/UNIQUE KEY\s+([^\(\s]+)\s*\(([^\(\)]+)\)/mi';
  299. if (preg_match_all($regexp, $sql, $matches, PREG_SET_ORDER)) {
  300. foreach ($matches as $match) {
  301. $indexName = str_replace('`', '', $match[1]);
  302. $indexColumns = array_map('trim', explode(',', str_replace('`', '', $match[2])));
  303. $uniqueIndexes[$indexName] = $indexColumns;
  304. }
  305. }
  306. return $uniqueIndexes;
  307. }
  308. /**
  309. * Returns all table names in the database.
  310. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  311. * @return array all table names in the database. The names have NO schema name prefix.
  312. */
  313. protected function findTableNames($schema = '')
  314. {
  315. $sql = 'SHOW TABLES';
  316. if ($schema !== '') {
  317. $sql .= ' FROM ' . $this->quoteSimpleTableName($schema);
  318. }
  319. return $this->db->createCommand($sql)->queryColumn();
  320. }
  321. /**
  322. * @inheritdoc
  323. */
  324. public function createColumnSchemaBuilder($type, $length = null)
  325. {
  326. return new ColumnSchemaBuilder($type, $length, $this->db);
  327. }
  328. }