/**
  * {@inheritdoc}
  */
 protected function performRollback($table, array $records)
 {
     $bulk = new BulkWrite();
     foreach ($records as $record) {
         $id = $record['_id'];
         unset($record['_id']);
         $bulk->delete(array('_id' => $id));
     }
     $this->conn->executeBulkWrite($this->getNamespace($table), $bulk);
 }
Example #2
1
 /**
  * Removes documents from collection
  *
  * @param array $query
  *
  * @return Result
  */
 public function remove($query)
 {
     $result = new Result();
     $bulk = new BulkWrite();
     $bulk->delete($query, ['limit' => 0]);
     $dbResult = $this->executeBulkWrite($bulk);
     if ($dbResult->getDeletedCount() === 0) {
         $result->setError(Result::ERROR_CANNOT_DELETE_RECORD, implode('. ', $dbResult->getWriteErrors()));
     }
     return $result;
 }
Example #3
0
 /**
  * Write into database
  *
  * @param $collection
  * @param $command
  * @param $data
  * @return mixed
  */
 public function write($collection, $command, $data)
 {
     // Make sure the database is connected
     $this->_connection or $this->connect();
     // Set the last query
     $this->_last_query = $data;
     // Configurations
     $config = $this->_config;
     // Exec bulk command
     $bulk = new BulkWrite();
     switch ($command) {
         case 'insert':
             $data['_id'] = new \MongoDB\BSON\ObjectID();
             $bulk->insert($data);
             break;
         case 'update':
             $bulk->update($data[0], $data[1], $data[2]);
             break;
         case 'delete':
             $bulk->delete($data[0], $data[1]);
             break;
     }
     try {
         $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
         $response = $this->_connection->executeBulkWrite($config['database'] . '.' . $collection, $bulk, $writeConcern);
     } catch (\MongoDB\Driver\Exception\BulkWriteException $e) {
         //print_r($e);die();
         echo $e->getMessage(), "\n";
         //exit;
     }
     return $response;
 }
Example #4
0
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  * @param Server $server
  * @return DeleteResult
  */
 public function execute(Server $server)
 {
     $bulk = new Bulk();
     $bulk->delete($this->filter, ['limit' => $this->limit]);
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new DeleteResult($writeResult);
 }
 /**
  * Create data fixtures.
  *
  * @param integer $n
  */
 private function createFixtures($n)
 {
     $bulkWrite = new BulkWrite(true);
     for ($i = 1; $i <= $n; $i++) {
         $bulkWrite->insert(['_id' => $i, 'x' => (object) ['foo' => 'bar']]);
     }
     $result = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite);
     $this->assertEquals($n, $result->getInsertedCount());
 }
 /**
  * Create data fixtures.
  *
  * @param integer $n
  */
 private function createFixtures($n)
 {
     $bulkWrite = new BulkWrite(['ordered' => true]);
     for ($i = 1; $i <= $n; $i++) {
         $bulkWrite->insert(['_id' => $i, 'x' => (int) ($i . $i)]);
     }
     $result = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite);
     $this->assertEquals($n, $result->getInsertedCount());
 }
 public function testDrop()
 {
     $bulkWrite = new BulkWrite();
     $bulkWrite->insert(['x' => 1]);
     $writeResult = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite);
     $this->assertEquals(1, $writeResult->getInsertedCount());
     $commandResult = $this->database->drop();
     $this->assertCommandSucceeded($commandResult);
     $this->assertCollectionCount($this->getNamespace(), 0);
 }
Example #8
0
 protected function write(array $record)
 {
     if (isset($this->collection)) {
         $this->collection->insertOne($record['formatted']);
     }
     if (isset($this->manager, $this->namespace)) {
         $bulk = new BulkWrite();
         $bulk->insert($record["formatted"]);
         $this->manager->executeBulkWrite($this->namespace, $bulk);
     }
 }
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  * @param Server $server
  * @return InsertOneResult
  */
 public function execute(Server $server)
 {
     $bulk = new Bulk();
     $insertedId = $bulk->insert($this->document);
     if ($insertedId === null) {
         // TODO: This may be removed if PHPC-382 is implemented
         $insertedId = is_array($this->document) ? $this->document['_id'] : $this->document->_id;
     }
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new InsertOneResult($writeResult, $insertedId);
 }
