SQLServerSchemaManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Schema;
  20. use Doctrine\DBAL\DBALException;
  21. use Doctrine\DBAL\Driver\DriverException;
  22. use Doctrine\DBAL\Types\Type;
  23. /**
  24. * SQL Server Schema Manager.
  25. *
  26. * @license http://www.opensource.org/licenses/mit-license.php MIT
  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. * @author Steve Müller <st.mueller@dzh-online.de>
  31. * @since 2.0
  32. */
  33. class SQLServerSchemaManager extends AbstractSchemaManager
  34. {
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function dropDatabase($database)
  39. {
  40. try {
  41. parent::dropDatabase($database);
  42. } catch (DBALException $exception) {
  43. $exception = $exception->getPrevious();
  44. if (! $exception instanceof DriverException) {
  45. throw $exception;
  46. }
  47. // If we have a error code 3702, the drop database operation failed
  48. // because of active connections on the database.
  49. // To force dropping the database, we first have to close all active connections
  50. // on that database and issue the drop database operation again.
  51. if ($exception->getErrorCode() !== 3702) {
  52. throw $exception;
  53. }
  54. $this->closeActiveDatabaseConnections($database);
  55. parent::dropDatabase($database);
  56. }
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. protected function _getPortableSequenceDefinition($sequence)
  62. {
  63. return new Sequence($sequence['name'], $sequence['increment'], $sequence['start_value']);
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. protected function _getPortableTableColumnDefinition($tableColumn)
  69. {
  70. $dbType = strtok($tableColumn['type'], '(), ');
  71. $fixed = null;
  72. $length = (int) $tableColumn['length'];
  73. $default = $tableColumn['default'];
  74. if (!isset($tableColumn['name'])) {
  75. $tableColumn['name'] = '';
  76. }
  77. while ($default != ($default2 = preg_replace("/^\((.*)\)$/", '$1', $default))) {
  78. $default = trim($default2, "'");
  79. if ($default == 'getdate()') {
  80. $default = $this->_platform->getCurrentTimestampSQL();
  81. }
  82. }
  83. switch ($dbType) {
  84. case 'nchar':
  85. case 'nvarchar':
  86. case 'ntext':
  87. // Unicode data requires 2 bytes per character
  88. $length = $length / 2;
  89. break;
  90. case 'varchar':
  91. // TEXT type is returned as VARCHAR(MAX) with a length of -1
  92. if ($length == -1) {
  93. $dbType = 'text';
  94. }
  95. break;
  96. }
  97. if ('char' === $dbType || 'nchar' === $dbType || 'binary' === $dbType) {
  98. $fixed = true;
  99. }
  100. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  101. $type = $this->extractDoctrineTypeFromComment($tableColumn['comment'], $type);
  102. $tableColumn['comment'] = $this->removeDoctrineTypeFromComment($tableColumn['comment'], $type);
  103. $options = array(
  104. 'length' => ($length == 0 || !in_array($type, array('text', 'string'))) ? null : $length,
  105. 'unsigned' => false,
  106. 'fixed' => (bool) $fixed,
  107. 'default' => $default !== 'NULL' ? $default : null,
  108. 'notnull' => (bool) $tableColumn['notnull'],
  109. 'scale' => $tableColumn['scale'],
  110. 'precision' => $tableColumn['precision'],
  111. 'autoincrement' => (bool) $tableColumn['autoincrement'],
  112. 'comment' => $tableColumn['comment'] !== '' ? $tableColumn['comment'] : null,
  113. );
  114. $column = new Column($tableColumn['name'], Type::getType($type), $options);
  115. if (isset($tableColumn['collation']) && $tableColumn['collation'] !== 'NULL') {
  116. $column->setPlatformOption('collation', $tableColumn['collation']);
  117. }
  118. return $column;
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. protected function _getPortableTableForeignKeysList($tableForeignKeys)
  124. {
  125. $foreignKeys = array();
  126. foreach ($tableForeignKeys as $tableForeignKey) {
  127. if ( ! isset($foreignKeys[$tableForeignKey['ForeignKey']])) {
  128. $foreignKeys[$tableForeignKey['ForeignKey']] = array(
  129. 'local_columns' => array($tableForeignKey['ColumnName']),
  130. 'foreign_table' => $tableForeignKey['ReferenceTableName'],
  131. 'foreign_columns' => array($tableForeignKey['ReferenceColumnName']),
  132. 'name' => $tableForeignKey['ForeignKey'],
  133. 'options' => array(
  134. 'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
  135. 'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc'])
  136. )
  137. );
  138. } else {
  139. $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][] = $tableForeignKey['ColumnName'];
  140. $foreignKeys[$tableForeignKey['ForeignKey']]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName'];
  141. }
  142. }
  143. return parent::_getPortableTableForeignKeysList($foreignKeys);
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
  149. {
  150. foreach ($tableIndexRows as &$tableIndex) {
  151. $tableIndex['non_unique'] = (boolean) $tableIndex['non_unique'];
  152. $tableIndex['primary'] = (boolean) $tableIndex['primary'];
  153. $tableIndex['flags'] = $tableIndex['flags'] ? array($tableIndex['flags']) : null;
  154. }
  155. return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
  156. }
  157. /**
  158. * {@inheritdoc}
  159. */
  160. protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
  161. {
  162. return new ForeignKeyConstraint(
  163. $tableForeignKey['local_columns'],
  164. $tableForeignKey['foreign_table'],
  165. $tableForeignKey['foreign_columns'],
  166. $tableForeignKey['name'],
  167. $tableForeignKey['options']
  168. );
  169. }
  170. /**
  171. * {@inheritdoc}
  172. */
  173. protected function _getPortableTableDefinition($table)
  174. {
  175. return $table['name'];
  176. }
  177. /**
  178. * {@inheritdoc}
  179. */
  180. protected function _getPortableDatabaseDefinition($database)
  181. {
  182. return $database['name'];
  183. }
  184. /**
  185. * {@inheritdoc}
  186. */
  187. protected function getPortableNamespaceDefinition(array $namespace)
  188. {
  189. return $namespace['name'];
  190. }
  191. /**
  192. * {@inheritdoc}
  193. */
  194. protected function _getPortableViewDefinition($view)
  195. {
  196. // @todo
  197. return new View($view['name'], null);
  198. }
  199. /**
  200. * {@inheritdoc}
  201. */
  202. public function listTableIndexes($table)
  203. {
  204. $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
  205. try {
  206. $tableIndexes = $this->_conn->fetchAll($sql);
  207. } catch (\PDOException $e) {
  208. if ($e->getCode() == "IMSSP") {
  209. return array();
  210. } else {
  211. throw $e;
  212. }
  213. } catch (DBALException $e) {
  214. if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) {
  215. return array();
  216. } else {
  217. throw $e;
  218. }
  219. }
  220. return $this->_getPortableTableIndexesList($tableIndexes, $table);
  221. }
  222. /**
  223. * {@inheritdoc}
  224. */
  225. public function alterTable(TableDiff $tableDiff)
  226. {
  227. if (count($tableDiff->removedColumns) > 0) {
  228. foreach ($tableDiff->removedColumns as $col) {
  229. $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
  230. foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) {
  231. $this->_conn->exec("ALTER TABLE $tableDiff->name DROP CONSTRAINT " . $constraint['Name']);
  232. }
  233. }
  234. }
  235. parent::alterTable($tableDiff);
  236. }
  237. /**
  238. * Returns the SQL to retrieve the constraints for a given column.
  239. *
  240. * @param string $table
  241. * @param string $column
  242. *
  243. * @return string
  244. */
  245. private function getColumnConstraintSQL($table, $column)
  246. {
  247. return "SELECT SysObjects.[Name]
  248. FROM SysObjects INNER JOIN (SELECT [Name],[ID] FROM SysObjects WHERE XType = 'U') AS Tab
  249. ON Tab.[ID] = Sysobjects.[Parent_Obj]
  250. INNER JOIN sys.default_constraints DefCons ON DefCons.[object_id] = Sysobjects.[ID]
  251. INNER JOIN SysColumns Col ON Col.[ColID] = DefCons.[parent_column_id] AND Col.[ID] = Tab.[ID]
  252. WHERE Col.[Name] = " . $this->_conn->quote($column) ." AND Tab.[Name] = " . $this->_conn->quote($table) . "
  253. ORDER BY Col.[Name]";
  254. }
  255. /**
  256. * Closes currently active connections on the given database.
  257. *
  258. * This is useful to force DROP DATABASE operations which could fail because of active connections.
  259. *
  260. * @param string $database The name of the database to close currently active connections for.
  261. *
  262. * @return void
  263. */
  264. private function closeActiveDatabaseConnections($database)
  265. {
  266. $database = new Identifier($database);
  267. $this->_execSql(
  268. sprintf(
  269. 'ALTER DATABASE %s SET SINGLE_USER WITH ROLLBACK IMMEDIATE',
  270. $database->getQuotedName($this->_platform)
  271. )
  272. );
  273. }
  274. }