Skip to content
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

Adds support for updateMany changes #574

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
42 changes: 42 additions & 0 deletions src/main/java/liquibase/ext/mongodb/change/UpdateManyChange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package liquibase.ext.mongodb.change;

import liquibase.change.ChangeMetaData;
import liquibase.change.CheckSum;
import liquibase.change.DatabaseChange;
import liquibase.database.Database;
import liquibase.ext.mongodb.statement.UpdateManyStatement;
import liquibase.statement.SqlStatement;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@DatabaseChange(name = "updateMany",
description = "Updates all documents that match the specified filter for a collection " +
"https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany",
priority = ChangeMetaData.PRIORITY_DEFAULT, appliesTo = "collection")
@NoArgsConstructor
@Getter
@Setter
public class UpdateManyChange extends AbstractMongoChange {

private String collectionName;
private String filter;
private String update;

@Override
public String getConfirmationMessage() {
return "Documents updated in collection " + getCollectionName();
}

@Override
public SqlStatement[] generateStatements(final Database database) {
return new SqlStatement[]{
new UpdateManyStatement(collectionName, filter, update)
};
}

@Override
public CheckSum generateCheckSum() {
return super.generateCheckSum(collectionName, filter, update);
}
}
16 changes: 16 additions & 0 deletions src/main/java/liquibase/ext/mongodb/statement/BsonUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,27 @@

import com.mongodb.DBRefCodecProvider;
import com.mongodb.MongoClientSettings;

import lombok.NoArgsConstructor;

import org.bson.Document;
import org.bson.UuidRepresentation;
import org.bson.codecs.*;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.util.Objects.nonNull;
import static java.util.Optional.ofNullable;

import static liquibase.util.StringUtil.trimToNull;
import static lombok.AccessLevel.PRIVATE;

import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import org.bson.conversions.Bson;

@NoArgsConstructor(access = PRIVATE)
public final class BsonUtils {
Expand Down Expand Up @@ -77,6 +83,16 @@ public static List<Document> orEmptyList(final String json) {
);
}

public static Class<?> classOf(final String json) {
return (
ofNullable(trimToNull(json))
.map(jn -> "{ " + ITEMS + ": " + jn + "}")
.map(s -> Document.parse(s, DOCUMENT_CODEC))
.map(d -> d.get(ITEMS).getClass())
.orElse(null)
);
}

