Skip to content

Commit

Permalink
Put Mimeloader insertion and read in the same transaction
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Citharel <tcit@tcit.fr>
  • Loading branch information
tcitworld committed Jan 20, 2023
1 parent 473c546 commit 63088ce
Showing 1 changed file with 28 additions and 18 deletions.
46 changes: 28 additions & 18 deletions lib/private/Files/Type/Loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
*/
namespace OC\Files\Type;

use OC\DB\Exceptions\DbalException;
use OCP\AppFramework\Db\TTransactional;
use OCP\DB\Exception as DBException;
use OCP\Files\IMimeTypeLoader;
use OCP\IDBConnection;

Expand All @@ -33,6 +36,7 @@
* @package OC\Files\Type
*/
class Loader implements IMimeTypeLoader {
use TTransactional;

/** @var IDBConnection */
private $dbConnection;
Expand Down Expand Up @@ -109,31 +113,37 @@ public function reset() {
* Store a mimetype in the DB
*
* @param string $mimetype
* @param int inserted ID
* @return int inserted ID
*/
protected function store($mimetype) {
$this->dbConnection->insertIfNotExist('*PREFIX*mimetypes', [
'mimetype' => $mimetype
]);

$fetch = $this->dbConnection->getQueryBuilder();
$fetch->select('id')
->from('mimetypes')
->where(
$fetch->expr()->eq('mimetype', $fetch->createNamedParameter($mimetype)
));

$result = $fetch->execute();
$row = $result->fetch();
$result->closeCursor();
$row = $this->atomic(function () use ($mimetype) {
try {
$insert = $this->dbConnection->getQueryBuilder();
$insert->insert('mimetypes')
->values([
'mimetype' => $insert->createNamedParameter($mimetype)
])
->executeStatement();
return [
'mimetype' => $mimetype,
'id' => $insert->getLastInsertId(),
];
} catch (DbalException $e) {
if ($e->getReason() !== DBException::REASON_UNIQUE_CONSTRAINT_VIOLATION) {
throw $e;
}
return null;
}
}, $this->dbConnection);

if (!$row) {
throw new \Exception("Failed to get mimetype id for $mimetype after trying to store it");
}
$mimetypeId = (int) $row['id'];

$this->mimetypes[$row['id']] = $mimetype;
$this->mimetypeIds[$mimetype] = $row['id'];
return $row['id'];
$this->mimetypes[$mimetypeId] = $mimetype;
$this->mimetypeIds[$mimetype] = $mimetypeId;
return $mimetypeId;
}

/**
Expand Down

0 comments on commit 63088ce

Please sign in to comment.