Example #10
0
 public function update($myNamespace, $data, $id)
 {
     $result = [];
     $collection = $this->getCollection($myNamespace);
     $id = new ObjectID($id);
     unset($data->_id);
     $bulk = new BulkWrite();
     $bulk->update(['_id' => $id], $data);
     $this->manager->executeBulkWrite($myNamespace, $bulk);
     //delete unset value
     //$result = $collection->updateOne(['_id'=>$id],['$set'=>$data]);//keep unset value
     return $result;
 }
Example #11
0
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  * @param Server $server
  * @return InsertOneResult
  */
 public function execute(Server $server)
 {
     $options = [];
     if (isset($this->options['bypassDocumentValidation']) && \MongoDB\server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)) {
         $options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
     }
     $bulk = new Bulk($options);
     $insertedId = $bulk->insert($this->document);
     if ($insertedId === null) {
         $insertedId = \MongoDB\extract_id_from_inserted_document($this->document);
     }
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new InsertOneResult($writeResult, $insertedId);
 }
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  * @param Server $server
  * @return InsertOneResult
  */
 public function execute(Server $server)
 {
     $options = [];
     if (isset($this->options['bypassDocumentValidation']) && \MongoDB\server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)) {
         $options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
     }
     $bulk = new Bulk($options);
     $insertedId = $bulk->insert($this->document);
     if ($insertedId === null) {
         // TODO: This may be removed if PHPC-382 is implemented
         $insertedId = is_array($this->document) ? $this->document['_id'] : $this->document->_id;
     }
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new InsertOneResult($writeResult, $insertedId);
 }
 public function testListDatabases()
 {
     $bulkWrite = new BulkWrite();
     $bulkWrite->insert(['x' => 1]);
     $writeResult = $this->manager->executeBulkWrite($this->getNamespace(), $bulkWrite);
     $this->assertEquals(1, $writeResult->getInsertedCount());
     $databases = $this->client->listDatabases();
     $this->assertInstanceOf('MongoDB\\Model\\DatabaseInfoIterator', $databases);
     foreach ($databases as $database) {
         $this->assertInstanceOf('MongoDB\\Model\\DatabaseInfo', $database);
     }
     $that = $this;
     $this->assertDatabaseExists($this->getDatabaseName(), function (DatabaseInfo $info) use($that) {
         $that->assertFalse($info->isEmpty());
         $that->assertGreaterThan(0, $info->getSizeOnDisk());
     });
 }
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  * @param Server $server
  * @return InsertManyResult
  */
 public function execute(Server $server)
 {
     $bulk = new Bulk(['ordered' => $this->options['ordered']]);
     $insertedIds = [];
     foreach ($this->documents as $i => $document) {
         $insertedId = $bulk->insert($document);
         if ($insertedId !== null) {
             $insertedIds[$i] = $insertedId;
         } else {
             // TODO: This may be removed if PHPC-382 is implemented
             $insertedIds[$i] = is_array($document) ? $document['_id'] : $document->_id;
         }
     }
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new InsertManyResult($writeResult, $insertedIds);
 }
Example #15
0
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  * @param Server $server
  * @return UpdateResult
  */
 public function execute(Server $server)
 {
     $options = array('multi' => $this->options['multi'], 'upsert' => $this->options['upsert']);
     $bulk = new Bulk();
     $bulk->update($this->filter, $this->update, $options);
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new UpdateResult($writeResult);
 }
Example #16
0
 /**
  * 指定字段的值-1
  *
  * @param string $key 操作的key user-id-1
  * @param int $val
  * @param string $field 要改变的字段
  *
  * @return bool
  */
 public function decrement($key, $val = 1, $field = null)
 {
     list($tableName, $condition) = $this->parseKey($key, true);
     if (is_null($field) || empty($tableName) || empty($condition)) {
         $this->bindParams = array();
         return false;
     }
     $val = abs(intval($val));
     $tableName = $this->tablePrefix . $tableName;
     $bulk = new BulkWrite();
     $bulk->update($condition, array('$inc' => array($field => -$val)), array('multi' => true));
     $result = $this->runMongoBulkWrite($tableName, $bulk);
     $GLOBALS['debug'] && $this->debugLogSql('BulkWrite DEC', $this->tablePrefix . $tableName, $condition, array('$inc' => array($field => -$val)));
     return $result->getModifiedCount();
 }
