MongoWriteBatch.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. */
  15. if (class_exists('MongoWriteBatch', false)) {
  16. return;
  17. }
  18. use Alcaeus\MongoDbAdapter\TypeConverter;
  19. use Alcaeus\MongoDbAdapter\Helper\WriteConcernConverter;
  20. use MongoDB\Driver\Exception\BulkWriteException;
  21. use MongoDB\Driver\WriteError;
  22. use MongoDB\Driver\WriteResult;
  23. /**
  24. * MongoWriteBatch allows you to "batch up" multiple operations (of same type)
  25. * and shipping them all to MongoDB at the same time. This can be especially
  26. * useful when operating on many documents at the same time to reduce roundtrips.
  27. *
  28. * @see http://php.net/manual/en/class.mongowritebatch.php
  29. */
  30. class MongoWriteBatch
  31. {
  32. use WriteConcernConverter;
  33. const COMMAND_INSERT = 1;
  34. const COMMAND_UPDATE = 2;
  35. const COMMAND_DELETE = 3;
  36. /**
  37. * @var MongoCollection
  38. */
  39. private $collection;
  40. /**
  41. * @var int
  42. */
  43. private $batchType;
  44. /**
  45. * @var array
  46. */
  47. private $writeOptions;
  48. /**
  49. * @var array
  50. */
  51. private $items = [];
  52. /**
  53. * Creates a new batch of write operations
  54. *
  55. * @see http://php.net/manual/en/mongowritebatch.construct.php
  56. * @param MongoCollection $collection
  57. * @param int $batchType
  58. * @param array $writeOptions
  59. */
  60. protected function __construct(MongoCollection $collection, $batchType, $writeOptions)
  61. {
  62. $this->collection = $collection;
  63. $this->batchType = $batchType;
  64. $this->writeOptions = $writeOptions;
  65. }
  66. /**
  67. * Adds a write operation to a batch
  68. *
  69. * @see http://php.net/manual/en/mongowritebatch.add.php
  70. * @param array|object $item
  71. * @return boolean
  72. */
  73. public function add($item)
  74. {
  75. if (is_object($item)) {
  76. $item = (array)$item;
  77. }
  78. $this->validate($item);
  79. $this->addItem($item);
  80. return true;
  81. }
  82. /**
  83. * Executes a batch of write operations
  84. *
  85. * @see http://php.net/manual/en/mongowritebatch.execute.php
  86. * @param array $writeOptions
  87. * @return array
  88. */
  89. final public function execute(array $writeOptions = [])
  90. {
  91. $writeOptions += $this->writeOptions;
  92. if (! count($this->items)) {
  93. return ['ok' => true];
  94. }
  95. if (isset($writeOptions['j'])) {
  96. trigger_error('j parameter is not supported', E_USER_WARNING);
  97. }
  98. if (isset($writeOptions['fsync'])) {
  99. trigger_error('fsync parameter is not supported', E_USER_WARNING);
  100. }
  101. $options['writeConcern'] = $this->createWriteConcernFromArray($writeOptions);
  102. if (isset($writeOptions['ordered'])) {
  103. $options['ordered'] = $writeOptions['ordered'];
  104. }
  105. try {
  106. $writeResult = $this->collection->getCollection()->bulkWrite($this->items, $options);
  107. $resultDocument = [];
  108. $ok = true;
  109. } catch (BulkWriteException $e) {
  110. $writeResult = $e->getWriteResult();
  111. $resultDocument = ['writeErrors' => $this->convertWriteErrors($writeResult)];
  112. $ok = false;
  113. }
  114. $this->items = [];
  115. switch ($this->batchType) {
  116. case self::COMMAND_UPDATE:
  117. $upsertedIds = [];
  118. foreach ($writeResult->getUpsertedIds() as $index => $id) {
  119. $upsertedIds[] = [
  120. 'index' => $index,
  121. '_id' => TypeConverter::toLegacy($id)
  122. ];
  123. }
  124. $resultDocument += [
  125. 'nMatched' => $writeResult->getMatchedCount(),
  126. 'nModified' => $writeResult->getModifiedCount(),
  127. 'nUpserted' => $writeResult->getUpsertedCount(),
  128. 'ok' => true,
  129. ];
  130. if (count($upsertedIds)) {
  131. $resultDocument['upserted'] = $upsertedIds;
  132. }
  133. break;
  134. case self::COMMAND_DELETE:
  135. $resultDocument += [
  136. 'nRemoved' => $writeResult->getDeletedCount(),
  137. 'ok' => true,
  138. ];
  139. break;
  140. case self::COMMAND_INSERT:
  141. $resultDocument += [
  142. 'nInserted' => $writeResult->getInsertedCount(),
  143. 'ok' => true,
  144. ];
  145. break;
  146. }
  147. if (! $ok) {
  148. // Exception code is hardcoded to the value in ext-mongo, see
  149. // https://github.com/mongodb/mongo-php-driver-legacy/blob/ab4bc0d90e93b3f247f6bcb386d0abc8d2fa7d74/batch/write.c#L428
  150. throw new \MongoWriteConcernException('Failed write', 911, null, $resultDocument);
  151. }
  152. return $resultDocument;
  153. }
  154. private function validate(array $item)
  155. {
  156. switch ($this->batchType) {
  157. case self::COMMAND_UPDATE:
  158. if (! isset($item['q'])) {
  159. throw new Exception("Expected \$item to contain 'q' key");
  160. }
  161. if (! isset($item['u'])) {
  162. throw new Exception("Expected \$item to contain 'u' key");
  163. }
  164. break;
  165. case self::COMMAND_DELETE:
  166. if (! isset($item['q'])) {
  167. throw new Exception("Expected \$item to contain 'q' key");
  168. }
  169. if (! isset($item['limit'])) {
  170. throw new Exception("Expected \$item to contain 'limit' key");
  171. }
  172. break;
  173. }
  174. }
  175. private function addItem(array $item)
  176. {
  177. switch ($this->batchType) {
  178. case self::COMMAND_UPDATE:
  179. $method = isset($item['multi']) ? 'updateMany' : 'updateOne';
  180. $options = [];
  181. if (isset($item['upsert']) && $item['upsert']) {
  182. $options['upsert'] = true;
  183. }
  184. $this->items[] = [$method => [TypeConverter::fromLegacy($item['q']), TypeConverter::fromLegacy($item['u']), $options]];
  185. break;
  186. case self::COMMAND_INSERT:
  187. $this->items[] = ['insertOne' => [TypeConverter::fromLegacy($item)]];
  188. break;
  189. case self::COMMAND_DELETE:
  190. $method = $item['limit'] === 0 ? 'deleteMany' : 'deleteOne';
  191. $this->items[] = [$method => [TypeConverter::fromLegacy($item['q'])]];
  192. break;
  193. }
  194. }
  195. /**
  196. * @param WriteResult $result
  197. * @return array
  198. */
  199. private function convertWriteErrors(WriteResult $result)
  200. {
  201. $writeErrors = [];
  202. /** @var WriteError $writeError */
  203. foreach ($result->getWriteErrors() as $writeError) {
  204. $writeErrors[] = [
  205. 'index' => $writeError->getIndex(),
  206. 'code' => $writeError->getCode(),
  207. 'errmsg' => $writeError->getMessage(),
  208. ];
  209. }
  210. return $writeErrors;
  211. }
  212. }