Skip to content

Commit 37e35a3

Browse files
committed
fix(indexes): report unique violations from index creation as Unique
Postgres, MariaDB/MySQL and Mongo now map a unique violation raised by createIndex() to UniqueException directly instead of relying on processException() to parse the violated key. On Postgres a nested object path key is an expression, and on MariaDB/MySQL a localized message names no key, so both came back as a plain DuplicateException that Database::createIndex() tolerated as an existing index, keeping metadata for an index that was never built. "Index already exists" and document-level duplicates are unchanged.
1 parent 2132831 commit 37e35a3

3 files changed

Lines changed: 17 additions & 0 deletions

File tree

‎src/Database/Adapter/MariaDB.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -779,6 +779,12 @@ public function createIndex(string $collection, string $id, string $type, array
779779
->prepare($sql)
780780
->execute();
781781
} catch (PDOException $e) {
782+
// Existing rows violate the new unique index. Classified here because
783+
// processException() can't parse the key from a localized message.
784+
if ($e->getCode() === '23000' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 1062) {
785+
throw new UniqueException('Unique index violation', $e->getCode(), $e);
786+
}
787+
782788
throw $this->processException($e);
783789
}
784790
}

‎src/Database/Adapter/Mongo.php‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1146,6 +1146,11 @@ public function createIndex(string $collection, string $id, string $type, array
11461146

11471147
return $result;
11481148
} catch (\Exception $e) {
1149+
// Existing documents violate the new unique index, whatever index the message names
1150+
if ($e->getCode() === 11000 || $e->getCode() === 11001) {
1151+
throw new UniqueException('Unique index violation', $e->getCode(), $e);
1152+
}
1153+
11491154
throw $this->processException($e);
11501155
}
11511156
}

‎src/Database/Adapter/Postgres.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,12 @@ public function createIndex(string $collection, string $id, string $type, array
925925
try {
926926
return $this->getPDO()->prepare($sql)->execute();
927927
} catch (PDOException $e) {
928+
// Existing rows violate the new unique index. Classified here because an
929+
// expression key (nested object path) has no columns for processException() to parse.
930+
if ($e->getCode() === '23505' && isset($e->errorInfo[1]) && $e->errorInfo[1] === 7) {
931+
throw new UniqueException('Unique index violation', $e->getCode(), $e);
932+
}
933+
928934
throw $this->processException($e);
929935
}
930936
}

0 commit comments

Comments
 (0)