Skip to content
This repository has been archived by the owner on Nov 11, 2020. It is now read-only.

Commit

Permalink
Merge pull request #324 from alcaeus/use-primary-readpreference-gridfs
Browse files Browse the repository at this point in the history
Use primary read preference when reading newly peristed GridFS files
  • Loading branch information
alcaeus authored Apr 30, 2018
2 parents 684f2d3 + 859565b commit a26a823
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 14 deletions.
31 changes: 28 additions & 3 deletions lib/Doctrine/MongoDB/GridFS.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,15 @@ public function storeFile($file, array &$document, array $options = [])
}

$document = array_merge(['_id' => $id], $document);
$gridFsFile = $this->mongoCollection->get($id);
$gridFsFile = $this->withPrimaryReadPreference(function () use ($id) {
return $this->mongoCollection->get($id);
});

if ( ! $gridFsFile instanceof \MongoGridFSFile) {
throw new \LogicException('Could not find newly persisted GridFS file');
}

// TODO: Consider throwing exception if file cannot be fetched
$file->setMongoGridFSFile($this->mongoCollection->get($id));
$file->setMongoGridFSFile($gridFsFile);

return $file;
}
Expand Down Expand Up @@ -288,4 +293,24 @@ protected function doUpdate(array $query, array $newObj, array $options = [])
$options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
return $this->mongoCollection->update($query, $newObj, $options);
}

/**
* Executes a closure with a temporary primary read preference.
*
* @param \Closure $closure
*
* @return mixed
*/
private function withPrimaryReadPreference(\Closure $closure)
{
$prevReadPref = $this->mongoCollection->getReadPreference();
$this->mongoCollection->setReadPreference(\MongoClient::RP_PRIMARY);

try {
return $closure();
} finally {
$prevTags = ! empty($prevReadPref['tagsets']) ? $prevReadPref['tagsets'] : [];
$this->mongoCollection->setReadPreference($prevReadPref['type'], $prevTags);
}
}
}
15 changes: 4 additions & 11 deletions lib/Doctrine/MongoDB/Query/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -481,17 +481,10 @@ private function withReadPreference($object, \Closure $closure)
$object->setReadPreference($this->query['readPreference'], $this->query['readPreferenceTags']);

try {
$result = $closure();
} catch (\Exception $e) {
}

$prevTags = ! empty($prevReadPref['tagsets']) ? $prevReadPref['tagsets'] : null;
$object->setReadPreference($prevReadPref['type'], $prevTags);

if (isset($e)) {
throw $e;
return $closure();
} finally {
$prevTags = ! empty($prevReadPref['tagsets']) ? $prevReadPref['tagsets'] : [];
$object->setReadPreference($prevReadPref['type'], $prevTags);
}

return $result;
}
}

0 comments on commit a26a823

Please sign in to comment.