Example #17
0
 /**
  * update data to database
  * @param  array $data  the formatede array for database
  * @return void
  */
 public function update($entity)
 {
     try {
         $data = $entity->toArray();
         $this->updateEmbedded($data, $entity);
         $theId = new MongoId($data['_id']);
         unset($data['_id']);
         $this->callBehavior('beforeUpdate', $data, $entity);
         $bulk = new BulkWrite();
         $bulk->update(['_id' => $theId], $data);
         $this->manager->executeBulkWrite($this->dbName . '.' . $this->collectionName, $bulk);
         $this->callBehavior('afterUpdate', $data, $entity);
     } catch (Exception $e) {
         throw $e;
     }
 }
Example #18
0
 function updateManyDocumentsDemo()
 {
     $bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
     //limit: limit the number of documents matched and updated to the specified value or unlimited when 0
     //You can also use something like ["viking" => "false"] for the first (filter) line
     $bulk->update(["_id" => ['$in' => ["1001", "1002"]]], ['$inc' => ["days.01.views" => 1]], ["limit" => 0, "upsert" => false, "multi" => true]);
     try {
         $result = $this->mongo_manager->executeBulkWrite("db.collection", $bulk, $this->write_concern);
         var_dump($result);
     } catch (MongoDB\Driver\Exception\Exception $e) {
         echo $e->getMessage(), "\n";
     }
 }
Example #19
0
 /**
  * Write a message to the log.
  *
  * @param array $event Event data
  * @return void
  * @throws Exception\RuntimeException
  */
 protected function doWrite(array $event)
 {
     if (null === $this->manager) {
         throw new Exception\RuntimeException('MongoDB\\Driver\\Manager must be defined');
     }
     if (isset($event['timestamp']) && $event['timestamp'] instanceof DateTimeInterface) {
         $millis = (int) floor((double) $event['timestamp']->format('U.u') * 1000);
         $event['timestamp'] = new UTCDateTime($millis);
     }
     $bulkWrite = new BulkWrite();
     $bulkWrite->insert($event);
     $this->manager->executeBulkWrite($this->database, $bulkWrite, $this->writeConcern);
 }
Example #20
0
 public function remove($namespace, $query = [], $options = [])
 {
     $bulk = new BulkWrite();
     $bulk->delete($query, $options);
     $this->result = $this->write($namespace, $bulk);
     return !$this->result->getWriteErrors();
 }
Example #21
0
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  *
  * @param Server $server
  *
  * @return InsertManyResult
  */
 public function execute(Server $server)
 {
     $options = ['ordered' => $this->options['ordered']];
     if (isset($this->options['bypassDocumentValidation']) && Functions::serverSupportsFeature($server, self::$wireVersionForDocumentLevelValidation)) {
         $options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
     }
     $bulk = new Bulk($options);
     $insertedIds = [];
     foreach ($this->documents as $i => $document) {
         $insertedId = $bulk->insert($document);
         if ($insertedId !== null) {
             $insertedIds[$i] = $insertedId;
         } else {
             $insertedIds[$i] = Functions::extractIdFromInsertedDocument($document);
         }
     }
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new InsertManyResult($writeResult, $insertedIds);
 }
Example #22
0
 /**
  * Create one or more indexes for the collection by inserting into the
  * "system.indexes" collection (MongoDB <2.6).
  *
  * @param Server $server
  */
 private function executeLegacy(Server $server)
 {
     $bulk = new Bulk(['ordered' => true]);
     foreach ($this->indexes as $index) {
         $bulk->insert($index);
     }
     $server->executeBulkWrite($this->databaseName . '.system.indexes', $bulk, new WriteConcern(1));
 }
Example #23
0
 /**
  * 指定字段的值-1
  *
  * @param string $key 操作的key user-id-1
  * @param int $val
  * @param string $field 要改变的字段
  * @param mixed $tablePrefix 表前缀 不传则获取配置中配置的前缀
  *
  * @return bool
  */
 public function decrement($key, $val = 1, $field = null, $tablePrefix = null)
 {
     list($tableName, $condition) = $this->parseKey($key, true);
     if (is_null($field) || empty($tableName) || empty($condition)) {
         return false;
     }
     $val = abs(intval($val));
     is_null($tablePrefix) && ($tablePrefix = $this->tablePrefix);
     $tableName = $tablePrefix . $tableName;
     $bulk = new BulkWrite();
     $bulk->update($condition, ['$inc' => [$field => -$val]], ['multi' => true]);
     $result = $this->runMongoBulkWrite($tableName, $bulk);
     Cml::$debug && $this->debugLogSql('BulkWrite DEC', $tableName, $condition, ['$inc' => [$field => -$val]]);
     return $result->getModifiedCount();
 }
