CMysqlSchema.php 11 KB

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