Skip to content

improve MongoStatement#executeUpdate #40

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 89 additions & 6 deletions src/main/java/com/mongodb/hibernate/jdbc/MongoStatement.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,37 @@

package com.mongodb.hibernate.jdbc;

import static com.mongodb.hibernate.internal.MongoAssertions.assertNotNull;
import static com.mongodb.hibernate.internal.MongoAssertions.assertTrue;
import static com.mongodb.hibernate.internal.VisibleForTesting.AccessModifier.PRIVATE;
import static com.mongodb.hibernate.jdbc.MongoConnection.DATABASE;
import static java.lang.String.format;
import static java.util.Collections.singletonList;

import com.mongodb.MongoExecutionTimeoutException;
import com.mongodb.MongoSocketReadTimeoutException;
import com.mongodb.MongoSocketWriteTimeoutException;
import com.mongodb.MongoTimeoutException;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.DeleteManyModel;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.UpdateManyModel;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.model.WriteModel;
import com.mongodb.hibernate.internal.FeatureNotSupportedException;
import com.mongodb.hibernate.internal.VisibleForTesting;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.sql.SQLTimeoutException;
import java.sql.SQLWarning;
import java.util.ArrayList;
import java.util.List;
import org.bson.BsonDocument;
import org.jspecify.annotations.Nullable;

Expand Down Expand Up @@ -67,14 +84,80 @@ public int executeUpdate(String mql) throws SQLException {
}

int executeUpdateCommand(BsonDocument command) throws SQLException {
var bulkWriteResult = executeBulkWrite(singletonList(command));
return switch (command.getFirstKey()) {
case "insert" -> bulkWriteResult.getInsertedCount();
case "update" -> bulkWriteResult.getModifiedCount();
case "delete" -> bulkWriteResult.getDeletedCount();
default -> throw new FeatureNotSupportedException();
};
}

