SQLServerSchemaManager.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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\Driver\SQLSrv\SQLSrvException;
  21. use Doctrine\DBAL\Types\Type;
  22. /**
  23. * SQL Server Schema Manager.
  24. *
  25. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  26. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  27. * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
  28. * @author Juozas Kaziukenas <juozas@juokaz.com>
  29. * @author Steve Müller <st.mueller@dzh-online.de>
  30. * @since 2.0
  31. */
  32. class SQLServerSchemaManager extends AbstractSchemaManager
  33. {
  34. /**
  35. * {@inheritdoc}
  36. */
  37. protected function _getPortableSequenceDefinition($sequence)
  38. {
  39. return new Sequence($sequence['name'], $sequence['increment'], $sequence['start_value']);
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. protected function _getPortableTableColumnDefinition($tableColumn)
  45. {
  46. $dbType = strtok($tableColumn['type'], '(), ');
  47. $fixed = null;
  48. $length = (int) $tableColumn['length'];
  49. $default = $tableColumn['default'];
  50. if (!isset($tableColumn['name'])) {
  51. $tableColumn['name'] = '';
  52. }
  53. while ($default != ($default2 = preg_replace("/^\((.*)\)$/", '$1', $default))) {
  54. $default = trim($default2, "'");
  55. if ($default == 'getdate()') {
  56. $default = $this->_platform->getCurrentTimestampSQL();
  57. }
  58. }
  59. switch ($dbType) {
  60. case 'nchar':
  61. case 'nvarchar':
  62. case 'ntext':
  63. // Unicode data requires 2 bytes per character
  64. $length = $length / 2;
  65. break;
  66. case 'varchar':
  67. // TEXT type is returned as VARCHAR(MAX) with a length of -1
  68. if ($length == -1) {
  69. $dbType = 'text';
  70. }
  71. break;
  72. }
  73. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  74. switch ($type) {
  75. case 'char':
  76. $fixed = true;
  77. break;
  78. case 'text':
  79. $fixed = false;
  80. break;
  81. }
  82. $options = array(
  83. 'length' => ($length == 0 || !in_array($type, array('text', 'string'))) ? null : $length,
  84. 'unsigned' => false,
  85. 'fixed' => (bool) $fixed,
  86. 'default' => $default !== 'NULL' ? $default : null,
  87. 'notnull' => (bool) $tableColumn['notnull'],
  88. 'scale' => $tableColumn['scale'],
  89. 'precision' => $tableColumn['precision'],
  90. 'autoincrement' => (bool) $tableColumn['autoincrement'],
  91. );
  92. $platformOptions = array(
  93. 'collate' => $tableColumn['collation'] == 'NULL' ? null : $tableColumn['collation']
  94. );
  95. $column = new Column($tableColumn['name'], Type::getType($type), $options);
  96. $column->setPlatformOptions($platformOptions);
  97. return $column;
  98. }
  99. /**
  100. * {@inheritdoc}
  101. */
  102. protected function _getPortableTableForeignKeysList($tableForeignKeys)
  103. {
  104. $foreignKeys = array();
  105. foreach ($tableForeignKeys as $tableForeignKey) {
  106. if ( ! isset($foreignKeys[$tableForeignKey['ForeignKey']])) {
  107. $foreignKeys[$tableForeignKey['ForeignKey']] = array(
  108. 'local_columns' => array($tableForeignKey['ColumnName']),
  109. 'foreign_table' => $tableForeignKey['ReferenceTableName'],
  110. 'foreign_columns' => array($tableForeignKey['ReferenceColumnName']),
  111. 'name' => $tableForeignKey['ForeignKey'],
  112. 'options' => array(
  113. 'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
  114. 'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc'])
  115. )
  116. );
  117. } else {
  118. $foreignKeys[$tableForeignKey['ForeignKey']]['local_columns'][] = $tableForeignKey['ColumnName'];
  119. $foreignKeys[$tableForeignKey['ForeignKey']]['foreign_columns'][] = $tableForeignKey['ReferenceColumnName'];
  120. }
  121. }
  122. return parent::_getPortableTableForeignKeysList($foreignKeys);
  123. }
  124. /**
  125. * {@inheritdoc}
  126. */
  127. protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
  128. {
  129. foreach ($tableIndexRows as &$tableIndex) {
  130. $tableIndex['non_unique'] = (boolean) $tableIndex['non_unique'];
  131. $tableIndex['primary'] = (boolean) $tableIndex['primary'];
  132. $tableIndex['flags'] = $tableIndex['flags'] ? array($tableIndex['flags']) : null;
  133. }
  134. return parent::_getPortableTableIndexesList($tableIndexRows, $tableName);
  135. }
  136. /**
  137. * {@inheritdoc}
  138. */
  139. protected function _getPortableTableForeignKeyDefinition($tableForeignKey)
  140. {
  141. return new ForeignKeyConstraint(
  142. $tableForeignKey['local_columns'],
  143. $tableForeignKey['foreign_table'],
  144. $tableForeignKey['foreign_columns'],
  145. $tableForeignKey['name'],
  146. $tableForeignKey['options']
  147. );
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. protected function _getPortableTableDefinition($table)
  153. {
  154. return $table['name'];
  155. }
  156. /**
  157. * {@inheritdoc}
  158. */
  159. protected function _getPortableDatabaseDefinition($database)
  160. {
  161. return $database['name'];
  162. }
  163. /**
  164. * {@inheritdoc}
  165. */
  166. protected function _getPortableViewDefinition($view)
  167. {
  168. // @todo
  169. return new View($view['name'], null);
  170. }
  171. /**
  172. * {@inheritdoc}
  173. */
  174. public function listTableIndexes($table)
  175. {
  176. $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
  177. try {
  178. $tableIndexes = $this->_conn->fetchAll($sql);
  179. } catch(\PDOException $e) {
  180. if ($e->getCode() == "IMSSP") {
  181. return array();
  182. } else {
  183. throw $e;
  184. }
  185. } catch(SQLSrvException $e) {
  186. if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) {
  187. return array();
  188. } else {
  189. throw $e;
  190. }
  191. }
  192. return $this->_getPortableTableIndexesList($tableIndexes, $table);
  193. }
  194. /**
  195. * {@inheritdoc}
  196. */
  197. public function alterTable(TableDiff $tableDiff)
  198. {
  199. if(count($tableDiff->removedColumns) > 0) {
  200. foreach($tableDiff->removedColumns as $col){
  201. $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
  202. foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) {
  203. $this->_conn->exec("ALTER TABLE $tableDiff->name DROP CONSTRAINT " . $constraint['Name']);
  204. }
  205. }
  206. }
  207. parent::alterTable($tableDiff);
  208. }
  209. /**
  210. * Returns the SQL to retrieve the constraints for a given column.
  211. *
  212. * @param string $table
  213. * @param string $column
  214. *
  215. * @return string
  216. */
  217. private function getColumnConstraintSQL($table, $column)
  218. {
  219. return "SELECT SysObjects.[Name]
  220. FROM SysObjects INNER JOIN (SELECT [Name],[ID] FROM SysObjects WHERE XType = 'U') AS Tab
  221. ON Tab.[ID] = Sysobjects.[Parent_Obj]
  222. INNER JOIN sys.default_constraints DefCons ON DefCons.[object_id] = Sysobjects.[ID]
  223. INNER JOIN SysColumns Col ON Col.[ColID] = DefCons.[parent_column_id] AND Col.[ID] = Tab.[ID]
  224. WHERE Col.[Name] = " . $this->_conn->quote($column) ." AND Tab.[Name] = " . $this->_conn->quote($table) . "
  225. ORDER BY Col.[Name]";
  226. }
  227. }