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.
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>.
20 namespace Doctrine\DBAL\Schema;
22 use Doctrine\DBAL\Events;
23 use Doctrine\DBAL\Event\SchemaIndexDefinitionEventArgs;
24 use Doctrine\DBAL\Driver\SQLSrv\SQLSrvException;
27 * SQL Server Schema Manager
29 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
30 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
31 * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
32 * @author Juozas Kaziukenas <juozas@juokaz.com>
35 class SQLServerSchemaManager extends AbstractSchemaManager
40 protected function _getPortableTableColumnDefinition($tableColumn)
42 $dbType = strtolower($tableColumn['TYPE_NAME']);
44 $autoincrement = false;
45 if (stripos($dbType, 'identity')) {
46 $dbType = trim(str_ireplace('identity', '', $dbType));
47 $autoincrement = true;
51 $unsigned = $fixed = null;
53 if (!isset($tableColumn['name'])) {
54 $tableColumn['name'] = '';
57 $default = $tableColumn['COLUMN_DEF'];
59 while ($default != ($default2 = preg_replace("/^\((.*)\)$/", '$1', $default))) {
60 $default = trim($default2, "'");
63 $length = (int) $tableColumn['LENGTH'];
65 $type = $this->_platform->getDoctrineTypeMapping($dbType);
68 if ($tableColumn['LENGTH'] == '1') {
70 if (preg_match('/^(is|has)/', $tableColumn['name'])) {
71 $type = array_reverse($type);
84 // Unicode data requires 2 bytes per character
85 $length = $length / 2;
90 'length' => ($length == 0 || !in_array($type, array('text', 'string'))) ? null : $length,
91 'unsigned' => (bool) $unsigned,
92 'fixed' => (bool) $fixed,
93 'default' => $default !== 'NULL' ? $default : null,
94 'notnull' => (bool) ($tableColumn['IS_NULLABLE'] != 'YES'),
95 'scale' => $tableColumn['SCALE'],
96 'precision' => $tableColumn['PRECISION'],
97 'autoincrement' => $autoincrement,
100 return new Column($tableColumn['COLUMN_NAME'], \Doctrine\DBAL\Types\Type::getType($type), $options);
106 protected function _getPortableTableIndexesList($tableIndexRows, $tableName=null)
108 // TODO: Remove code duplication with AbstractSchemaManager;
110 foreach ($tableIndexRows as $tableIndex) {
111 $indexName = $keyName = $tableIndex['index_name'];
112 if (strpos($tableIndex['index_description'], 'primary key') !== false) {
113 $keyName = 'primary';
115 $keyName = strtolower($keyName);
118 if (strpos($tableIndex['index_description'], 'clustered') !== false) {
119 $flags[] = 'clustered';
120 } else if (strpos($tableIndex['index_description'], 'nonclustered') !== false) {
121 $flags[] = 'nonclustered';
124 $result[$keyName] = array(
125 'name' => $indexName,
126 'columns' => explode(', ', $tableIndex['index_keys']),
127 'unique' => strpos($tableIndex['index_description'], 'unique') !== false,
128 'primary' => strpos($tableIndex['index_description'], 'primary key') !== false,
133 $eventManager = $this->_platform->getEventManager();
136 foreach ($result as $indexKey => $data) {
138 $defaultPrevented = false;
140 if (null !== $eventManager && $eventManager->hasListeners(Events::onSchemaIndexDefinition)) {
141 $eventArgs = new SchemaIndexDefinitionEventArgs($data, $tableName, $this->_conn);
142 $eventManager->dispatchEvent(Events::onSchemaIndexDefinition, $eventArgs);
144 $defaultPrevented = $eventArgs->isDefaultPrevented();
145 $index = $eventArgs->getIndex();
148 if ( ! $defaultPrevented) {
149 $index = new Index($data['name'], $data['columns'], $data['unique'], $data['primary']);
153 $indexes[$indexKey] = $index;
163 public function _getPortableTableForeignKeyDefinition($tableForeignKey)
165 return new ForeignKeyConstraint(
166 (array) $tableForeignKey['ColumnName'],
167 $tableForeignKey['ReferenceTableName'],
168 (array) $tableForeignKey['ReferenceColumnName'],
169 $tableForeignKey['ForeignKey'],
171 'onUpdate' => str_replace('_', ' ', $tableForeignKey['update_referential_action_desc']),
172 'onDelete' => str_replace('_', ' ', $tableForeignKey['delete_referential_action_desc']),
180 protected function _getPortableTableDefinition($table)
182 return $table['name'];
188 protected function _getPortableDatabaseDefinition($database)
190 return $database['name'];
196 protected function _getPortableViewDefinition($view)
199 return new View($view['name'], null);
203 * List the indexes for a given table returning an array of Index instances.
205 * Keys of the portable indexes list are all lower-cased.
207 * @param string $table The name of the table
208 * @return Index[] $tableIndexes
210 public function listTableIndexes($table)
212 $sql = $this->_platform->getListTableIndexesSQL($table, $this->_conn->getDatabase());
215 $tableIndexes = $this->_conn->fetchAll($sql);
216 } catch(\PDOException $e) {
217 if ($e->getCode() == "IMSSP") {
222 } catch(SQLSrvException $e) {
223 if (strpos($e->getMessage(), 'SQLSTATE [01000, 15472]') === 0) {
230 return $this->_getPortableTableIndexesList($tableIndexes, $table);
236 public function alterTable(TableDiff $tableDiff)
238 if(count($tableDiff->removedColumns) > 0) {
239 foreach($tableDiff->removedColumns as $col){
240 $columnConstraintSql = $this->getColumnConstraintSQL($tableDiff->name, $col->getName());
241 foreach ($this->_conn->fetchAll($columnConstraintSql) as $constraint) {
242 $this->_conn->exec("ALTER TABLE $tableDiff->name DROP CONSTRAINT " . $constraint['Name']);
247 return parent::alterTable($tableDiff);
251 * This function retrieves the constraints for a given column.
253 private function getColumnConstraintSQL($table, $column)
255 return "SELECT SysObjects.[Name]
256 FROM SysObjects INNER JOIN (SELECT [Name],[ID] FROM SysObjects WHERE XType = 'U') AS Tab
257 ON Tab.[ID] = Sysobjects.[Parent_Obj]
258 INNER JOIN sys.default_constraints DefCons ON DefCons.[object_id] = Sysobjects.[ID]
259 INNER JOIN SysColumns Col ON Col.[ColID] = DefCons.[parent_column_id] AND Col.[ID] = Tab.[ID]
260 WHERE Col.[Name] = " . $this->_conn->quote($column) ." AND Tab.[Name] = " . $this->_conn->quote($table) . "
261 ORDER BY Col.[Name]";