Example #24
0
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  * @param Server $server
  * @return BulkWriteResult
  */
 public function execute(Server $server)
 {
     $bulk = new Bulk(['ordered' => $this->options['ordered']]);
     $insertedIds = [];
     foreach ($this->operations as $i => $operation) {
         $type = key($operation);
         $args = current($operation);
         switch ($type) {
             case self::DELETE_MANY:
             case self::DELETE_ONE:
                 $bulk->delete($args[0], $args[1]);
                 break;
             case self::INSERT_ONE:
                 $insertedId = $bulk->insert($args[0]);
                 if ($insertedId !== null) {
                     $insertedIds[$i] = $insertedId;
                 } else {
                     // TODO: This may be removed if PHPC-382 is implemented
                     $insertedIds[$i] = is_array($args[0]) ? $args[0]['_id'] : $args[0]->_id;
                 }
                 break;
             case self::REPLACE_ONE:
             case self::UPDATE_MANY:
             case self::UPDATE_ONE:
                 $bulk->update($args[0], $args[1], $args[2]);
         }
     }
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new BulkWriteResult($writeResult, $insertedIds);
 }
Example #25
0
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  * @param Server $server
  * @return UpdateResult
  */
 public function execute(Server $server)
 {
     $updateOptions = ['multi' => $this->options['multi'], 'upsert' => $this->options['upsert']];
     $bulkOptions = [];
     if (isset($this->options['bypassDocumentValidation']) && \MongoDB\server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)) {
         $bulkOptions['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
     }
     $bulk = new Bulk($bulkOptions);
     $bulk->update($this->filter, $this->update, $updateOptions);
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new UpdateResult($writeResult);
 }
 /**
  * Create one or more indexes for the collection by inserting into the
  * "system.indexes" collection (MongoDB <2.6).
  *
  * @param Server $server
  * @param IndexInput[] $indexes
  */
 private function executeLegacy(Server $server)
 {
     $bulk = new Bulk(true);
     foreach ($this->indexes as $index) {
         $bulk->insert($index);
     }
     $server->executeBulkWrite($this->databaseName . '.system.indexes', $bulk);
 }
Example #27
0
 /**
  * Execute the operation.
  *
  * @see Executable::execute()
  * @param Server $server
  * @return BulkWriteResult
  */
 public function execute(Server $server)
 {
     $options = ['ordered' => $this->options['ordered']];
     if (isset($this->options['bypassDocumentValidation']) && \MongoDB\server_supports_feature($server, self::$wireVersionForDocumentLevelValidation)) {
         $options['bypassDocumentValidation'] = $this->options['bypassDocumentValidation'];
     }
     $bulk = new Bulk($options);
     $insertedIds = [];
     foreach ($this->operations as $i => $operation) {
         $type = key($operation);
         $args = current($operation);
         switch ($type) {
             case self::DELETE_MANY:
             case self::DELETE_ONE:
                 $bulk->delete($args[0], $args[1]);
                 break;
             case self::INSERT_ONE:
                 $insertedId = $bulk->insert($args[0]);
                 if ($insertedId !== null) {
                     $insertedIds[$i] = $insertedId;
                 } else {
                     $insertedIds[$i] = \MongoDB\extract_id_from_inserted_document($args[0]);
                 }
                 break;
             case self::REPLACE_ONE:
             case self::UPDATE_MANY:
             case self::UPDATE_ONE:
                 $bulk->update($args[0], $args[1], $args[2]);
         }
     }
     $writeConcern = isset($this->options['writeConcern']) ? $this->options['writeConcern'] : null;
     $writeResult = $server->executeBulkWrite($this->databaseName . '.' . $this->collectionName, $bulk, $writeConcern);
     return new BulkWriteResult($writeResult, $insertedIds);
 }
 public function testDateTypes()
 {
     //unix seconds: 1451649661
     $mongo_date = new MongoDB\BSON\UTCDateTime(1451649661000 + 501.123456789);
     //01/01/2016 @ 12:01 + 500,000 microseconds
     echo "var dump: " . var_dump($mongo_date) . "\n";
     echo "todatetime: " . var_dump($mongo_date->toDateTime()) . "\n";
     echo "__tostring: |" . var_dump($mongo_date->__toString()) . "|\n";
     $bulk_write = new MongoDB\Driver\BulkWrite(['ordered' => false]);
     $document = ["prop_id" => "leggett-FP-123456", "prop_type" => "residential", "timestamp" => ["utcdatetime" => $mongo_date, "year" => 2016, "month" => "01", "day" => "01", "hour" => "12", "minute" => "01"]];
     $bulk_write->insert($document);
     $this->mongo_manager->executeBulkWrite($this->databaseAndCollectionName(), $bulk_write, $this->write_concern);
 }
