SQLServerSchemaManager.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.phpdoctrine.org>.
  18. */
  19. namespace Doctrine\DBAL\Schema;
  20. use Doctrine\DBAL\Events;
  21. use Doctrine\DBAL\Event\SchemaIndexDefinitionEventArgs;
  22. use Doctrine\DBAL\Driver\SQLSrv\SQLSrvException;
  23. /**
  24. * SQL Server Schema Manager
  25. *
  26. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  27. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  28. * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
  29. * @author Juozas Kaziukenas <juozas@juokaz.com>
  30. * @since 2.0
  31. */
  32. class SQLServerSchemaManager extends AbstractSchemaManager
  33. {
  34. /**
  35. * @override
  36. */
  37. protected function _getPortableTableColumnDefinition($tableColumn)
  38. {
  39. $dbType = strtolower($tableColumn['TYPE_NAME']);
  40. $autoincrement = false;
  41. if (stripos($dbType, 'identity')) {
  42. $dbType = trim(str_ireplace('identity', '', $dbType));
  43. $autoincrement = true;
  44. }
  45. $dbType = strtok($dbType, '(), ');
  46. $type = array();
  47. $unsigned = $fixed = null;
  48. if (!isset($tableColumn['name'])) {
  49. $tableColumn['name'] = '';
  50. }
  51. $default = $tableColumn['COLUMN_DEF'];
  52. while ($default != ($default2 = preg_replace("/^\((.*)\)$/", '$1', $default))) {
  53. $default = trim($default2, "'");
  54. }
  55. $length = (int) $tableColumn['LENGTH'];
  56. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  57. switch ($type) {
  58. case 'char':
  59. if ($tableColumn['LENGTH'] == '1') {
  60. $type = 'boolean';
  61. if (preg_match('/^(is|has)/', $tableColumn['name'])) {
  62. $type = array_reverse($type);
  63. }
  64. }
  65. $fixed = true;
  66. break;
  67. case 'text':
  68. $fixed = false;
  69. break;
  70. }
  71. switch ($dbType) {
  72. case 'nchar':
  73. case 'nvarchar':
  74. case 'ntext':
  75. // Unicode data requires 2 bytes per character
  76. $length = $length / 2;
  77. break;
  78. }
  79. $options = array(
  80. 'length' => ($length == 0 || !in_array($type, array('text', 'string'))) ? null : $length,
  81. 'unsigned' => (bool) $unsigned,
  82. 'fixed' => (bool) $fixed,
  83. 'default' => $default !== 'NULL' ? $default : null,
  84. 'notnull' => (bool) ($tableColumn['IS_NULLABLE'] != 'YES'),
  85. 'scale' => $tableColumn['SCALE'],
  86. 'precision' => $tableColumn['PRECISION'],
  87. 'autoincrement' => $autoincrement,
  88. );
  89. return new Column($tableColumn['COLUMN_NAME'], \Doctrine\DBAL\Types\Type::getType($type), $options);
  90. }
  91. /**
  92. * @override
  93. */
  94. protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
  95. {
  96. // TODO: Remove code duplication with AbstractSchemaManager;
  97. $result = array();
  98. foreach ($tableIndexRows as $tableIndex) {
  99. $indexName = $keyName = $tableIndex['index_name'];
  100. if (strpos($tableIndex['index_description'], 'primary key') !== false) {
  101. $keyName = 'primary';
  102. }
  103. $keyName = strtolower($keyName);
  104. $flags = array();
  105. if (strpos($tableIndex['index_description'], 'clustered') !== false) {
  106. $flags[] = 'clustered';
  107. } else if (strpos($tableIndex['index_description'], 'nonclustered') !== false) {
  108. $flags[] = 'nonclustered';
  109. }
  110. $result[$keyName] = array(
  111. 'name' => $indexName,
  112. 'columns' => explode(', ', $tableIndex['index_keys']),
  113. 'unique' => strpos($tableIndex['index_description'], 'unique') !== false,
  114. 'primary' => strpos($tableIndex['index_description'], 'primary key') !== false,
  115. 'flags' => $flags,
  116. );
  117. }
  118. $eventManager = $this->_platform->getEventManager();
  119. $indexes = array();
  120. foreach ($result as $indexKey => $data) {
  121. $index = null;
  122. $defaultPrevented = false;
  123. if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaIndexDefinition)) {
  124. $eventArgs = new SchemaIndexDefinitionEventArgs($data, $tableName, $this->_conn);
  125. $eventManager->dispatchEvent(Events::onSchemaIndexDefinition, $eventArgs);
  126. $defaultPrevented = $eventArgs->isDefaultPrevented();
  127. $index = $eventArgs->getIndex();
  128. }
  129. if ( ! $defaultPrevented) {
  130. $index = new Index($data['name'], $data['columns'], $data['unique'], $data['primary']);
  131. }
  132. if ($index) {
  133. $indexes[$indexKey] = $index;
  134. }
  135. }
  136. return $indexes;
  137. }
  138. /**
  139. * @override
  140. */
  141. public function _getPortableTableForeignKeyDefinition($tableForeignKey)
  142. {
  143. return new ForeignKeyConstraint(
  144. (array) $tableForeignKey['ColumnName'],
  145. $tableForeignKey['ReferenceTableName'],
  146. (array) $tableForeignKey['ReferenceColumnName'],
  147. $tableForeignKey['ForeignKey'],
  148. array(
  149. 'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
  150. 'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']),
  151. )
  152. );
  153. }
  154. /**
  155. * @override
  156. */
  157. protected function _getPortableTableDefinition($table)
  158. {
  159. return $table['name'];
  160. }
  161. /**
  162. * @override
  163. */
  164. protected function _getPortableDatabaseDefinition($database)
  165. {
  166. return $database['name'];
  167. }
  168. /**
  169. * @override
  170. */
  171. protected function _getPortableViewDefinition($view)
  172. {
  173. // @todo
  174. return new View($view['name'], null);
  175. }
  176. /**
  177. * List the indexes for a given table returning an array of Index instances.
  178. *
  179. * Keys of the portable indexes list are all lower-cased.
  180. *
  181. * @param string $table The name of the table
  182. * @return Index[] $tableIndexes
  183. */
  184. public function listTableIndexes($table)
  185. {
  186. $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
  187. try {
  188. $tableIndexes = $this->_conn->fetchAll($sql);
  189. } catch(\PDOException $e) {
  190. if ($e->getCode() == "IMSSP") {
  191. return array();
  192. } else {
  193. throw $e;
  194. }
  195. } catch(SQLSrvException $e) {
  196. if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) {
  197. return array();
  198. } else {
  199. throw $e;
  200. }
  201. }
  202. return $this->_getPortableTableIndexesList($tableIndexes, $table);
  203. }
  204. /**
  205. * @override
  206. */
  207. public function alterTable(TableDiff $tableDiff)
  208. {
  209. if(count($tableDiff->removedColumns) > 0) {
  210. foreach($tableDiff->removedColumns as $col){
  211. $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
  212. foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) {
  213. $this->_conn->exec("ALTER TABLE $tableDiff->name DROP CONSTRAINT " . $constraint['Name']);
  214. }
  215. }
  216. }
  217. return parent::alterTable($tableDiff);
  218. }
  219. /**
  220. * This function retrieves the constraints for a given column.
  221. */
  222. private function getColumnConstraintSQL($table, $column)
  223. {
  224. return "SELECT SysObjects.[Name]
  225. FROM SysObjects INNER JOIN (SELECT [Name],[ID] FROM SysObjects WHERE XType = 'U') AS Tab
  226. ON Tab.[ID] = Sysobjects.[Parent_Obj]
  227. INNER JOIN sys.default_constraints DefCons ON DefCons.[object_id] = Sysobjects.[ID]
  228. INNER JOIN SysColumns Col ON Col.[ColID] = DefCons.[parent_column_id] AND Col.[ID] = Tab.[ID]
  229. WHERE Col.[Name] = " . $this->_conn->quote($column) ." AND Tab.[Name] = " . $this->_conn->quote($table) . "
  230. ORDER BY Col.[Name]";
  231. }
  232. }