SQLServerSchemaManager.php 11 KB

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