Browse Source

Restart identity columns in SQLServer if they exist.

Since SQLServer won't let us truncate tables with foreign keys we can
use delete from and restart the identity sequences.
mark_story 11 years ago
parent
commit
e3fcc629f2

+ 14 - 2
src/Database/Schema/SqlserverSchema.php

@@ -429,9 +429,21 @@ class SqlserverSchema extends BaseSchema {
  */
 	public function truncateTableSql(Table $table) {
 		$name = $this->_driver->quoteIdentifier($table->name());
-		return [
-			sprintf('TRUNCATE TABLE %s', $name)
+		$queries = [
+			sprintf('DELETE FROM TABLE %s', $name)
 		];
+		$pk = $table->primaryKey();
+		foreach ($pk as $column) {
+			$column = $table->column($column);
+			if (!empty($column['autoIncrement'])) {
+				$queries[] = sprintf(
+					'DBCC CHECKIDENT(%s, RESEED, 0)',
+					$this->_driver->quoteIdentifier($column)
+				);
+				break;
+			}
+		}
+		return $queries;
 	}
 
 }

+ 2 - 1
tests/TestCase/Database/Schema/SqlserverSchemaTest.php

@@ -710,8 +710,9 @@ SQL;
 				'columns' => ['id']
 			]);
 		$result = $table->truncateSql($connection);
-		$this->assertCount(1, $result);
+		$this->assertCount(2, $result);
 		$this->assertEquals('TRUNCATE TABLE [schema_articles]', $result[0]);
+		$this->assertEquals('DBCC CHECKIDENT([schema_articles], RESEED, 0)', $result[1]);
 	}
 
 /**