CMysqlSchema.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. <?php
  2. /**
  3. * CMysqlSchema class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CMysqlSchema is the class for retrieving metadata information from a MySQL database (version 4.1.x and 5.x).
  12. *
  13. * @author Qiang Xue <qiang.xue@gmail.com>
  14. * @package system.db.schema.mysql
  15. * @since 1.0
  16. */
  17. class CMysqlSchema extends CDbSchema
  18. {
  19. /**
  20. * @var array the abstract column types mapped to physical column types.
  21. * @since 1.1.6
  22. */
  23. public $columnTypes=array(
  24. 'pk' => 'int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY',
  25. 'string' => 'varchar(255)',
  26. 'text' => 'text',
  27. 'integer' => 'int(11)',
  28. 'float' => 'float',
  29. 'decimal' => 'decimal',
  30. 'datetime' => 'datetime',
  31. 'timestamp' => 'timestamp',
  32. 'time' => 'time',
  33. 'date' => 'date',
  34. 'binary' => 'blob',
  35. 'boolean' => 'tinyint(1)',
  36. 'money' => 'decimal(19,4)',
  37. );
  38. /**
  39. * Quotes a table name for use in a query.
  40. * A simple table name does not schema prefix.
  41. * @param string $name table name
  42. * @return string the properly quoted table name
  43. * @since 1.1.6
  44. */
  45. public function quoteSimpleTableName($name)
  46. {
  47. return '`'.$name.'`';
  48. }
  49. /**
  50. * Quotes a column name for use in a query.
  51. * A simple column name does not contain prefix.
  52. * @param string $name column name
  53. * @return string the properly quoted column name
  54. * @since 1.1.6
  55. */
  56. public function quoteSimpleColumnName($name)
  57. {
  58. return '`'.$name.'`';
  59. }
  60. /**
  61. * Compares two table names.
  62. * The table names can be either quoted or unquoted. This method
  63. * will consider both cases.
  64. * @param string $name1 table name 1
  65. * @param string $name2 table name 2
  66. * @return boolean whether the two table names refer to the same table.
  67. */
  68. public function compareTableNames($name1,$name2)
  69. {
  70. return parent::compareTableNames(strtolower($name1),strtolower($name2));
  71. }
  72. /**
  73. * Resets the sequence value of a table's primary key.
  74. * The sequence will be reset such that the primary key of the next new row inserted
  75. * will have the specified value or max value of a primary key plus one (i.e. sequence trimming).
  76. * @param CDbTableSchema $table the table schema whose primary key sequence will be reset
  77. * @param integer|null $value the value for the primary key of the next new row inserted.
  78. * If this is not set, the next new row's primary key will have the max value of a primary
  79. * key plus one (i.e. sequence trimming).
  80. * @since 1.1
  81. */
  82. public function resetSequence($table,$value=null)
  83. {
  84. if($table->sequenceName===null)
  85. return;
  86. if($value!==null)
  87. $value=(int)$value;
  88. else
  89. {
  90. $value=(int)$this->getDbConnection()
  91. ->createCommand("SELECT MAX(`{$table->primaryKey}`) FROM {$table->rawName}")
  92. ->queryScalar();
  93. $value++;
  94. }
  95. $this->getDbConnection()
  96. ->createCommand("ALTER TABLE {$table->rawName} AUTO_INCREMENT=$value")
  97. ->execute();
  98. }
  99. /**
  100. * Enables or disables integrity check.
  101. * @param boolean $check whether to turn on or off the integrity check.
  102. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  103. * @since 1.1
  104. */
  105. public function checkIntegrity($check=true,$schema='')
  106. {
  107. $this->getDbConnection()->createCommand('SET FOREIGN_KEY_CHECKS='.($check?1:0))->execute();
  108. }
  109. /**
  110. * Loads the metadata for the specified table.
  111. * @param string $name table name
  112. * @return CMysqlTableSchema driver dependent table metadata. Null if the table does not exist.
  113. */
  114. protected function loadTable($name)
  115. {
  116. $table=new CMysqlTableSchema;
  117. $this->resolveTableNames($table,$name);
  118. if($this->findColumns($table))
  119. {
  120. $this->findConstraints($table);
  121. return $table;
  122. }
  123. else
  124. return null;
  125. }
  126. /**
  127. * Generates various kinds of table names.
  128. * @param CMysqlTableSchema $table the table instance
  129. * @param string $name the unquoted table name
  130. */
  131. protected function resolveTableNames($table,$name)
  132. {
  133. $parts=explode('.',str_replace(array('`','"'),'',$name));
  134. if(isset($parts[1]))
  135. {
  136. $table->schemaName=$parts[0];
  137. $table->name=$parts[1];
  138. $table->rawName=$this->quoteTableName($table->schemaName).'.'.$this->quoteTableName($table->name);
  139. }
  140. else
  141. {
  142. $table->name=$parts[0];
  143. $table->rawName=$this->quoteTableName($table->name);
  144. }
  145. }
  146. /**
  147. * Collects the table column metadata.
  148. * @param CMysqlTableSchema $table the table metadata
  149. * @return boolean whether the table exists in the database
  150. */
  151. protected function findColumns($table)
  152. {
  153. $sql='SHOW FULL COLUMNS FROM '.$table->rawName;
  154. try
  155. {
  156. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  157. }
  158. catch(Exception $e)
  159. {
  160. return false;
  161. }
  162. foreach($columns as $column)
  163. {
  164. $c=$this->createColumn($column);
  165. $table->columns[$c->name]=$c;
  166. if($c->isPrimaryKey)
  167. {
  168. if($table->primaryKey===null)
  169. $table->primaryKey=$c->name;
  170. elseif(is_string($table->primaryKey))
  171. $table->primaryKey=array($table->primaryKey,$c->name);
  172. else
  173. $table->primaryKey[]=$c->name;
  174. if($c->autoIncrement)
  175. $table->sequenceName='';
  176. }
  177. }
  178. return true;
  179. }
  180. /**
  181. * Creates a table column.
  182. * @param array $column column metadata
  183. * @return CDbColumnSchema normalized column metadata
  184. */
  185. protected function createColumn($column)
  186. {
  187. $c=new CMysqlColumnSchema;
  188. $c->name=$column['Field'];
  189. $c->rawName=$this->quoteColumnName($c->name);
  190. $c->allowNull=$column['Null']==='YES';
  191. $c->isPrimaryKey=strpos($column['Key'],'PRI')!==false;
  192. $c->isForeignKey=false;
  193. $c->init($column['Type'],$column['Default']);
  194. $c->autoIncrement=strpos(strtolower($column['Extra']),'auto_increment')!==false;
  195. if(isset($column['Comment']))
  196. $c->comment=$column['Comment'];
  197. return $c;
  198. }
  199. /**
  200. * @return float server version.
  201. */
  202. protected function getServerVersion()
  203. {
  204. $version=$this->getDbConnection()->getAttribute(PDO::ATTR_SERVER_VERSION);
  205. $digits=array();
  206. preg_match('/(\d+)\.(\d+)\.(\d+)/', $version, $digits);
  207. return floatval($digits[1].'.'.$digits[2].$digits[3]);
  208. }
  209. /**
  210. * Collects the foreign key column details for the given table.
  211. * @param CMysqlTableSchema $table the table metadata
  212. */
  213. protected function findConstraints($table)
  214. {
  215. $row=$this->getDbConnection()->createCommand('SHOW CREATE TABLE '.$table->rawName)->queryRow();
  216. $matches=array();
  217. $regexp='/FOREIGN KEY\s+\(([^\)]+)\)\s+REFERENCES\s+([^\(^\s]+)\s*\(([^\)]+)\)/mi';
  218. foreach($row as $sql)
  219. {
  220. if(preg_match_all($regexp,$sql,$matches,PREG_SET_ORDER))
  221. break;
  222. }
  223. foreach($matches as $match)
  224. {
  225. $keys=array_map('trim',explode(',',str_replace(array('`','"'),'',$match[1])));
  226. $fks=array_map('trim',explode(',',str_replace(array('`','"'),'',$match[3])));
  227. foreach($keys as $k=>$name)
  228. {
  229. $table->foreignKeys[$name]=array(str_replace(array('`','"'),'',$match[2]),$fks[$k]);
  230. if(isset($table->columns[$name]))
  231. $table->columns[$name]->isForeignKey=true;
  232. }
  233. }
  234. }
  235. /**
  236. * Returns all table names in the database.
  237. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  238. * If not empty, the returned table names will be prefixed with the schema name.
  239. * @return array all table names in the database.
  240. */
  241. protected function findTableNames($schema='')
  242. {
  243. if($schema==='')
  244. return $this->getDbConnection()->createCommand('SHOW TABLES')->queryColumn();
  245. $names=$this->getDbConnection()->createCommand('SHOW TABLES FROM '.$this->quoteTableName($schema))->queryColumn();
  246. foreach($names as &$name)
  247. $name=$schema.'.'.$name;
  248. return $names;
  249. }
  250. /**
  251. * Creates a command builder for the database.
  252. * This method overrides parent implementation in order to create a MySQL specific command builder
  253. * @return CDbCommandBuilder command builder instance
  254. * @since 1.1.13
  255. */
  256. protected function createCommandBuilder()
  257. {
  258. return new CMysqlCommandBuilder($this);
  259. }
  260. /**
  261. * Builds a SQL statement for renaming a column.
  262. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  263. * @param string $name the old name of the column. The name will be properly quoted by the method.
  264. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  265. * @throws CDbException if specified column is not found in given table
  266. * @return string the SQL statement for renaming a DB column.
  267. * @since 1.1.6
  268. */
  269. public function renameColumn($table, $name, $newName)
  270. {
  271. $db=$this->getDbConnection();
  272. $row=$db->createCommand('SHOW CREATE TABLE '.$db->quoteTableName($table))->queryRow();
  273. if($row===false)
  274. throw new CDbException(Yii::t('yii','Unable to find "{column}" in table "{table}".',array('{column}'=>$name,'{table}'=>$table)));
  275. if(isset($row['Create Table']))
  276. $sql=$row['Create Table'];
  277. else
  278. {
  279. $row=array_values($row);
  280. $sql=$row[1];
  281. }
  282. if(preg_match_all('/^\s*[`"](.*?)[`"]\s+(.*?),?$/m',$sql,$matches))
  283. {
  284. foreach($matches[1] as $i=>$c)
  285. {
  286. if($c===$name)
  287. {
  288. return "ALTER TABLE ".$db->quoteTableName($table)
  289. . " CHANGE ".$db->quoteColumnName($name)
  290. . ' '.$db->quoteColumnName($newName).' '.$matches[2][$i];
  291. }
  292. }
  293. }
  294. // try to give back a SQL anyway
  295. return "ALTER TABLE ".$db->quoteTableName($table)
  296. . " CHANGE ".$db->quoteColumnName($name).' '.$newName;
  297. }
  298. /**
  299. * Builds a SQL statement for dropping a foreign key constraint.
  300. * @param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
  301. * @param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
  302. * @return string the SQL statement for dropping a foreign key constraint.
  303. * @since 1.1.6
  304. */
  305. public function dropForeignKey($name, $table)
  306. {
  307. return 'ALTER TABLE '.$this->quoteTableName($table)
  308. .' DROP FOREIGN KEY '.$this->quoteColumnName($name);
  309. }
  310. /**
  311. * Builds a SQL statement for removing a primary key constraint to an existing table.
  312. * @param string $name the name of the primary key constraint to be removed.
  313. * @param string $table the table that the primary key constraint will be removed from.
  314. * @return string the SQL statement for removing a primary key constraint from an existing table.
  315. * @since 1.1.13
  316. */
  317. public function dropPrimaryKey($name,$table)
  318. {
  319. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' DROP PRIMARY KEY';
  320. }
  321. /**
  322. * Builds a SQL statement for adding a primary key constraint to a table.
  323. * @param string $name not used in the MySQL syntax, the primary key is always called PRIMARY and is reserved.
  324. * @param string $table the table that the primary key constraint will be added to.
  325. * @param string|array $columns comma separated string or array of columns that the primary key will consist of.
  326. * @return string the SQL statement for adding a primary key constraint to an existing table.
  327. * @since 1.1.14
  328. */
  329. public function addPrimaryKey($name,$table,$columns)
  330. {
  331. if(is_string($columns))
  332. $columns=preg_split('/\s*,\s*/',$columns,-1,PREG_SPLIT_NO_EMPTY);
  333. foreach($columns as $i=>$col)
  334. $columns[$i]=$this->quoteColumnName($col);
  335. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' ADD PRIMARY KEY ('
  336. . implode(', ', $columns). ' )';
  337. }
  338. }