CMssqlSchema.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. <?php
  2. /**
  3. * CMssqlSchema class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @author Christophe Boulain <Christophe.Boulain@gmail.com>
  7. * @link http://www.yiiframework.com/
  8. * @copyright 2008-2013 Yii Software LLC
  9. * @license http://www.yiiframework.com/license/
  10. */
  11. /**
  12. * CMssqlSchema is the class for retrieving metadata information from a MS SQL Server database.
  13. *
  14. * @author Qiang Xue <qiang.xue@gmail.com>
  15. * @author Christophe Boulain <Christophe.Boulain@gmail.com>
  16. * @package system.db.schema.mssql
  17. */
  18. class CMssqlSchema extends CDbSchema
  19. {
  20. const DEFAULT_SCHEMA='dbo';
  21. /**
  22. * @var array the abstract column types mapped to physical column types.
  23. * @since 1.1.6
  24. */
  25. public $columnTypes=array(
  26. 'pk' => 'int IDENTITY PRIMARY KEY',
  27. 'string' => 'varchar(255)',
  28. 'text' => 'text',
  29. 'integer' => 'int',
  30. 'float' => 'float',
  31. 'decimal' => 'decimal',
  32. 'datetime' => 'datetime',
  33. 'timestamp' => 'timestamp',
  34. 'time' => 'time',
  35. 'date' => 'date',
  36. 'binary' => 'binary',
  37. 'boolean' => 'bit',
  38. );
  39. /**
  40. * Quotes a table name for use in a query.
  41. * A simple table name does not schema prefix.
  42. * @param string $name table name
  43. * @return string the properly quoted table name
  44. * @since 1.1.6
  45. */
  46. public function quoteSimpleTableName($name)
  47. {
  48. return '['.$name.']';
  49. }
  50. /**
  51. * Quotes a column name for use in a query.
  52. * A simple column name does not contain prefix.
  53. * @param string $name column name
  54. * @return string the properly quoted column name
  55. * @since 1.1.6
  56. */
  57. public function quoteSimpleColumnName($name)
  58. {
  59. return '['.$name.']';
  60. }
  61. /**
  62. * Compares two table names.
  63. * The table names can be either quoted or unquoted. This method
  64. * will consider both cases.
  65. * @param string $name1 table name 1
  66. * @param string $name2 table name 2
  67. * @return boolean whether the two table names refer to the same table.
  68. */
  69. public function compareTableNames($name1,$name2)
  70. {
  71. $name1=str_replace(array('[',']'),'',$name1);
  72. $name2=str_replace(array('[',']'),'',$name2);
  73. return parent::compareTableNames(strtolower($name1),strtolower($name2));
  74. }
  75. /**
  76. * Resets the sequence value of a table's primary key.
  77. * The sequence will be reset such that the primary key of the next new row inserted
  78. * will have the specified value or max value of a primary key plus one (i.e. sequence trimming).
  79. * @param CDbTableSchema $table the table schema whose primary key sequence will be reset
  80. * @param integer|null $value the value for the primary key of the next new row inserted.
  81. * If this is not set, the next new row's primary key will have the max value of a primary
  82. * key plus one (i.e. sequence trimming).
  83. * @since 1.1.6
  84. */
  85. public function resetSequence($table,$value=null)
  86. {
  87. if($table->sequenceName===null)
  88. return;
  89. if($value!==null)
  90. $value=(int)($value)-1;
  91. else
  92. $value=(int)$this->getDbConnection()
  93. ->createCommand("SELECT MAX([{$table->primaryKey}]) FROM {$table->rawName}")
  94. ->queryScalar();
  95. $name=strtr($table->rawName,array('['=>'',']'=>''));
  96. $this->getDbConnection()
  97. ->createCommand("DBCC CHECKIDENT ('$name',RESEED,$value)")
  98. ->execute();
  99. }
  100. private $_normalTables=array(); // non-view tables
  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.6
  106. */
  107. public function checkIntegrity($check=true,$schema='')
  108. {
  109. $enable=$check ? 'CHECK' : 'NOCHECK';
  110. if(!isset($this->_normalTables[$schema]))
  111. $this->_normalTables[$schema]=$this->findTableNames($schema,false);
  112. $db=$this->getDbConnection();
  113. foreach($this->_normalTables[$schema] as $tableName)
  114. {
  115. $tableName=$this->quoteTableName($tableName);
  116. $db->createCommand("ALTER TABLE $tableName $enable CONSTRAINT ALL")->execute();
  117. }
  118. }
  119. /**
  120. * Loads the metadata for the specified table.
  121. * @param string $name table name
  122. * @return CMssqlTableSchema driver dependent table metadata. Null if the table does not exist.
  123. */
  124. protected function loadTable($name)
  125. {
  126. $table=new CMssqlTableSchema;
  127. $this->resolveTableNames($table,$name);
  128. //if (!in_array($table->name, $this->tableNames)) return null;
  129. $table->primaryKey=$this->findPrimaryKey($table);
  130. $table->foreignKeys=$this->findForeignKeys($table);
  131. if($this->findColumns($table))
  132. {
  133. return $table;
  134. }
  135. else
  136. return null;
  137. }
  138. /**
  139. * Generates various kinds of table names.
  140. * @param CMssqlTableSchema $table the table instance
  141. * @param string $name the unquoted table name
  142. */
  143. protected function resolveTableNames($table,$name)
  144. {
  145. $parts=explode('.',str_replace(array('[',']'),'',$name));
  146. if(($c=count($parts))==3)
  147. {
  148. // Catalog name, schema name and table name provided
  149. $table->catalogName=$parts[0];
  150. $table->schemaName=$parts[1];
  151. $table->name=$parts[2];
  152. $table->rawName=$this->quoteTableName($table->catalogName).'.'.$this->quoteTableName($table->schemaName).'.'.$this->quoteTableName($table->name);
  153. }
  154. elseif ($c==2)
  155. {
  156. // Only schema name and table name provided
  157. $table->name=$parts[1];
  158. $table->schemaName=$parts[0];
  159. $table->rawName=$this->quoteTableName($table->schemaName).'.'.$this->quoteTableName($table->name);
  160. }
  161. else
  162. {
  163. // Only the name given, we need to get at least the schema name
  164. //if (empty($this->_schemaNames)) $this->findTableNames();
  165. $table->name=$parts[0];
  166. $table->schemaName=self::DEFAULT_SCHEMA;
  167. $table->rawName=$this->quoteTableName($table->schemaName).'.'.$this->quoteTableName($table->name);
  168. }
  169. }
  170. /**
  171. * Gets the primary key column(s) details for the given table.
  172. * @param CMssqlTableSchema $table table
  173. * @return mixed primary keys (null if no pk, string if only 1 column pk, or array if composite pk)
  174. */
  175. protected function findPrimaryKey($table)
  176. {
  177. $kcu='INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
  178. $tc='INFORMATION_SCHEMA.TABLE_CONSTRAINTS';
  179. if (isset($table->catalogName))
  180. {
  181. $kcu=$table->catalogName.'.'.$kcu;
  182. $tc=$table->catalogName.'.'.$tc;
  183. }
  184. $sql = <<<EOD
  185. SELECT k.column_name field_name
  186. FROM {$this->quoteTableName($kcu)} k
  187. LEFT JOIN {$this->quoteTableName($tc)} c
  188. ON k.table_name = c.table_name
  189. AND k.constraint_name = c.constraint_name
  190. WHERE c.constraint_type ='PRIMARY KEY'
  191. AND k.table_name = :table
  192. AND k.table_schema = :schema
  193. EOD;
  194. $command = $this->getDbConnection()->createCommand($sql);
  195. $command->bindValue(':table', $table->name);
  196. $command->bindValue(':schema', $table->schemaName);
  197. $primary=$command->queryColumn();
  198. switch (count($primary))
  199. {
  200. case 0: // No primary key on table
  201. $primary=null;
  202. break;
  203. case 1: // Only 1 primary key
  204. $primary=$primary[0];
  205. break;
  206. }
  207. return $primary;
  208. }
  209. /**
  210. * Gets foreign relationship constraint keys and table name
  211. * @param CMssqlTableSchema $table table
  212. * @return array foreign relationship table name and keys.
  213. */
  214. protected function findForeignKeys($table)
  215. {
  216. $rc='INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS';
  217. $kcu='INFORMATION_SCHEMA.KEY_COLUMN_USAGE';
  218. if (isset($table->catalogName))
  219. {
  220. $kcu=$table->catalogName.'.'.$kcu;
  221. $rc=$table->catalogName.'.'.$rc;
  222. }
  223. //From http://msdn2.microsoft.com/en-us/library/aa175805(SQL.80).aspx
  224. $sql = <<<EOD
  225. SELECT
  226. KCU1.CONSTRAINT_NAME AS 'FK_CONSTRAINT_NAME'
  227. , KCU1.TABLE_NAME AS 'FK_TABLE_NAME'
  228. , KCU1.COLUMN_NAME AS 'FK_COLUMN_NAME'
  229. , KCU1.ORDINAL_POSITION AS 'FK_ORDINAL_POSITION'
  230. , KCU2.CONSTRAINT_NAME AS 'UQ_CONSTRAINT_NAME'
  231. , KCU2.TABLE_NAME AS 'UQ_TABLE_NAME'
  232. , KCU2.COLUMN_NAME AS 'UQ_COLUMN_NAME'
  233. , KCU2.ORDINAL_POSITION AS 'UQ_ORDINAL_POSITION'
  234. FROM {$this->quoteTableName($rc)} RC
  235. JOIN {$this->quoteTableName($kcu)} KCU1
  236. ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG
  237. AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
  238. AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
  239. JOIN {$this->quoteTableName($kcu)} KCU2
  240. ON KCU2.CONSTRAINT_CATALOG =
  241. RC.UNIQUE_CONSTRAINT_CATALOG
  242. AND KCU2.CONSTRAINT_SCHEMA =
  243. RC.UNIQUE_CONSTRAINT_SCHEMA
  244. AND KCU2.CONSTRAINT_NAME =
  245. RC.UNIQUE_CONSTRAINT_NAME
  246. AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION
  247. WHERE KCU1.TABLE_NAME = :table
  248. EOD;
  249. $command = $this->getDbConnection()->createCommand($sql);
  250. $command->bindValue(':table', $table->name);
  251. $fkeys=array();
  252. foreach($command->queryAll() as $info)
  253. {
  254. $fkeys[$info['FK_COLUMN_NAME']]=array($info['UQ_TABLE_NAME'],$info['UQ_COLUMN_NAME'],);
  255. }
  256. return $fkeys;
  257. }
  258. /**
  259. * Collects the table column metadata.
  260. * @param CMssqlTableSchema $table the table metadata
  261. * @return boolean whether the table exists in the database
  262. */
  263. protected function findColumns($table)
  264. {
  265. $columnsTable="INFORMATION_SCHEMA.COLUMNS";
  266. $where=array();
  267. $where[]="t1.TABLE_NAME='".$table->name."'";
  268. if (isset($table->catalogName))
  269. {
  270. $where[]="t1.TABLE_CATALOG='".$table->catalogName."'";
  271. $columnsTable = $table->catalogName.'.'.$columnsTable;
  272. }
  273. if (isset($table->schemaName))
  274. $where[]="t1.TABLE_SCHEMA='".$table->schemaName."'";
  275. $sql="SELECT t1.*, columnproperty(object_id(t1.table_schema+'.'+t1.table_name), t1.column_name, 'IsIdentity') AS IsIdentity, ".
  276. "CONVERT(VARCHAR, t2.value) AS Comment FROM ".$this->quoteTableName($columnsTable)." AS t1 ".
  277. "LEFT OUTER JOIN sys.extended_properties AS t2 ON t1.ORDINAL_POSITION = t2.minor_id AND ".
  278. "object_name(t2.major_id) = t1.TABLE_NAME AND t2.class=1 AND t2.class_desc='OBJECT_OR_COLUMN' AND t2.name='MS_Description' ".
  279. "WHERE ".join(' AND ',$where);
  280. try
  281. {
  282. $columns=$this->getDbConnection()->createCommand($sql)->queryAll();
  283. if(empty($columns))
  284. return false;
  285. }
  286. catch(Exception $e)
  287. {
  288. return false;
  289. }
  290. foreach($columns as $column)
  291. {
  292. $c=$this->createColumn($column);
  293. if (is_array($table->primaryKey))
  294. $c->isPrimaryKey=in_array($c->name, $table->primaryKey);
  295. else
  296. $c->isPrimaryKey=strcasecmp($c->name,$table->primaryKey)===0;
  297. $c->isForeignKey=isset($table->foreignKeys[$c->name]);
  298. $table->columns[$c->name]=$c;
  299. if ($c->autoIncrement && $table->sequenceName===null)
  300. $table->sequenceName=$table->name;
  301. }
  302. return true;
  303. }
  304. /**
  305. * Creates a table column.
  306. * @param array $column column metadata
  307. * @return CDbColumnSchema normalized column metadata
  308. */
  309. protected function createColumn($column)
  310. {
  311. $c=new CMssqlColumnSchema;
  312. $c->name=$column['COLUMN_NAME'];
  313. $c->rawName=$this->quoteColumnName($c->name);
  314. $c->allowNull=$column['IS_NULLABLE']=='YES';
  315. if ($column['NUMERIC_PRECISION_RADIX']!==null)
  316. {
  317. // We have a numeric datatype
  318. $c->size=$c->precision=$column['NUMERIC_PRECISION']!==null?(int)$column['NUMERIC_PRECISION']:null;
  319. $c->scale=$column['NUMERIC_SCALE']!==null?(int)$column['NUMERIC_SCALE']:null;
  320. }
  321. elseif ($column['DATA_TYPE']=='image' || $column['DATA_TYPE']=='text')
  322. $c->size=$c->precision=null;
  323. else
  324. $c->size=$c->precision=($column['CHARACTER_MAXIMUM_LENGTH']!== null)?(int)$column['CHARACTER_MAXIMUM_LENGTH']:null;
  325. $c->autoIncrement=$column['IsIdentity']==1;
  326. $c->comment=$column['Comment']===null ? '' : $column['Comment'];
  327. $c->init($column['DATA_TYPE'],$column['COLUMN_DEFAULT']);
  328. return $c;
  329. }
  330. /**
  331. * Returns all table names in the database.
  332. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  333. * If not empty, the returned table names will be prefixed with the schema name.
  334. * @param boolean $includeViews whether to include views in the result. Defaults to true.
  335. * @return array all table names in the database.
  336. */
  337. protected function findTableNames($schema='',$includeViews=true)
  338. {
  339. if($schema==='')
  340. $schema=self::DEFAULT_SCHEMA;
  341. if($includeViews)
  342. $condition="TABLE_TYPE in ('BASE TABLE','VIEW')";
  343. else
  344. $condition="TABLE_TYPE='BASE TABLE'";
  345. $sql=<<<EOD
  346. SELECT TABLE_NAME FROM [INFORMATION_SCHEMA].[TABLES]
  347. WHERE TABLE_SCHEMA=:schema AND $condition
  348. EOD;
  349. $command=$this->getDbConnection()->createCommand($sql);
  350. $command->bindParam(":schema", $schema);
  351. $rows=$command->queryAll();
  352. $names=array();
  353. foreach ($rows as $row)
  354. {
  355. if ($schema == self::DEFAULT_SCHEMA)
  356. $names[]=$row['TABLE_NAME'];
  357. else
  358. $names[]=$schema.'.'.$row['TABLE_NAME'];
  359. }
  360. return $names;
  361. }
  362. /**
  363. * Creates a command builder for the database.
  364. * This method overrides parent implementation in order to create a MSSQL specific command builder
  365. * @return CDbCommandBuilder command builder instance
  366. */
  367. protected function createCommandBuilder()
  368. {
  369. return new CMssqlCommandBuilder($this);
  370. }
  371. /**
  372. * Builds a SQL statement for renaming a DB table.
  373. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  374. * @param string $newName the new table name. The name will be properly quoted by the method.
  375. * @return string the SQL statement for renaming a DB table.
  376. * @since 1.1.6
  377. */
  378. public function renameTable($table, $newName)
  379. {
  380. return "sp_rename '$table', '$newName'";
  381. }
  382. /**
  383. * Builds a SQL statement for renaming a column.
  384. * @param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
  385. * @param string $name the old name of the column. The name will be properly quoted by the method.
  386. * @param string $newName the new name of the column. The name will be properly quoted by the method.
  387. * @return string the SQL statement for renaming a DB column.
  388. * @since 1.1.6
  389. */
  390. public function renameColumn($table, $name, $newName)
  391. {
  392. return "sp_rename '$table.$name', '$newName', 'COLUMN'";
  393. }
  394. /**
  395. * Builds a SQL statement for changing the definition of a column.
  396. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  397. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  398. * @param string $type the new column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any)
  399. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  400. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  401. * @return string the SQL statement for changing the definition of a column.
  402. * @since 1.1.6
  403. */
  404. public function alterColumn($table, $column, $type)
  405. {
  406. $type=$this->getColumnType($type);
  407. $sql='ALTER TABLE ' . $this->quoteTableName($table) . ' ALTER COLUMN '
  408. . $this->quoteColumnName($column) . ' '
  409. . $this->getColumnType($type);
  410. return $sql;
  411. }
  412. }