diff --git a/lib/private/db/migrator.php b/lib/private/db/migrator.php
index 517be8399e86a1c4d832c5f25c45bb01f5328100..8dbfabe443ca1dcbc7e7d90c55011f7ae13b33bd 100644
--- a/lib/private/db/migrator.php
+++ b/lib/private/db/migrator.php
@@ -128,7 +128,13 @@ class Migrator {
 		$indexes = $table->getIndexes();
 		$newIndexes = array();
 		foreach ($indexes as $index) {
-			$indexName = 'oc_' . uniqid(); // avoid conflicts in index names
+			if ($index->isPrimary()) {
+				// do not rename primary key
+				$indexName = $index->getName();
+			} else {
+				// avoid conflicts in index names
+				$indexName = 'oc_' . uniqid();
+			}
 			$newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
 		}
 
diff --git a/tests/lib/db/migrator.php b/tests/lib/db/migrator.php
index e9b986236b8970901b924aa994a579be8de23911..e94d550f836ffee5a7cbb7368b49100e211568cd 100644
--- a/tests/lib/db/migrator.php
+++ b/tests/lib/db/migrator.php
@@ -119,4 +119,25 @@ class Migrator extends \PHPUnit_Framework_TestCase {
 			$this->assertTrue(true);
 		}
 	}
+
+	public function testAddingPrimaryKeyWithAutoIncrement() {
+		$startSchema = new Schema(array(), array(), $this->getSchemaConfig());
+		$table = $startSchema->createTable($this->tableName);
+		$table->addColumn('id', 'integer');
+		$table->addColumn('name', 'string');
+
+		$endSchema = new Schema(array(), array(), $this->getSchemaConfig());
+		$table = $endSchema->createTable($this->tableName);
+		$table->addColumn('id', 'integer', array('autoincrement' => true));
+		$table->addColumn('name', 'string');
+		$table->setPrimaryKey(array('id'));
+
+		$migrator = $this->getMigrator();
+		$migrator->migrate($startSchema);
+
+		$migrator->checkMigrate($endSchema);
+		$migrator->migrate($endSchema);
+
+		$this->assertTrue(true);
+	}
 }