Example #29
0
 /**
  * Execute commands batch (bulk).
  * @param string $collectionName collection name.
  * @param array $options batch options.
  * @return array array of 2 elements:
  *
  * - 'insertedIds' - contains inserted IDs.
  * - 'result' - [[\MongoDB\Driver\WriteResult]] instance.
  *
  * @throws Exception on failure.
  * @throws InvalidConfigException on invalid [[document]] format.
  */
 public function executeBatch($collectionName, $options = [])
 {
     $databaseName = $this->databaseName === null ? $this->db->defaultDatabaseName : $this->databaseName;
     $token = $this->log([$databaseName, $collectionName, 'bulkWrite'], $this->document, __METHOD__);
     try {
         $this->beginProfile($token, __METHOD__);
         $batch = new BulkWrite($options);
         $insertedIds = [];
         foreach ($this->document as $key => $operation) {
             switch ($operation['type']) {
                 case 'insert':
                     $insertedIds[$key] = $batch->insert($operation['document']);
                     break;
                 case 'update':
                     $batch->update($operation['condition'], $operation['document'], $operation['options']);
                     break;
                 case 'delete':
                     $batch->delete($operation['condition'], isset($operation['options']) ? $operation['options'] : []);
                     break;
                 default:
                     throw new InvalidConfigException("Unsupported batch operation type '{$operation['type']}'");
             }
         }
         $this->db->open();
         $server = $this->db->manager->selectServer($this->getReadPreference());
         $writeResult = $server->executeBulkWrite($databaseName . '.' . $collectionName, $batch, $this->getWriteConcern());
         $this->endProfile($token, __METHOD__);
     } catch (RuntimeException $e) {
         $this->endProfile($token, __METHOD__);
         throw new Exception($e->getMessage(), $e->getCode(), $e);
     }
     return ['insertedIds' => $insertedIds, 'result' => $writeResult];
 }
Example #30
0
 /**
  * Deletes some collections instance. Returning true on success or false otherwise.
  *
  * @param array $filter
  * @param array $options
  * @param boolean $mode
  * @return boolean|int
  */
 public static function deleteMany($filter = [], $options = [], $mode = true)
 {
     if (!is_array($filter)) {
         throw new Exception('The "filter" must be an array !');
     }
     if (!is_array($options)) {
         throw new Exception('The "options" must be an array !');
     }
     if ($mode) {
         $documents = static::find($filter, $options);
         if ($documents) {
             foreach ($documents as $document) {
                 $document->delete();
             }
         }
         return count($documents);
     } else {
         $className = get_called_class();
         $collection = new $className();
         $db = $collection->getDB();
         $source = $collection->getSource();
         if (empty($source)) {
             throw new Exception('Method getSource() returns empty string');
         }
         /* Specify some command options for the update:
          *
          *  * limit (integer): Deletes all matching documents when 0 (false). Otherwise,
          *    only the first matching document is deleted. */
         if (empty($options)) {
             $options = ["limit" => 0];
         }
         // Create a bulk write object and add our delete operation
         $bulk = new BulkWrite();
         $bulk->delete($filter, $options);
         /* Specify the full namespace as the first argument, followed by the bulk
          * write object and an optional write concern. MongoDB\Driver\WriteResult is
          * returned on success; otherwise, an exception is thrown. */
         $result = $collection->getCollectionManager()->executeBulkWrite($collection, $db, $source, $bulk);
         if (empty($result->getWriteErrors())) {
             return $result->getDeletedCount();
         } else {
             return false;
         }
     }
 }