BulkWriteResult executeBulkWrite(List<? extends BsonDocument> commandBatch) throws SQLException {
startTransactionIfNeeded();

try {
return mongoClient
.getDatabase(DATABASE)
.runCommand(clientSession, command)
.getInteger("n");
} catch (Exception e) {
throw new SQLException("Failed to execute update command", e);
var writeModels = new ArrayList<WriteModel<BsonDocument>>(commandBatch.size());

var commandName = assertNotNull(commandBatch.get(0).getFirstKey());
var collectionName =
assertNotNull(commandBatch.get(0).getString(commandName).getValue());

for (var command : commandBatch) {

assertTrue(commandName.equals(command.getFirstKey()));
assertTrue(collectionName.equals(command.getString(commandName).getValue()));

List<WriteModel<BsonDocument>> subWriteModels;

switch (commandName) {
case "insert":
var documents = command.getArray("documents");
subWriteModels = new ArrayList<>(documents.size());
for (var document : documents) {
subWriteModels.add(new InsertOneModel<>((BsonDocument) document));
}
break;
case "update":
var updates = command.getArray("updates").getValues();
subWriteModels = new ArrayList<>(updates.size());
for (var update : updates) {
var updateDocument = (BsonDocument) update;
WriteModel<BsonDocument> updateModel =
!updateDocument.getBoolean("multi").getValue()
? new UpdateOneModel<>(
updateDocument.getDocument("q"), updateDocument.getDocument("u"))
: new UpdateManyModel<>(
updateDocument.getDocument("q"), updateDocument.getDocument("u"));
subWriteModels.add(updateModel);
}
break;
case "delete":
var deletes = command.getArray("deletes");
subWriteModels = new ArrayList<>(deletes.size());
for (var delete : deletes) {
var deleteDocument = (BsonDocument) delete;
subWriteModels.add(
deleteDocument.getNumber("limit").intValue() == 1
? new DeleteOneModel<>(deleteDocument.getDocument("q"))
: new DeleteManyModel<>(deleteDocument.getDocument("q")));
}
break;
default:
throw new FeatureNotSupportedException();
}
writeModels.addAll(subWriteModels);
}
return getMongoDatabase()
.getCollection(collectionName, BsonDocument.class)
.bulkWrite(clientSession, writeModels);
} catch (MongoSocketReadTimeoutException
| MongoSocketWriteTimeoutException
| MongoTimeoutException
| MongoExecutionTimeoutException e) {
throw new SQLTimeoutException(e.getMessage(), e);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MongoOperationTimeoutException is the only child class of MongoTimeoutException which has been listed here.

} catch (RuntimeException e) {
throw new SQLException("Failed to execute bulk write: " + e.getMessage(), e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,27 @@
package com.mongodb.hibernate.jdbc;

import static java.lang.String.format;
import static org.bson.BsonDocument.parse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

import com.mongodb.bulk.BulkWriteInsert;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.bulk.BulkWriteUpsert;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.WriteModel;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.sql.Array;
Expand All @@ -40,10 +48,10 @@
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.bson.BsonDocument;
import org.bson.Document;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
Expand Down Expand Up @@ -100,16 +108,52 @@ class ParameterValueSettingTests {
private MongoDatabase mongoDatabase;

@Captor
private ArgumentCaptor<BsonDocument> commandCaptor;
private ArgumentCaptor<List<WriteModel<BsonDocument>>> writeModelsCaptor;

@Test
@DisplayName("Happy path when all parameters are provided values")
void testSuccess() throws SQLException {
void testSuccess(@Mock MongoCollection<BsonDocument> mongoCollection) throws SQLException {
// given
doReturn(mongoDatabase).when(mongoClient).getDatabase(anyString());
doReturn(Document.parse("{ok: 1.0, n: 1}"))
.when(mongoDatabase)
.runCommand(eq(clientSession), any(BsonDocument.class));
doReturn(mongoCollection).when(mongoDatabase).getCollection(anyString(), eq(BsonDocument.class));
doReturn(new BulkWriteResult() {
@Override
public boolean wasAcknowledged() {
return false;
}

@Override
public int getInsertedCount() {
return 1;
}

@Override
public int getMatchedCount() {
return 0;
}

@Override
public int getDeletedCount() {
return 0;
}

@Override
public int getModifiedCount() {
return 0;
}

@Override
public List<BulkWriteInsert> getInserts() {
return List.of();
}

@Override
public List<BulkWriteUpsert> getUpserts() {
return List.of();
}
})
.when(mongoCollection)
.bulkWrite(eq(clientSession), anyList());

// when && then
try (var preparedStatement = createMongoPreparedStatement(EXAMPLE_MQL)) {
Expand All @@ -122,26 +166,24 @@ void testSuccess() throws SQLException {

preparedStatement.executeUpdate();

verify(mongoDatabase).runCommand(eq(clientSession), commandCaptor.capture());
var command = commandCaptor.getValue();
var expectedDoc = BsonDocument.parse(
verify(mongoCollection).bulkWrite(eq(clientSession), writeModelsCaptor.capture());
var writeModels = writeModelsCaptor.getValue();
assertEquals(1, writeModels.size());
var writeModel = writeModels.get(0);
assertInstanceOf(InsertOneModel.class, writeModel);
var insertDoc = ((InsertOneModel<BsonDocument>) writeModel).getDocument();
var expectedDoc = parse(
"""
{
insert: "books",
documents: [
{
title: "War and Peace",
author: "Leo Tolstoy",
publishYear: 1869,
outOfStock: false,
tags: [
"classic"
]
}
title: "War and Peace",
author: "Leo Tolstoy",
publishYear: 1869,
outOfStock: false,
tags: [
"classic"
]
}
""");
assertEquals(expectedDoc, command);
}""");
assertEquals(expectedDoc, insertDoc);
}
}

Expand Down Expand Up @@ -221,14 +263,16 @@ private static Stream<Arguments> getMongoPreparedStatementMethodInvocationsImpac
Map.entry(
"setObject(int,Object,int)",
pstmt -> pstmt.setObject(1, Mockito.mock(Array.class), Types.OTHER)),
Map.entry("addBatch()", MongoPreparedStatement::addBatch),
Map.entry("setArray(int,Array)", pstmt -> pstmt.setArray(1, Mockito.mock(Array.class))),
Map.entry("setDate(int,Date,Calendar)", pstmt -> pstmt.setDate(1, new Date(now), calendar)),
Map.entry("setTime(int,Time,Calendar)", pstmt -> pstmt.setTime(1, new Time(now), calendar)),
Map.entry(
"setTimestamp(int,Timestamp,Calendar)",
pstmt -> pstmt.setTimestamp(1, new Timestamp(now), calendar)),
Map.entry("setNull(int,Object,String)", pstmt -> pstmt.setNull(1, Types.STRUCT, "BOOK")))
Map.entry("setNull(int,Object,String)", pstmt -> pstmt.setNull(1, Types.STRUCT, "BOOK")),
Map.entry("addBatch()", MongoPreparedStatement::addBatch),
Map.entry("clearBatch()", MongoPreparedStatement::clearBatch),
Map.entry("executeBatch()", MongoPreparedStatement::executeBatch))
.entrySet()
.stream()
.map(entry -> Arguments.of(entry.getKey(), entry.getValue()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,16 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;

import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
Expand Down Expand Up @@ -90,11 +92,13 @@ void testSQLExceptionThrownWhenCalledWithInvalidMql() {

@Test
@DisplayName("SQLException is thrown when database access error occurs")
void testSQLExceptionThrownWhenDBAccessFailed(@Mock MongoDatabase mongoDatabase) {
void testSQLExceptionThrownWhenDBAccessFailed(
@Mock MongoDatabase mongoDatabase, @Mock MongoCollection<BsonDocument> mongoCollection) {
// given
doReturn(mongoDatabase).when(mongoClient).getDatabase(anyString());
doReturn(mongoCollection).when(mongoDatabase).getCollection(anyString(), eq((BsonDocument.class)));
var dbAccessException = new RuntimeException();
doThrow(dbAccessException).when(mongoDatabase).runCommand(same(clientSession), any(BsonDocument.class));
doThrow(dbAccessException).when(mongoCollection).bulkWrite(same(clientSession), anyList());
String mql =
"""
{
Expand Down