public static String toJson(final Document document) {
return ofNullable(document).map(Document::toJson).orElse(null);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,24 @@
* #L%
*/

import java.util.ArrayList;
import java.util.List;
import static java.util.Optional.ofNullable;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.client.MongoCollection;

import liquibase.ext.mongodb.database.MongoLiquibaseDatabase;
import static liquibase.ext.mongodb.statement.AbstractRunCommandStatement.SHELL_DB_PREFIX;
import static liquibase.ext.mongodb.statement.BsonUtils.classOf;
import static liquibase.ext.mongodb.statement.BsonUtils.orEmptyDocument;
import static liquibase.ext.mongodb.statement.BsonUtils.orEmptyList;
import liquibase.nosql.statement.NoSqlExecuteStatement;
import liquibase.nosql.statement.NoSqlUpdateStatement;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.bson.Document;
import org.bson.conversions.Bson;

import static java.util.Optional.ofNullable;
import static liquibase.ext.mongodb.statement.AbstractRunCommandStatement.SHELL_DB_PREFIX;

@Getter
@EqualsAndHashCode(callSuper = true)
Expand All @@ -40,12 +47,31 @@ public class UpdateManyStatement extends AbstractCollectionStatement
public static final String COMMAND_NAME = "updateMany";

private final Bson filter;
private final Bson document;
private Bson update = null;
private List<? extends Bson> aggregation = null;

public UpdateManyStatement(final String collectionName, final String filter, final String update) {
super(collectionName);
this.filter = orEmptyDocument(filter);
Class<?> clazz = classOf(update);

if (Document.class.equals(clazz)) {
this.update = orEmptyDocument(update);
} else if (ArrayList.class.equals(clazz)) {
this.aggregation = orEmptyList(update);
}
}

public UpdateManyStatement(final String collectionName, final Bson filter, final Bson document) {
public UpdateManyStatement(final String collectionName, final Bson filter, final Bson update) {
super(collectionName);
this.filter = filter;
this.document = document;
this.update = update;
}

public UpdateManyStatement(final String collectionName, final Bson filter, final List<? extends Bson> aggregation) {
super(collectionName);
this.filter = filter;
this.aggregation = aggregation;
}

@Override
Expand All @@ -55,15 +81,23 @@ public String getCommandName() {

@Override
public String toJs() {
String updateString = "{}";

if (update != null) {
updateString = update.toBsonDocument().toJson();
} else if (aggregation != null) {
updateString = "[" + String.join(",", aggregation.stream().map(u -> u.toBsonDocument().toJson()).toArray(String[]::new)) + "]";
}

return
SHELL_DB_PREFIX +
getCollectionName() +
"." +
getCommandName() +
"(" +
ofNullable(filter).map(Bson::toString).orElse(null) +
ofNullable(filter).map(f -> f.toBsonDocument().toJson()).orElse(null) +
", " +
ofNullable(document).map(Bson::toString).orElse(null) +
updateString +
");";
}

Expand All @@ -75,6 +109,13 @@ public void execute(final MongoLiquibaseDatabase database) {
@Override
public int update(final MongoLiquibaseDatabase database) {
final MongoCollection<Document> collection = database.getMongoDatabase().getCollection(getCollectionName());
return (int) collection.updateMany(filter, document).getMatchedCount();

if (update != null) {
return (int) collection.updateMany(filter, update).getMatchedCount();
} else if (aggregation != null) {
return (int) collection.updateMany(filter, aggregation).getMatchedCount();
}

return 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ liquibase.ext.mongodb.change.DropIndexChange
liquibase.ext.mongodb.change.InsertManyChange
liquibase.ext.mongodb.change.InsertOneChange
liquibase.ext.mongodb.change.RunCommandChange
liquibase.ext.mongodb.change.UpdateManyChange
Original file line number Diff line number Diff line change
Expand Up @@ -140,5 +140,20 @@
<xsd:attribute name="collectionName" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>


<xsd:element name="updateMany">

<xsd:complexType>

<xsd:all>
<xsd:element name="filter" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="update" type="xsd:string" minOccurs="1" maxOccurs="1"/>
</xsd:all>

<xsd:attribute name="collectionName" type="xsd:string" use="required"/>

</xsd:complexType>

</xsd:element>

</xsd:schema>
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package liquibase.ext.mongodb.change;

/*-
* #%L
* Liquibase MongoDB Extension
* %%
* Copyright (C) 2019 Mastercard
* %%
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/

import liquibase.ChecksumVersion;
import liquibase.changelog.ChangeSet;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;

import java.util.List;

import static liquibase.ext.mongodb.TestUtils.getChangesets;
import static org.assertj.core.api.Assertions.assertThat;

class UpdateManyChangeTest extends AbstractMongoChangeTest {

@Test
void getConfirmationMessage() {
final UpdateManyChange updateManyChange = new UpdateManyChange();
updateManyChange.setCollectionName("collection1");
assertThat(updateManyChange.getConfirmationMessage()).isEqualTo("Documents updated in collection collection1");
}

@Test
@SneakyThrows
void generateStatements() {
final List<ChangeSet> changeSets = getChangesets("liquibase/ext/changelog.update-many.test.xml", database);

assertThat(changeSets)
.hasSize(1).first()
.returns("9:221a9c901f6a318845c509ff231d3698", changeSet -> changeSet.generateCheckSum(ChecksumVersion.latest()).toString());

assertThat(changeSets.get(0).getChanges())
.hasSize(1)
.hasOnlyElementsOfType(UpdateManyChange.class);

assertThat(changeSets.get(0).getChanges().get(0))
.hasFieldOrPropertyWithValue("collectionName", "updateManyTest1")
.hasFieldOrPropertyWithValue("filter", "{ name: \"first\" }")
.hasFieldOrPropertyWithValue("update", "{ $set: { name: \"modified\" } }");
}
}
Loading
Loading