package com.mongodb.internal.connection;
import com.mongodb.MongoNamespace;
import com.mongodb.WriteConcernResult;
import com.mongodb.async.SingleResultCallback;
import com.mongodb.bulk.DeleteRequest;
import com.mongodb.connection.ByteBufferBsonOutput;
import com.mongodb.diagnostics.logging.Logger;
import com.mongodb.diagnostics.logging.Loggers;
import org.bson.BsonArray;
import org.bson.BsonDocument;
import org.bson.BsonInt32;
import static com.mongodb.internal.connection.ByteBufBsonDocument.createOne;
import static java.lang.String.format;
import static java.util.Collections.singletonList;
class DeleteProtocol extends WriteProtocol {
private static final Logger LOGGER = Loggers.getLogger("protocol.delete");
private final DeleteRequest deleteRequest;
DeleteProtocol(final MongoNamespace namespace, final boolean ordered, final DeleteRequest deleteRequest) {
super(namespace, ordered);
this.deleteRequest = deleteRequest;
}
@Override
public WriteConcernResult execute(final InternalConnection connection) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(format("Deleting documents from namespace %s on connection [%s] to server %s", getNamespace(),
connection.getDescription().getConnectionId(), connection.getDescription().getServerAddress()));
}
WriteConcernResult writeConcernResult = super.execute(connection);
LOGGER.debug("Delete completed");
return writeConcernResult;
}
@Override
public void executeAsync(final InternalConnection connection, final SingleResultCallback<WriteConcernResult> callback) {
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(format("Asynchronously deleting documents in namespace %s on connection [%s] to server %s", getNamespace(),
connection.getDescription().getConnectionId(), connection.getDescription().getServerAddress()));
}
super.executeAsync(connection, new SingleResultCallback<WriteConcernResult>() {
@Override
public void onResult(final WriteConcernResult result, final Throwable t) {
if (t != null) {
callback.onResult(null, t);
} else {
LOGGER.debug("Asynchronous delete completed");
callback.onResult(result, null);
}
}
});
} catch (Throwable t) {
callback.onResult(null, t);
}
}
@Override
protected BsonDocument getAsWriteCommand(final ByteBufferBsonOutput bsonOutput, final int firstDocumentPosition) {
BsonDocument deleteDocument = new BsonDocument("q", createOne(bsonOutput, firstDocumentPosition))
.append("limit", deleteRequest.isMulti() ? new BsonInt32(0) : new BsonInt32(1));
return getBaseCommandDocument("delete").append("deletes", new BsonArray(singletonList(deleteDocument)));
}
@Override
protected RequestMessage createRequestMessage(final MessageSettings settings) {
return new DeleteMessage(getNamespace().getFullName(), deleteRequest, settings);
}
@Override
protected Logger getLogger() {
return LOGGER;
}
}