From 4991921372fab61ec0840518c5d74370bd9055a4 Mon Sep 17 00:00:00 2001 From: evanchooly Date: Mon, 23 Nov 2026 10:13:31 -0500 Subject: [PATCH] Generate find and update cases from query and update pages The query/filters and query/updates families are generated: a find becomes runner.find with the filter's Filters calls, an update runner.update with the filter and one UpdateOperators call per field. The runner gains option-free find and update overloads, and a new UPDATE binding position covers the field update operators. Query and update operands are data, so their arrays are lists rather than array expressions. Two cases are generated, integrated under both mappers and promoted; a third is excluded because its page prints the whole collection after the update, not the documents the filter still matches. --- audits/catalog/dsl-bindings.json | 165 +++++++++++++++ audits/catalog/generation-review.json | 8 +- .../morphia/audits/generate/CaseGenerator.kt | 124 ++++++++--- .../morphia/audits/generate/DslBindings.kt | 14 +- .../morphia/audits/offline/GeneratorTest.kt | 99 ++++++++- .../dev/morphia/test/OperatorCaseRunner.java | 15 ++ .../test/generated/filters/TestIn.java | 29 +++ .../generated/updates/TestPositionalAll.java | 26 +++ .../in/matchValuesInAnArray/scenario.json | 92 ++++++++ .../updateAllElementsInAnArray/scenario.json | 197 ++++++++++++++++++ .../dev/morphia/test/generated/manifest.json | 26 +++ design/operator-audits-design.md | 19 +- design/operator-audits-progress.md | 24 ++- 13 files changed, 789 insertions(+), 49 deletions(-) create mode 100644 core/src/test/java/dev/morphia/test/generated/filters/TestIn.java create mode 100644 core/src/test/java/dev/morphia/test/generated/updates/TestPositionalAll.java create mode 100644 core/src/test/resources/dev/morphia/test/generated/fixtures/filters/in/matchValuesInAnArray/scenario.json create mode 100644 core/src/test/resources/dev/morphia/test/generated/fixtures/updates/positional-all/updateAllElementsInAnArray/scenario.json diff --git a/audits/catalog/dsl-bindings.json b/audits/catalog/dsl-bindings.json index 30c13ff7041..0ca035c64dc 100644 --- a/audits/catalog/dsl-bindings.json +++ b/audits/catalog/dsl-bindings.json @@ -705,6 +705,171 @@ "arguments": [], "options": {}, "fields": {} + }, + { + "operator": "$addToSet", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "addToSet", + "parameters": [ + "java.lang.String", + "java.lang.Object" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$inc", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "inc", + "parameters": [ + "java.lang.String", + "java.lang.Number" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$max", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "max", + "parameters": [ + "java.lang.String", + "java.lang.Number" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$min", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "min", + "parameters": [ + "java.lang.String", + "java.lang.Number" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$mul", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "mul", + "parameters": [ + "java.lang.String", + "java.lang.Number" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$pull", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "pull", + "parameters": [ + "java.lang.String", + "java.lang.Object" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$pullAll", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "pullAll", + "parameters": [ + "java.lang.String", + "java.util.List" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$push", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "push", + "parameters": [ + "java.lang.String", + "java.lang.Object" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$rename", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "rename", + "parameters": [ + "java.lang.String", + "java.lang.String" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$set", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "set", + "parameters": [ + "java.lang.String", + "java.lang.Object" + ], + "varargs": false, + "arguments": [], + "options": {}, + "fields": {} + }, + { + "operator": "$unset", + "position": "UPDATE", + "form": "FIELD", + "owner": "dev.morphia.query.updates.UpdateOperators", + "method": "unset", + "parameters": [ + "java.lang.String", + "java.lang.String[]" + ], + "varargs": true, + "arguments": [], + "options": {}, + "fields": {} } ] } diff --git a/audits/catalog/generation-review.json b/audits/catalog/generation-review.json index 66a99f92c55..2ac82a9fb86 100644 --- a/audits/catalog/generation-review.json +++ b/audits/catalog/generation-review.json @@ -1,7 +1,9 @@ { "schemaVersion": 1, "families": [ - "aggregation/expressions" + "aggregation/expressions", + "query/filters", + "query/updates" ], "excluded": [ { @@ -15,6 +17,10 @@ { "name": "aggregation/expressions/filter/useIdxToAccessTheIndex", "reason": "$$IDX is newer than the tests' MongoDB 8.2, which rejects it (Use of undefined variable: IDX); 8.3 cannot run on the test hosts' kernels (SERVER-121912)." + }, + { + "name": "query/updates/positional-all/updateArraysSpecifiedUsingANegationQueryOperator", + "reason": "The page prints the whole collection after the update; the runner's update results are the documents its filter still matches, as the legacy tests read them. Serialization and behavior pass." } ], "sampleDatasets": { diff --git a/audits/src/main/kotlin/dev/morphia/audits/generate/CaseGenerator.kt b/audits/src/main/kotlin/dev/morphia/audits/generate/CaseGenerator.kt index 177502f5686..79bd31b1759 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/generate/CaseGenerator.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/generate/CaseGenerator.kt @@ -80,6 +80,8 @@ object CaseGenerator { private const val OBJECT = "java.lang.Object" private const val STRING = "java.lang.String" private const val ITERABLE = "java.lang.Iterable" + private const val LIST = "java.util.List" + private const val NUMBER = "java.lang.Number" private const val SORTS = "dev.morphia.query.Sort[]" /** The binding key of an array literal in an expression. */ const val ARRAY = "[]" @@ -106,6 +108,10 @@ object CaseGenerator { catalog.bindings .filter { it.position == BindingPosition.FILTER } .associateBy { it.operator } + val updates = + catalog.bindings + .filter { it.position == BindingPosition.UPDATE } + .associateBy { it.operator } val excluded = review.excluded.associate { it.name to it.reason } val cases = mutableListOf>() val gaps = mutableListOf() @@ -152,17 +158,39 @@ object CaseGenerator { failure.message!!.removePrefix("$name: "), ) } - if (documented.shape != ActionShape.PIPELINE) { + if (documented.shape == ActionShape.FIND && documented.action.size != 1) { return@forEach gap( GapKind.SOURCE_UNSUPPORTED, - "a ${documented.shape} action is not generated yet", + "a documented projection is not generated yet", ) } - val emitted = Emitter(stages, expressions, filters) - val pipeline = + val emitted = Emitter(stages, expressions, filters, updates) + val resource = + FixtureMigration.scenarioPath(name, GENERATED).removePrefix(RESOURCES) + val indent = "\n " + val call = try { - documented.action.mapIndexed { index, stage -> - emitted.stage(stage, "/pipeline/$index") + when (documented.shape) { + ActionShape.PIPELINE -> { + val pipeline = + documented.action.mapIndexed { index, stage -> + emitted.stage(stage, "/pipeline/$index") + } + "runner.aggregate(\n OperatorCase.of(${literal(resource)}),\n" + + " (aggregation) -> aggregation.pipeline($indent" + + pipeline.joinToString(",$indent") + + "));" + } + ActionShape.FIND -> + "runner.find(\n OperatorCase.of(${literal(resource)}),\n" + + " ${query(emitted.filters(documented.action[0], "/filter"))});" + ActionShape.UPDATE -> { + val operators = emitted.updates(documented.action[1], "/update") + "runner.update(\n OperatorCase.of(${literal(resource)}),\n" + + " ${query(emitted.filters(documented.action[0], "/filter"))}," + + operators.joinToString(",") { "\n $it" } + + ");" + } } } catch (unbound: Unbound) { return@forEach gap(GapKind.UNBOUND, unbound.message!!) @@ -173,7 +201,6 @@ object CaseGenerator { review.sampleDatasets[documented.collection].takeIf { example.blocks.none { it.role == BlockRole.DATA } } - val scenario = FixtureMigration.scenarioPath(name, GENERATED) val override = FormOverride( fixture = name, @@ -190,16 +217,12 @@ object CaseGenerator { retiredLock = null, fixtureFiles = emptyMap(), ) - val resource = scenario.removePrefix(RESOURCES) val method = """ | @Test | @DisplayName(${literal(example.name ?: example.title)}) | public void $stem() { - | runner.aggregate( - | OperatorCase.of(${literal(resource)}), - | (aggregation) -> aggregation.pipeline( - | ${pipeline.joinToString(",\n ")})); + | $call | } |""" .trimMargin() @@ -231,6 +254,11 @@ object CaseGenerator { ) } + /** The query function of a find or an update: its filters, or the query itself for none. */ + private fun query(filters: List): String = + if (filters.isEmpty()) "(query) -> query" + else "(query) -> query.filter(${filters.joinToString(", ")})" + private fun type( qualified: String, cases: List, @@ -302,6 +330,7 @@ object CaseGenerator { val stages: Map, val expressions: Map, val filters: Map, + val updates: Map, ) { /** Owner and method of every factory called. */ val calls = mutableSetOf>() @@ -396,19 +425,7 @@ object CaseGenerator { ".$method(${literal(field)}, ${value(each, OBJECT, "$path/$field")})" } } - BindingForm.FILTERS -> { - if (!argument.isDocument) - throw Unbound("$path: ${binding.operator} takes a query document") - factory.format( - argument - .asDocument() - .entries - .flatMap { (field, predicate) -> - predicates(field, predicate, "$path/$field") - } - .joinToString(", ") - ) - } + BindingForm.FILTERS -> factory.format(filters(argument, path).joinToString(", ")) BindingForm.FIELD -> throw Unbound("$path: ${binding.operator} is a query operator, not a value") BindingForm.GROUP -> { @@ -472,6 +489,37 @@ object CaseGenerator { } } + /** The filters of a query document, one per field operator, in order. */ + fun filters(query: BsonValue, path: String): List { + if (!query.isDocument) throw Unbound("$path: not a query document") + return query.asDocument().entries.flatMap { (field, predicate) -> + predicates(field, predicate, "$path/$field") + } + } + + /** The update operators of an update document, one call per field, in order. */ + fun updates(update: BsonValue, path: String): List { + if (!update.isDocument) throw Unbound("$path: a pipeline update has no binding") + return update.asDocument().entries.flatMap { (operator, fields) -> + val binding = + updates[operator] + ?: throw Unbound( + "$path/$operator: update operator $operator has no binding" + ) + if (!fields.isDocument) throw Unbound("$path/$operator: $operator takes a document") + calls += binding.owner to binding.method + fields.asDocument().entries.map { (field, value) -> + // A field-only factory (`$unset`'s `unset(String, String...)`) ignores the + // value. + if (binding.parameters.size == 1 || binding.varargs) + "${binding.method}(${literal(field)})" + else + "${binding.method}(${literal(field)}, " + + "${value(value, binding.parameters[1], "$path/$operator/$field", plain = true)})" + } + } + } + /** The filters of one field's predicate: one per operator, or `$eq` for a plain value. */ private fun predicates(field: String, predicate: BsonValue, path: String): List { if (field.startsWith("$")) throw Unbound("$path: query operator $field has no binding") @@ -504,7 +552,7 @@ object CaseGenerator { throw Unbound("$path: $operator $value has no binding") return "${binding.method}(${literal(field)})" } - return "${binding.method}(${literal(field)}, ${value(value, binding.parameters[1], path)})" + return "${binding.method}(${literal(field)}, ${value(value, binding.parameters[1], path, plain = true)})" } /** @@ -522,19 +570,28 @@ object CaseGenerator { else -> null } - /** [value] as an argument of [type]; anything its type cannot take is unbound. */ - private fun value(value: BsonValue, type: String, path: String): String { + /** + * [value] as an argument of [type]; anything its type cannot take is unbound. A [plain] + * value (a query or update operand) is data, so its arrays are lists; elsewhere an array is + * an expression. + */ + private fun value( + value: BsonValue, + type: String, + path: String, + plain: Boolean = false, + ): String { operator(value, path)?.let { (operator, argument) -> val binding = expressions[operator] ?: throw Unbound("$path: $operator has no binding") return call(binding, argument, "$path/$operator") } - if (value.isArray && type == ITERABLE) { + if (value.isArray && (type == ITERABLE || type == LIST || plain && type == OBJECT)) { val items = value.asArray().values if (items.any { it.isNull }) throw Unbound("$path: List.of cannot hold null") types += "java.util.List" return items - .mapIndexed { index, item -> value(item, OBJECT, "$path/$index") } + .mapIndexed { index, item -> value(item, OBJECT, "$path/$index", plain) } .joinToString(", ", "List.of(", ")") } if (value.isDocument && type == SORTS) { @@ -573,6 +630,13 @@ object CaseGenerator { STRING -> if (value.isString) literal(value.asString().value) else throw Unbound("$path: ${value.bsonType} where $type is required") + NUMBER -> + when { + value.isInt32 -> "${value.asInt32().value}" + value.isInt64 -> "${value.asInt64().value}L" + value.isDouble -> double(value.asDouble().value) + else -> throw Unbound("$path: ${value.bsonType} where $type is required") + } else -> // Any other parameter type is an enum whose constants are the upper-cased MQL // values; integration's compile step proves the constant exists. diff --git a/audits/src/main/kotlin/dev/morphia/audits/generate/DslBindings.kt b/audits/src/main/kotlin/dev/morphia/audits/generate/DslBindings.kt index 1b8909ecb7b..c5e8472e12d 100644 --- a/audits/src/main/kotlin/dev/morphia/audits/generate/DslBindings.kt +++ b/audits/src/main/kotlin/dev/morphia/audits/generate/DslBindings.kt @@ -4,12 +4,14 @@ import dev.morphia.audits.api.ApiInventory import dev.morphia.audits.api.DeclarationKind /** - * Where an MQL operator appears: as a pipeline stage, inside an expression, or in a query filter. + * Where an MQL operator appears: as a pipeline stage, inside an expression, in a query filter, or + * as an update operator. */ enum class BindingPosition { STAGE, EXPRESSION, FILTER, + UPDATE, } /** How an operator's BSON value becomes the factory's arguments. */ @@ -38,8 +40,9 @@ enum class BindingForm { */ FILTERS, /** - * A query operator on a field, `{field: {$op: v}}`: the factory takes the field name and, when - * it has a second parameter, `v`. A one-parameter factory (`$exists`) takes only `true`. + * An operator on a field: a query operator, `{field: {$op: v}}`, or an update operator, `{$op: + * {field: v}}`. The factory takes the field name and, when it has a second parameter, `v`. A + * one-parameter query factory (`$exists`) takes only `true`. */ FIELD, /** @@ -144,12 +147,13 @@ object DslBindings { "$label: a sort stage takes no arguments and binds [ascending, descending]" BindingForm.FIELD -> if ( - binding.position != BindingPosition.FILTER || + binding.position !in + setOf(BindingPosition.FILTER, BindingPosition.UPDATE) || binding.parameters.firstOrNull() != "java.lang.String" || binding.parameters.size !in 1..2 ) problems += - "$label: a field filter takes the field name and at most a value" + "$label: a field operator takes the field name and at most a value" } val result = erase(factory.returnType ?: "") (binding.options + binding.fields).forEach { (key, call) -> diff --git a/audits/src/test/kotlin/dev/morphia/audits/offline/GeneratorTest.kt b/audits/src/test/kotlin/dev/morphia/audits/offline/GeneratorTest.kt index d72576a724e..3aedf8f613c 100644 --- a/audits/src/test/kotlin/dev/morphia/audits/offline/GeneratorTest.kt +++ b/audits/src/test/kotlin/dev/morphia/audits/offline/GeneratorTest.kt @@ -180,6 +180,100 @@ class GeneratorTest { assertEquals(inventory, AuditJson.exampleInventory(AuditJson.write(inventory))) } + /** Query and update pages generate find and update cases with the committed bindings. */ + @Test + fun findsAndUpdatesAreGenerated() { + val root = directory.resolve("repository") + write( + root.resolve("audits/catalog/fixture-migration.json"), + AuditJson.write(FixtureMigrationLedger()), + ) + val seed = + block("db.inventory.insertMany( [ { _id: 1, qty: Int32(25), tags: [ \"a\" ] } ] )") + page( + "gt", + "query", + """ + |Examples + |-------- + | + |$seed + |Match Larger Quantities + |~~~~~~~~~~~~~~~~~~~~~~~ + | + |${block("db.inventory.find( { qty: { ${'$'}gt: 20 } } )")} + |Project the Quantity + |~~~~~~~~~~~~~~~~~~~~ + | + |${block("db.inventory.find( { qty: { ${'$'}gt: 20 } }, { qty: 1 } )")}""" + .trimMargin(), + ) + page( + "inc", + "update", + """ + |Examples + |-------- + | + |$seed + |Increment and Tag + |~~~~~~~~~~~~~~~~~ + | + |${block("db.inventory.updateOne( { _id: 1 }, { ${'$'}inc: { qty: 2 }, ${'$'}set: { tags: [ \"b\" ] } } )")} + |Increment in a Pipeline + |~~~~~~~~~~~~~~~~~~~~~~~ + | + |${block("db.inventory.updateOne( { _id: 1 }, [ { ${'$'}set: { qty: 2 } } ] )")}""" + .trimMargin(), + ) + val inventory = + DocumentedExamples.capture( + root, + directory.resolve("pages"), + CurrentPages( + commit = commit, + pages = + listOf("gt", "inc").map { + CurrentPage(FormSource(commit, "$folder/$it.txt")) + }, + ), + ) + val repository = + generateSequence(Path.of("").toAbsolutePath()) { it.parent } + .first { Files.isDirectory(it.resolve("audits/catalog")) } + val generation = + CaseGenerator.generate( + inventory, + AuditJson.dslBindings(Files.readString(repository.resolve(DslBindings.PATH))), + GenerationReview(families = listOf("query/filters", "query/updates")), + emptySet(), + ) + assertEquals( + listOf("query/filters/gt/matchLargerQuantities", "query/updates/inc/incrementAndTag"), + generation.cases.map { it.manifest.name }, + ) + val find = + generation.files.getValue( + "core/src/test/java/dev/morphia/test/generated/filters/TestGt.java" + ) + assertTrue("(query) -> query.filter(gt(\"qty\", 20)));" in find, find) + val update = + generation.files.getValue( + "core/src/test/java/dev/morphia/test/generated/updates/TestInc.java" + ) + val call = + "(query) -> query.filter(eq(\"_id\", 1)),\n inc(\"qty\", 2),\n" + + " set(\"tags\", List.of(\"b\")));" + assertTrue("runner.update(" in update && call in update, update) + assertEquals( + mapOf( + "Project the Quantity" to "a documented projection is not generated yet", + "Increment in a Pipeline" to "/update: a pipeline update has no binding", + ), + generation.gaps.associate { it.title to it.detail }, + ) + } + /** A reviewed name stands in for a generic title; a stale review is counted, not applied. */ @Test fun reviewedNamesResolveGenericTitles() { @@ -572,7 +666,10 @@ class GeneratorTest { assertTrue(catalog.bindings.isNotEmpty()) val review = AuditJson.generationReview(Files.readString(root.resolve(CaseGenerator.REVIEW))) - assertEquals(listOf("aggregation/expressions"), review.families) + assertEquals( + listOf("aggregation/expressions", "query/filters", "query/updates"), + review.families, + ) // The inventory's recorded source text is what generation reads; its digests must hold. val inventory = AuditJson.exampleInventory(Files.readString(root.resolve(DocumentedExamples.PATH))) diff --git a/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java b/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java index 6db88e3b6da..1ca2ff27f79 100644 --- a/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java +++ b/core/src/test/java/dev/morphia/test/OperatorCaseRunner.java @@ -94,6 +94,13 @@ public void aggregate(OperatorCase operatorCase, Function, */ public void find(OperatorCase operatorCase, ActionTestOptions options, Function, Query> dsl) { options(operatorCase, options); + find(operatorCase, dsl); + } + + /** + * Runs a query case: the documented filter runs through the driver, and Morphia's query as {@code dsl} builds it. + */ + public void find(OperatorCase operatorCase, Function, Query> dsl) { run(operatorCase, "find", Shape.FIND, (action, collection) -> { Query query = dsl.apply(test.getDs().find(Document.class, new FindOptions().collection(collection)) .disableValidation()); @@ -116,6 +123,14 @@ public void find(OperatorCase operatorCase, ActionTestOptions options, Function< public void update(OperatorCase operatorCase, ActionTestOptions options, Function, Query> dsl, UpdateOperator... operators) { options(operatorCase, options); + update(operatorCase, dsl, operators); + } + + /** + * Runs an update case: the results are the documents its filter matches after the update, and every collection is + * compared as well. + */ + public void update(OperatorCase operatorCase, Function, Query> dsl, UpdateOperator... operators) { run(operatorCase, "update", Shape.UPDATE, (action, collection) -> { Query query = dsl.apply(test.getDs().find(collection, Document.class).disableValidation()); Document updates = new Operations(test.getDs(), null, List.of(operators), false).toDocument(test.getDs()); diff --git a/core/src/test/java/dev/morphia/test/generated/filters/TestIn.java b/core/src/test/java/dev/morphia/test/generated/filters/TestIn.java new file mode 100644 index 00000000000..d9911994ced --- /dev/null +++ b/core/src/test/java/dev/morphia/test/generated/filters/TestIn.java @@ -0,0 +1,29 @@ +// spotless:off +package dev.morphia.test.generated.filters; + +import java.util.List; + +import dev.morphia.test.OperatorCase; +import dev.morphia.test.OperatorCaseRunner; +import dev.morphia.test.TestBase; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static dev.morphia.query.filters.Filters.in; +import static dev.morphia.query.updates.UpdateOperators.set; + +/** Generated by GenerateMainKt from audits/catalog/documented-examples.json; do not edit. */ +public class TestIn extends TestBase { + private final OperatorCaseRunner runner = new OperatorCaseRunner(this); + + @Test + @DisplayName("Match Values in an Array") + public void matchValuesInAnArray() { + runner.update( + OperatorCase.of("/dev/morphia/test/generated/fixtures/filters/in/matchValuesInAnArray/scenario.json"), + (query) -> query.filter(in("rated", List.of("G", "TV-G"))), + set("familyFriendly", true)); + } +} +// spotless:on diff --git a/core/src/test/java/dev/morphia/test/generated/updates/TestPositionalAll.java b/core/src/test/java/dev/morphia/test/generated/updates/TestPositionalAll.java new file mode 100644 index 00000000000..0f8feb2fdf5 --- /dev/null +++ b/core/src/test/java/dev/morphia/test/generated/updates/TestPositionalAll.java @@ -0,0 +1,26 @@ +// spotless:off +package dev.morphia.test.generated.updates; + +import dev.morphia.test.OperatorCase; +import dev.morphia.test.OperatorCaseRunner; +import dev.morphia.test.TestBase; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static dev.morphia.query.updates.UpdateOperators.inc; + +/** Generated by GenerateMainKt from audits/catalog/documented-examples.json; do not edit. */ +public class TestPositionalAll extends TestBase { + private final OperatorCaseRunner runner = new OperatorCaseRunner(this); + + @Test + @DisplayName("Update All Elements in an Array") + public void updateAllElementsInAnArray() { + runner.update( + OperatorCase.of("/dev/morphia/test/generated/fixtures/updates/positional-all/updateAllElementsInAnArray/scenario.json"), + (query) -> query, + inc("grades.$[]", 10)); + } +} +// spotless:on diff --git a/core/src/test/resources/dev/morphia/test/generated/fixtures/filters/in/matchValuesInAnArray/scenario.json b/core/src/test/resources/dev/morphia/test/generated/fixtures/filters/in/matchValuesInAnArray/scenario.json new file mode 100644 index 00000000000..72f4a3993d3 --- /dev/null +++ b/core/src/test/resources/dev/morphia/test/generated/fixtures/filters/in/matchValuesInAnArray/scenario.json @@ -0,0 +1,92 @@ +{ + "schemaVersion": { + "$numberInt": "1" + }, + "name": "query/filters/in/matchValuesInAnArray", + "title": "Match Values in an Array", + "context": "FILTER", + "source": { + "repository": "mongodb/docs", + "commit": "e4b0c153a0f39829bb1c2e5195beee1e92a8eff7", + "path": "content/manual/manual/source/reference/operator/query/in.txt", + "blob": "bac31808d1910fe9947955e65d193b3035f2e718" + }, + "dataset": "sample_mflix", + "collections": {}, + "indexes": [], + "action": { + "kind": "update", + "collection": "movies", + "filter": { + "rated": { + "$in": [ + "G", + "TV-G" + ] + } + }, + "update": { + "$set": { + "familyFriendly": true + } + }, + "multi": true + }, + "expected": { + "printed": [ + { + "document": [ + { + "name": "acknowledged", + "value": { + "exact": true + } + }, + { + "name": "insertedId", + "value": { + "exact": null + } + }, + { + "name": "matchedCount", + "value": { + "whole": { + "$numberInt": "536" + } + } + }, + { + "name": "modifiedCount", + "value": { + "whole": { + "$numberInt": "536" + } + } + }, + { + "name": "upsertedCount", + "value": { + "whole": { + "$numberInt": "0" + } + } + } + ] + } + ] + }, + "comparison": { + "order": "ORDERED", + "rules": [], + "ignore": [], + "tolerance": null + }, + "requirements": { + "minimumServer": null, + "topology": "STANDALONE" + }, + "skipped": { + "results": "the example queries the sample_mflix sample dataset, which the tests do not load" + } +} diff --git a/core/src/test/resources/dev/morphia/test/generated/fixtures/updates/positional-all/updateAllElementsInAnArray/scenario.json b/core/src/test/resources/dev/morphia/test/generated/fixtures/updates/positional-all/updateAllElementsInAnArray/scenario.json new file mode 100644 index 00000000000..c2cbdcc4458 --- /dev/null +++ b/core/src/test/resources/dev/morphia/test/generated/fixtures/updates/positional-all/updateAllElementsInAnArray/scenario.json @@ -0,0 +1,197 @@ +{ + "schemaVersion": { + "$numberInt": "1" + }, + "name": "query/updates/positional-all/updateAllElementsInAnArray", + "title": "Update All Elements in an Array", + "context": "UPDATE", + "source": { + "repository": "mongodb/docs", + "commit": "e4b0c153a0f39829bb1c2e5195beee1e92a8eff7", + "path": "content/manual/manual/source/reference/operator/update/positional-all.txt", + "blob": "2132adf02cce83c6e597ccf578bc2990525a5c6e" + }, + "dataset": null, + "collections": { + "students": [ + { + "_id": { + "$numberInt": "1" + }, + "grades": [ + { + "$numberInt": "85" + }, + { + "$numberInt": "82" + }, + { + "$numberInt": "80" + } + ] + }, + { + "_id": { + "$numberInt": "2" + }, + "grades": [ + { + "$numberInt": "88" + }, + { + "$numberInt": "90" + }, + { + "$numberInt": "92" + } + ] + }, + { + "_id": { + "$numberInt": "3" + }, + "grades": [ + { + "$numberInt": "85" + }, + { + "$numberInt": "100" + }, + { + "$numberInt": "90" + } + ] + } + ] + }, + "indexes": [], + "action": { + "kind": "update", + "collection": "students", + "filter": {}, + "update": { + "$inc": { + "grades.$[]": { + "$numberInt": "10" + } + } + }, + "multi": true + }, + "expected": { + "printed": [ + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "1" + } + } + }, + { + "name": "grades", + "value": { + "array": [ + { + "whole": { + "$numberInt": "95" + } + }, + { + "whole": { + "$numberInt": "92" + } + }, + { + "whole": { + "$numberInt": "90" + } + } + ] + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "2" + } + } + }, + { + "name": "grades", + "value": { + "array": [ + { + "whole": { + "$numberInt": "98" + } + }, + { + "whole": { + "$numberInt": "100" + } + }, + { + "whole": { + "$numberInt": "102" + } + } + ] + } + } + ] + }, + { + "document": [ + { + "name": "_id", + "value": { + "whole": { + "$numberInt": "3" + } + } + }, + { + "name": "grades", + "value": { + "array": [ + { + "whole": { + "$numberInt": "95" + } + }, + { + "whole": { + "$numberInt": "110" + } + }, + { + "whole": { + "$numberInt": "100" + } + } + ] + } + } + ] + } + ] + }, + "comparison": { + "order": "ORDERED", + "rules": [], + "ignore": [], + "tolerance": null + }, + "requirements": { + "minimumServer": null, + "topology": "STANDALONE" + } +} diff --git a/core/src/test/resources/dev/morphia/test/generated/manifest.json b/core/src/test/resources/dev/morphia/test/generated/manifest.json index 755fc14bf4f..6da4bbe532a 100644 --- a/core/src/test/resources/dev/morphia/test/generated/manifest.json +++ b/core/src/test/resources/dev/morphia/test/generated/manifest.json @@ -1619,6 +1619,11 @@ "name" : "query/filters/gte/performAnUpdateBasedOnEmbeddedDocumentFields", "scenario" : "/dev/morphia/test/query/filters/gte/performAnUpdateBasedOnEmbeddedDocumentFields/scenario.json", "test" : "dev.morphia.test.query.filters.TestGte#testPerformAnUpdateBasedOnEmbeddedDocumentFields" + }, { + "kind" : "GENERATED", + "name" : "query/filters/in/matchValuesInAnArray", + "scenario" : "/dev/morphia/test/generated/fixtures/filters/in/matchValuesInAnArray/scenario.json", + "test" : "dev.morphia.test.generated.filters.TestIn#matchValuesInAnArray" }, { "kind" : "CONVERTED", "name" : "query/filters/in/useTheInOperatorToMatchValuesInAnArray", @@ -1764,6 +1769,11 @@ "name" : "query/updates/position/useANegativeArrayIndexPositionToAddElementsToTheArray", "scenario" : "/dev/morphia/test/query/updates/position/useANegativeArrayIndexPositionToAddElementsToTheArray/scenario.json", "test" : "dev.morphia.test.query.updates.TestPosition#testUseANegativeArrayIndexPositionToAddElementsToTheArray" + }, { + "kind" : "GENERATED", + "name" : "query/updates/positional-all/updateAllElementsInAnArray", + "scenario" : "/dev/morphia/test/generated/fixtures/updates/positional-all/updateAllElementsInAnArray/scenario.json", + "test" : "dev.morphia.test.generated.updates.TestPositionalAll#updateAllElementsInAnArray" }, { "kind" : "CONVERTED", "name" : "query/updates/positional/updateEmbeddedDocumentsUsingMultipleFieldMatches", @@ -1915,6 +1925,14 @@ "owner" : "GENERATED", "path" : "src/test/java/dev/morphia/test/generated/expressions/TestTopN.java", "sha256" : "60d9727f2c4e2891bfed4f4689c7853e9248d56ab24b06ad3ab982ac17d92e9c" + }, { + "owner" : "GENERATED", + "path" : "src/test/java/dev/morphia/test/generated/filters/TestIn.java", + "sha256" : "4488d2132039c96a001b74dbcd0239737633aa411d805159fbbf5c0f7d5bbaea" + }, { + "owner" : "GENERATED", + "path" : "src/test/java/dev/morphia/test/generated/updates/TestPositionalAll.java", + "sha256" : "1f15f53398639623ff92a2275b197f99359ef1fb9c68b12ad2a90d0ad11bb4aa" }, { "owner" : "GENERATED", "path" : "src/test/resources/dev/morphia/test/aggregation/expressions/abs/absExpressionOperator/scenario.json", @@ -3087,6 +3105,10 @@ "owner" : "GENERATED", "path" : "src/test/resources/dev/morphia/test/generated/fixtures/expressions/topN/findTheThreeHighestRatedMoviesInASingleGenre/scenario.json", "sha256" : "c00273bdf10a7ad0ba29a9e4f603963c802b0be41588284f15a273a45343d6ba" + }, { + "owner" : "GENERATED", + "path" : "src/test/resources/dev/morphia/test/generated/fixtures/filters/in/matchValuesInAnArray/scenario.json", + "sha256" : "4a83c4febc4e907c0d2cd33830e5ebb27b2c03b1ffac2d742ca106c5102697b6" }, { "owner" : "PROTECTED", "path" : "src/test/resources/dev/morphia/test/generated/fixtures/runner/crossDatabase/scenario.json", @@ -3095,6 +3117,10 @@ "owner" : "PROTECTED", "path" : "src/test/resources/dev/morphia/test/generated/fixtures/runner/printedMismatch/scenario.json", "sha256" : "ccdec466a95e3325eecd8997cb852a14de71a815c6f6c5e4cd5b77332aab5296" + }, { + "owner" : "GENERATED", + "path" : "src/test/resources/dev/morphia/test/generated/fixtures/updates/positional-all/updateAllElementsInAnArray/scenario.json", + "sha256" : "1c36e64e5a860d392f99d2a786c8ab8098a51fe441001282f512845d8dfd668a" }, { "owner" : "PROTECTED", "path" : "src/test/resources/dev/morphia/test/generated/vectors/printed.json", diff --git a/design/operator-audits-design.md b/design/operator-audits-design.md index cd50f34f373..e63d4ef2fe6 100644 --- a/design/operator-audits-design.md +++ b/design/operator-audits-design.md @@ -247,17 +247,20 @@ a test method: expression or a query filter, to a Morphia factory by its exact erased signature, with the form its BSON takes: - `POSITIONAL` and `NAMED` for operators, `PROJECTION`, `FIELDS`, `GROUP` and `SORT` for those - stages, `FILTERS` for `$match`, and `FIELD` for a query operator on a field; + stages, `FILTERS` for `$match`, and `FIELD` for a query or update operator on a field; - the `[]` entry binds an array literal (`ArrayExpressions.array`). The API inventory of core's current source must contain every one; a stale binding stops generation. 2. **Lower the source.** `FormMigration.documented` turns the example's mongosh blocks into typed seed data, an action and expected results, through `ShellPrograms`. -3. **Emit the call.** The emitter walks the pipeline. Every stage and operator node needs a binding, - and every value is emitted only in a form its parameter type accepts: an array as `List.of` for - an `Iterable`, a sort document as `Sort` varargs. The first node without a binding makes the - example a gap. +3. **Emit the call.** The emitter walks the action: a pipeline becomes `runner.aggregate`, a find + `runner.find` with the filter's `Filters` calls, and an update `runner.update` with the filter and + one `UpdateOperators` call per field. Every node needs a binding, and every value is emitted only + in a form its parameter type accepts: a sort document as `Sort` varargs, and an array as `List.of` + where it is data (a query or update operand, an `Iterable`) or as `array(...)` where it is an + expression. The first node without a binding makes the example a gap; so does a documented + projection or a pipeline update. 4. **Write the scenario.** `FixtureMigration.scenario` writes it in the same format a converted case uses, ordered. Its form rules are those the emitted spelling needs: `EQ_SHORTHAND` when a plain value became `eq()`, `FIELD_OPERATORS_AND` when one field's operators became one filter @@ -279,9 +282,9 @@ Examples that are not generated are listed in `gaps.json`, each with its reason: | `EXCLUDED` | A reviewed exclusion. | Its reason says what would lift it. | | `PROTECTED_CLASS` | The operator's class holds a moved handwritten body. | Move the body or the case. | -Only the aggregation expressions family is generated today, its pipelines using the bound stages. -Stage pages, queries and updates need more bindings and generator support for find and update -actions. +The aggregation expressions, query filters and query updates families are generated today. Stage +pages need their family enabled and more bindings; documented projections and update options +(`arrayFilters`) need generator and runner support. ### Candidates, integration and promotion diff --git a/design/operator-audits-progress.md b/design/operator-audits-progress.md index 29b22ba58d1..72840546985 100644 --- a/design/operator-audits-progress.md +++ b/design/operator-audits-progress.md @@ -18,7 +18,7 @@ how the audits work updates it too; this file records what each PR delivered. Every step of the plan (0–7) has been started. What stands: -- **On the runner:** 363 legacy cases (362 converted, 1 migrated), plus 12 generated cases. +- **On the runner:** 363 legacy cases (362 converted, 1 migrated), plus 14 generated cases. Core gate: 662 tests under each mapper; audits: 452. - **Generation:** inventory of mongodb/docs `e4b0c153` (297 pages read, tested snippets included; 437 examples owned, 145 unowned, none unnamed or ambiguous after review), reviewed DSL bindings checked against core's API, and the @@ -44,13 +44,14 @@ Step 5, generation and cutover: - **Bindings for the remaining gaps** the weekly job files as issues (today `$serializeEJSON`, `$deserializeEJSON`, `$toObject`, `$toArray`, `$hexHash`, `$percentile`, `$limit`, `$type`, a compound `$group` `_id`, `$convert` options, `$reduce` `valueAs`). -- **Find and update generation.** Only aggregation pipelines are generated. - **The remaining legacy fixtures:** 193 directories. - 98 are locked; 96 are unresolved in `form-review.json`. - 23 are legacy-only in `cutover.json`. - 69 never-locked fixtures have no pinned reference. -- **Deferred cutover features:** documented projections (`findOptions`), indexes, alternative - commands. +- **Deferred cutover features:** documented projections (`findOptions`), update options + (`arrayFilters`, `upsert`), update results as the page reads them (the whole collection, not + the filter's matches), indexes, alternative commands. +- **The stage pages' family** (41 unowned examples, most on sample datasets). Step 6, monitoring: - **An accepted production baseline for capability discovery.** It is needed before @@ -2641,3 +2642,18 @@ no product-documentation changes. Legacy operator AsciiDoc tables are intentiona `$maxN` as `{input, n}`). - One more generated case (`maxN-array-element`, "Find the Top Two Cast Members"); 12 in all. Core: 690 tests under each mapper; audits: 457. + +## Find and update generation (2026-11-23) + +- Branch audits-find-update. The `query/filters` and `query/updates` families are generated: a find + becomes `runner.find(case, query -> query.filter(...))`, an update + `runner.update(case, query -> query.filter(...), set(...), inc(...))`. The runner gained those + option-free overloads; the legacy ones check their options, then delegate. +- New `UPDATE` binding position (form `FIELD`): `$set`, `$inc`, `$mul`, `$max`, `$min`, `$unset`, + `$rename`, `$addToSet`, `$push`, `$pull`, `$pullAll`. `Number` and `List` parameters take literals; + query and update operands are data, so their arrays are `List.of`, not `array(...)`. +- Two cases generated (`$in` "Match Values in an Array", `$[]` "Update All Elements in an Array"); + 14 in all. `$[]`'s negation example is excluded: the page prints the whole collection after the + update, while the runner's update results are the filter's matches. Most query and update gaps + are documented projections (5) and `arrayFilters` update options (5). +- Core: 692 tests under each mapper; audits: 458.