Exemplo n.º 1
0
    def _update(self, filter, update, upsert, multi, **kwargs):
        validate_is_mapping("filter", filter)
        validate_boolean("upsert", upsert)

        if self.write_concern.acknowledged:
            updates = [
                SON([('q', filter), ('u', update), ("upsert", upsert),
                     ("multi", multi)])
            ]

            command = SON([("update", self._collection_name),
                           ("updates", updates),
                           ("writeConcern", self.write_concern.document)])
            raw_response = yield self._database.command(command, **kwargs)
            _check_write_command_response([[0, raw_response]])

            # Extract upserted_id from returned array
            if raw_response.get("upserted"):
                raw_response["upserted"] = raw_response["upserted"][0]["_id"]

        else:
            yield self.update(filter,
                              update,
                              upsert=upsert,
                              multi=multi,
                              **kwargs)
            raw_response = None

        defer.returnValue(raw_response)
Exemplo n.º 2
0
def got_app_error(topology, app_error):
    server_address = common.partition_node(app_error['address'])
    server = topology.get_server_by_address(server_address)
    error_type = app_error['type']
    generation = app_error.get(
        'generation', server.pool.gen.get_overall())
    when = app_error['when']
    max_wire_version = app_error['maxWireVersion']
    # XXX: We could get better test coverage by mocking the errors on the
    # Pool/SocketInfo.
    try:
        if error_type == 'command':
            _check_command_response(app_error['response'], max_wire_version)
            _check_write_command_response(app_error['response'])
        elif error_type == 'network':
            raise AutoReconnect('mock non-timeout network error')
        elif error_type == 'timeout':
            raise NetworkTimeout('mock network timeout error')
        else:
            raise AssertionError('unknown error type: %s' % (error_type,))
        assert False
    except (AutoReconnect, NotPrimaryError, OperationFailure) as e:
        if when == 'beforeHandshakeCompletes':
            completed_handshake = False
        elif when == 'afterHandshakeCompletes':
            completed_handshake = True
        else:
            assert False, 'Unknown when field %s' % (when,)

        topology.handle_error(
            server_address, _ErrorContext(e, max_wire_version, generation,
                                          completed_handshake, None))
Exemplo n.º 3
0
    def insert_one(self, document, **kwargs):
        """Insert a single document into collection

        :param document: Document to insert
        :returns:
            :class:`Deferred` that called back with
            :class:`pymongo.results.InsertOneResult`
        """
        inserted_ids, response = yield self._insert_one_or_many([document], **kwargs)
        if response:
            _check_write_command_response([[0, response]])
        defer.returnValue(InsertOneResult(inserted_ids[0], self.write_concern.acknowledged))
Exemplo n.º 4
0
    def insert_one(self, document, **kwargs):
        """Insert a single document into collection

        :param document: Document to insert
        :returns:
            :class:`Deferred` that called back with
            :class:`pymongo.results.InsertOneResult`
        """
        inserted_ids, response = yield self._insert_one_or_many([document],
                                                                **kwargs)
        if response:
            _check_write_command_response([[0, response]])
        defer.returnValue(
            InsertOneResult(inserted_ids[0], self.write_concern.acknowledged))
Exemplo n.º 5
0
        def _find_and_modify(session, sock_info, retryable_write):
            if (sock_info.max_wire_version >= 4
                    and not write_concern.is_server_default):
                cmd['writeConcern'] = write_concern.document
            result = self._command(sock_info,
                                   cmd,
                                   read_preference=ReadPreference.PRIMARY,
                                   collation=collation,
                                   session=session,
                                   retryable_write=retryable_write,
                                   user_fields=_FIND_AND_MODIFY_DOC_FIELDS)

            _check_write_command_response(result)
            return result
Exemplo n.º 6
0
    def _delete(self, filter, multi):
        validate_is_mapping("filter", filter)

        if self.write_concern.acknowledged:
            deletes = [SON([("q", filter), ("limit", 0 if multi else 1)])]
            command = SON(
                [("delete", self._collection_name), ("deletes", deletes), ("writeConcern", self.write_concern.document)]
            )

            raw_response = yield self._database.command(command)
            _check_write_command_response([[0, raw_response]])

        else:
            yield self.remove(filter, single=not multi)
            raw_response = None

        defer.returnValue(raw_response)
Exemplo n.º 7
0
    def _delete(self, filter, multi, **kwargs):
        validate_is_mapping("filter", filter)

        if self.write_concern.acknowledged:
            deletes = [SON([('q', filter), ("limit", 0 if multi else 1)])]
            command = SON([("delete", self._collection_name),
                           ("deletes", deletes),
                           ("writeConcern", self.write_concern.document)])

            raw_response = yield self._database.command(command, **kwargs)
            _check_write_command_response([[0, raw_response]])

        else:
            yield self.remove(filter, single=not multi, **kwargs)
            raw_response = None

        defer.returnValue(raw_response)
Exemplo n.º 8
0
    def _insert_one_or_many(self, documents, ordered=True, **kwargs):
        if self.write_concern.acknowledged:
            inserted_ids = []
            for doc in documents:
                if "_id" not in doc:
                    doc["_id"] = ObjectId()
                inserted_ids.append(doc["_id"])

            command = SON([("insert", self._collection_name),
                           ("documents", documents),
                           ("ordered", ordered),
                           ("writeConcern", self.write_concern.document)])
            response = yield self._database.command(command, **kwargs)
            _check_write_command_response([[0, response]])
        else:
            # falling back to OP_INSERT in case of unacknowledged op
            flags = INSERT_CONTINUE_ON_ERROR if not ordered else 0
            inserted_ids = yield self.insert(documents, flags=flags, **kwargs)

        defer.returnValue(inserted_ids)
Exemplo n.º 9
0
    def _update(self, filter, update, upsert, multi):
        validate_is_mapping("filter", filter)
        validate_boolean("upsert", upsert)

        if self.write_concern.acknowledged:
            updates = [SON([("q", filter), ("u", update), ("upsert", upsert), ("multi", multi)])]

            command = SON(
                [("update", self._collection_name), ("updates", updates), ("writeConcern", self.write_concern.document)]
            )
            raw_response = yield self._database.command(command)
            _check_write_command_response([[0, raw_response]])

            # Extract upserted_id from returned array
            if raw_response.get("upserted"):
                raw_response["upserted"] = raw_response["upserted"][0]["_id"]

        else:
            yield self.update(filter, update, upsert=upsert, multi=multi)
            raw_response = None

        defer.returnValue(raw_response)
Exemplo n.º 10
0
 def insert_one(self, document, **kwargs):
     inserted_ids, response = yield self._insert_one_or_many([document], **kwargs)
     if response:
         _check_write_command_response([[0, response]])
     defer.returnValue(InsertOneResult(inserted_ids[0], self.write_concern.acknowledged))
Exemplo n.º 11
0
 def insert_one(self, document, **kwargs):
     inserted_ids, response = yield self._insert_one_or_many([document], **kwargs)
     if response:
         _check_write_command_response([[0, response]])
     defer.returnValue(InsertOneResult(inserted_ids[0], self.write_concern.acknowledged))