From be40fd1c7603174deef9787e107982ac12bf5976 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Piaggio?= Date: Mon, 16 Nov 2026 20:34:32 -0300 Subject: [PATCH 1/2] multi-type query generation --- README.md | 7 +- .../scala/clue/annotation/GraphQLType.scala | 7 +- .../scala/clue/GraphQLInterpolatorSuite.scala | 3 +- .../graphql/schemas/StarWars.graphql | 8 +- .../scala/test/StarWarsHumanSubquery.scala | 3 +- .../scala/test/StarWarsNestedSubquery.scala | 3 +- .../main/scala/test/StarWarsSubquery.scala | 3 +- .../test/StarWarsSubqueryInferVariable.scala | 3 +- .../StarWarsSubqueryMultiTypeGenerated.scala | 10 +- .../StarWarsSubqueryMultiTypeInvalid.scala | 22 +++ .../StarWarsSubqueryMultiTypeMismatch.scala | 22 +++ ...arsSubqueryMultiTypeVariableMismatch.scala | 22 +++ ...rWarsTypedSubqueryMultiTypeAnnotated.scala | 23 +++ .../StarWarsSubqueryMultiTypeGenerated.scala | 34 ++++ ...rWarsTypedSubqueryMultiTypeAnnotated.scala | 16 ++ .../src/main/scala/clue/gen/GraphQLGen.scala | 153 +++++++++++------- .../scala/clue/gen/GraphQLValidation.scala | 40 +++-- .../src/main/scala/clue/gen/QueryGen.scala | 58 ++++--- 18 files changed, 323 insertions(+), 114 deletions(-) create mode 100644 gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeInvalid.scala create mode 100644 gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeMismatch.scala create mode 100644 gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeVariableMismatch.scala create mode 100644 gen/input/src/main/scala/test/StarWarsTypedSubqueryMultiTypeAnnotated.scala create mode 100644 gen/output/src/main/scala/test/StarWarsSubqueryMultiTypeGenerated.scala create mode 100644 gen/output/src/main/scala/test/StarWarsTypedSubqueryMultiTypeAnnotated.scala diff --git a/README.md b/README.md index d1ee4aaf..447fd451 100644 --- a/README.md +++ b/README.md @@ -132,9 +132,10 @@ abstract class FriendFields extends GraphQLSubquery.Typed[StarWars, Json] { A subquery's `subquery` is a `GraphQLDocument` too, so it is built with `gql` for the same reason a `document` is (see [Subquery variables](#subquery-variables)). -Hand-written subqueries may declare **multiple** types (the selection is validated against each: -`@GraphQLType("Human", "Droid")`). A subquery processed by the generator (`@GraphQL`) must declare -**exactly one** type. `@GraphQLType` is only valid on a subquery, not on a `GraphQLOperation`. +A subquery may declare **multiple** types (the selection is validated against each: +`@GraphQLType("Human", "Droid")`). For a subquery processed by the generator (`@GraphQL`), the +selected fields must also have the same types in every declared type, since a single `Data` is +generated from them. `@GraphQLType` is only valid on a subquery, not on a `GraphQLOperation`. #### Interfaces and unions diff --git a/core/src/main/scala/clue/annotation/GraphQLType.scala b/core/src/main/scala/clue/annotation/GraphQLType.scala index b366d82f..28c3af0b 100644 --- a/core/src/main/scala/clue/annotation/GraphQLType.scala +++ b/core/src/main/scala/clue/annotation/GraphQLType.scala @@ -7,8 +7,9 @@ import scala.annotation.StaticAnnotation /** * Declares the GraphQL root type(s) a `GraphQLSubquery`'s selection set applies to, so it can be - * validated against the schema. Multiple types are allowed for hand-written subqueries (the - * selection is validated against each); a subquery processed by the generator (`@GraphQL`) must - * declare exactly one. Not valid on a `GraphQLOperation`. + * validated against the schema. When multiple types are declared, the selection is validated + * against each. For a subquery processed by the generator (`@GraphQL`), the selected fields must + * also have the same types in every declared type, since a single `Data` is generated. Not valid on + * a `GraphQLOperation`. */ class GraphQLType(types: String*) extends StaticAnnotation diff --git a/core/src/test/scala/clue/GraphQLInterpolatorSuite.scala b/core/src/test/scala/clue/GraphQLInterpolatorSuite.scala index 968a464f..5f618e51 100644 --- a/core/src/test/scala/clue/GraphQLInterpolatorSuite.scala +++ b/core/src/test/scala/clue/GraphQLInterpolatorSuite.scala @@ -3,6 +3,7 @@ package clue +import clue.annotation.GraphQLStub import io.circe.Json // A subquery declaring a required variable, used to exercise the `gql` caller-check. @@ -38,7 +39,7 @@ object InterpolatorTestSubList extends GraphQLSubquery.Typed[Unit, Json] { // A pre-generation `@GraphQLStub` placeholder (no `GraphQLSubquery` supertype), as the generator // leaves it before the scalafix rule replaces it with a real subquery. Exercises that the macro // tolerates splicing it. -@clue.annotation.GraphQLStub +@GraphQLStub object InterpolatorTestStub class GraphQLInterpolatorSuite extends munit.FunSuite { diff --git a/gen/input/src/main/resources/graphql/schemas/StarWars.graphql b/gen/input/src/main/resources/graphql/schemas/StarWars.graphql index 063b6339..1f1be37d 100644 --- a/gen/input/src/main/resources/graphql/schemas/StarWars.graphql +++ b/gen/input/src/main/resources/graphql/schemas/StarWars.graphql @@ -41,4 +41,10 @@ type Droid implements Character { appearsIn: [Episode!] functions: [String!] primaryFunction: String @deprecated(reason: "Use 'functions' instead") -} \ No newline at end of file +} + +type Starship { + id: String! + name: String! + hero(episode: Episode): Character +} diff --git a/gen/input/src/main/scala/test/StarWarsHumanSubquery.scala b/gen/input/src/main/scala/test/StarWarsHumanSubquery.scala index c555f652..6f16301f 100644 --- a/gen/input/src/main/scala/test/StarWarsHumanSubquery.scala +++ b/gen/input/src/main/scala/test/StarWarsHumanSubquery.scala @@ -10,6 +10,7 @@ package test import clue.GraphQLSubquery import clue.annotation.GraphQL +import clue.annotation.GraphQLStub import clue.annotation.GraphQLType @GraphQL @@ -23,6 +24,6 @@ abstract class StarWarsHumanSubquery extends GraphQLSubquery[StarWars] { """ } -@clue.annotation.GraphQLStub +@GraphQLStub object StarWarsHumanSubquery // format: on diff --git a/gen/input/src/main/scala/test/StarWarsNestedSubquery.scala b/gen/input/src/main/scala/test/StarWarsNestedSubquery.scala index f7878539..28a2ee56 100644 --- a/gen/input/src/main/scala/test/StarWarsNestedSubquery.scala +++ b/gen/input/src/main/scala/test/StarWarsNestedSubquery.scala @@ -10,6 +10,7 @@ package test import clue.GraphQLSubquery import clue.annotation.GraphQL +import clue.annotation.GraphQLStub import clue.annotation.GraphQLType @GraphQL // assert: GraphQLGen @@ -32,6 +33,6 @@ abstract class StarWarsNestedSubquery extends GraphQLSubquery[StarWars] { """ } -@clue.annotation.GraphQLStub +@GraphQLStub object StarWarsNestedSubquery // format: on diff --git a/gen/input/src/main/scala/test/StarWarsSubquery.scala b/gen/input/src/main/scala/test/StarWarsSubquery.scala index 44cde1ac..18079fe1 100644 --- a/gen/input/src/main/scala/test/StarWarsSubquery.scala +++ b/gen/input/src/main/scala/test/StarWarsSubquery.scala @@ -10,6 +10,7 @@ package test import clue.GraphQLSubquery import clue.annotation.GraphQL +import clue.annotation.GraphQLStub import clue.annotation.GraphQLType @GraphQL @@ -23,6 +24,6 @@ abstract class StarWarsSubquery extends GraphQLSubquery[StarWars] { """ } -@clue.annotation.GraphQLStub +@GraphQLStub object StarWarsSubquery // format: on diff --git a/gen/input/src/main/scala/test/StarWarsSubqueryInferVariable.scala b/gen/input/src/main/scala/test/StarWarsSubqueryInferVariable.scala index e0ddd904..fea535ee 100644 --- a/gen/input/src/main/scala/test/StarWarsSubqueryInferVariable.scala +++ b/gen/input/src/main/scala/test/StarWarsSubqueryInferVariable.scala @@ -10,6 +10,7 @@ package test import clue.GraphQLSubquery import clue.annotation.GraphQL +import clue.annotation.GraphQLStub import clue.annotation.GraphQLType // A generated subquery that references `$ep` without declaring it: the generator infers the variable @@ -20,6 +21,6 @@ abstract class StarWarsSubqueryInferVariable extends GraphQLSubquery[StarWars] { override val subquery = gql"{ hero(episode: $$ep) { name } }" } -@clue.annotation.GraphQLStub +@GraphQLStub object StarWarsSubqueryInferVariable // format: on diff --git a/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeGenerated.scala b/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeGenerated.scala index 86bba5dd..2546a35a 100644 --- a/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeGenerated.scala +++ b/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeGenerated.scala @@ -10,13 +10,17 @@ package test import clue.GraphQLSubquery import clue.annotation.GraphQL +import clue.annotation.GraphQLStub import clue.annotation.GraphQLType -// A subquery processed by the generator (`@GraphQL`) must declare exactly one `@GraphQLType`, since -// generation targets a single type. Multiple types here is an error (and nothing is generated). -@GraphQL // assert: GraphQLGen +// A subquery processed by the generator (`@GraphQL`) declaring multiple root types. `id` and `name` +// have the same types on `Human` and `Droid`, so a single `Data` is generated for both. +@GraphQL @GraphQLType("Human", "Droid") abstract class StarWarsSubqueryMultiTypeGenerated extends GraphQLSubquery[StarWars] { override val subquery = gql"{ id name }" } + +@GraphQLStub +object StarWarsSubqueryMultiTypeGenerated // format: on diff --git a/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeInvalid.scala b/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeInvalid.scala new file mode 100644 index 00000000..75d32310 --- /dev/null +++ b/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeInvalid.scala @@ -0,0 +1,22 @@ +// Copyright (c) 2016-2026 Association of Universities for Research in Astronomy, Inc. (AURA) +// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause + +// format: off +/* + rules = [GraphQLGen] + Clue.schemaDirs = ["gen/input/src/main/resources/graphql/schemas"] + */ +package test + +import clue.GraphQLSubquery +import clue.annotation.GraphQL +import clue.annotation.GraphQLType + +// `homePlanet` exists on `Human` but not on `Droid`: a generated subquery is validated against +// every declared type too, so it must be reported for `Droid` (and nothing is generated). +@GraphQL +@GraphQLType("Human", "Droid") +abstract class StarWarsSubqueryMultiTypeInvalid extends GraphQLSubquery[StarWars] { + override val subquery = gql"{ id homePlanet }" // assert: GraphQLGen +} +// format: on diff --git a/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeMismatch.scala b/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeMismatch.scala new file mode 100644 index 00000000..a0b9d204 --- /dev/null +++ b/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeMismatch.scala @@ -0,0 +1,22 @@ +// Copyright (c) 2016-2026 Association of Universities for Research in Astronomy, Inc. (AURA) +// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause + +// format: off +/* + rules = [GraphQLGen] + Clue.schemaDirs = ["gen/input/src/main/resources/graphql/schemas"] + */ +package test + +import clue.GraphQLSubquery +import clue.annotation.GraphQL +import clue.annotation.GraphQLType + +// `name` is nullable on `Human` but not on `Starship`, so the two root types would generate a +// different `Data`. Since a single one is emitted, this is an error (and nothing is generated). +@GraphQL // assert: GraphQLGen +@GraphQLType("Human", "Starship") +abstract class StarWarsSubqueryMultiTypeMismatch extends GraphQLSubquery[StarWars] { + override val subquery = gql"{ id name }" +} +// format: on diff --git a/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeVariableMismatch.scala b/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeVariableMismatch.scala new file mode 100644 index 00000000..8c6aeb05 --- /dev/null +++ b/gen/input/src/main/scala/test/StarWarsSubqueryMultiTypeVariableMismatch.scala @@ -0,0 +1,22 @@ +// Copyright (c) 2016-2026 Association of Universities for Research in Astronomy, Inc. (AURA) +// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause + +// format: off +/* + rules = [GraphQLGen] + Clue.schemaDirs = ["gen/input/src/main/resources/graphql/schemas"] + */ +package test + +import clue.GraphQLSubquery +import clue.annotation.GraphQL +import clue.annotation.GraphQLType + +// `$ep` is inferred as `Episode!` from `Query.hero` but as `Episode` from `Starship.hero`. A single +// `type VariableDefs` is emitted, so the variables must be declared explicitly instead. +@GraphQL +@GraphQLType("Query", "Starship") +abstract class StarWarsSubqueryMultiTypeVariableMismatch extends GraphQLSubquery[StarWars] { + override val subquery = gql"{ hero(episode: $$ep) { name } }" // assert: GraphQLGen +} +// format: on diff --git a/gen/input/src/main/scala/test/StarWarsTypedSubqueryMultiTypeAnnotated.scala b/gen/input/src/main/scala/test/StarWarsTypedSubqueryMultiTypeAnnotated.scala new file mode 100644 index 00000000..f8c3c6cd --- /dev/null +++ b/gen/input/src/main/scala/test/StarWarsTypedSubqueryMultiTypeAnnotated.scala @@ -0,0 +1,23 @@ +// Copyright (c) 2016-2026 Association of Universities for Research in Astronomy, Inc. (AURA) +// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause + +// format: off +/* + rules = [GraphQLGen] + Clue.schemaDirs = ["gen/input/src/main/resources/graphql/schemas"] + */ +package test + +import clue.GraphQLSubquery +import clue.annotation.GraphQL +import clue.annotation.GraphQLType +import io.circe.Json + +// An annotated subquery that supplies its own `Data` and declares multiple root types: there is +// nothing to generate, so it is validated against each type and copied without `@GraphQL`. +@GraphQL +@GraphQLType("Human", "Droid") +object StarWarsTypedSubqueryMultiTypeAnnotated extends GraphQLSubquery.Typed[StarWars, Json] { + override val subquery = gql"{ id name }" +} +// format: on diff --git a/gen/output/src/main/scala/test/StarWarsSubqueryMultiTypeGenerated.scala b/gen/output/src/main/scala/test/StarWarsSubqueryMultiTypeGenerated.scala new file mode 100644 index 00000000..4cb2157a --- /dev/null +++ b/gen/output/src/main/scala/test/StarWarsSubqueryMultiTypeGenerated.scala @@ -0,0 +1,34 @@ +// Copyright (c) 2016-2026 Association of Universities for Research in Astronomy, Inc. (AURA) +// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause + +// format: off + +package test + +import clue.GraphQLSubquery +import clue.annotation.GraphQLType + +// A subquery processed by the generator (`@GraphQL`) declaring multiple root types. `id` and `name` +// have the same types on `Human` and `Droid`, so a single `Data` is generated for both. + +@GraphQLType("Human", "Droid") object StarWarsSubqueryMultiTypeGenerated extends GraphQLSubquery[StarWars] { + import StarWars.Scalars._ + ignoreUnusedImportScalars() + import StarWars.Enums._ + ignoreUnusedImportEnums() + import StarWars.Types._ + ignoreUnusedImportTypes() + override val subquery = gql"{ id name }" + case class Data(val id: String, val name: Option[String] = None) + object Data { + val id: monocle.Lens[Data, String] = monocle.macros.GenLens[Data](_.id) + val name: monocle.Lens[Data, Option[String]] = monocle.macros.GenLens[Data](_.name) + implicit val eqData: cats.Eq[Data] = cats.Eq.fromUniversalEquals + implicit val showData: cats.Show[Data] = cats.Show.fromToString + implicit val jsonDecoderData: io.circe.Decoder[Data] = io.circe.generic.semiauto.deriveDecoder[Data] + } + val dataDecoder: io.circe.Decoder[Data] = Data.jsonDecoderData +} + + +// format: on diff --git a/gen/output/src/main/scala/test/StarWarsTypedSubqueryMultiTypeAnnotated.scala b/gen/output/src/main/scala/test/StarWarsTypedSubqueryMultiTypeAnnotated.scala new file mode 100644 index 00000000..646ca133 --- /dev/null +++ b/gen/output/src/main/scala/test/StarWarsTypedSubqueryMultiTypeAnnotated.scala @@ -0,0 +1,16 @@ +// Copyright (c) 2016-2026 Association of Universities for Research in Astronomy, Inc. (AURA) +// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause + +// format: off + +package test + +import clue.GraphQLSubquery +import clue.annotation.GraphQLType +import io.circe.Json + +// An annotated subquery that supplies its own `Data` and declares multiple root types: there is +// nothing to generate, so it is validated against each type and copied without `@GraphQL`. + +@GraphQLType("Human", "Droid") object StarWarsTypedSubqueryMultiTypeAnnotated extends GraphQLSubquery.Typed[StarWars, Json] { override val subquery = gql"{ id name }" } +// format: on diff --git a/gen/rules/src/main/scala/clue/gen/GraphQLGen.scala b/gen/rules/src/main/scala/clue/gen/GraphQLGen.scala index abe5ea87..6c6a821a 100644 --- a/gen/rules/src/main/scala/clue/gen/GraphQLGen.scala +++ b/gen/rules/src/main/scala/clue/gen/GraphQLGen.scala @@ -35,6 +35,31 @@ class GraphQLGen(val config: GraphQLGenConfig) newLineIndent + lines.replaceAll("\\n", newLineIndent) } + // A generated subquery with several root types emits a single object, so the definitions + // generated from each of them (one entry per root type) must be the same. Reports the first + // difference found, if any. + private def generatedMismatch(bodies: List[(String, List[Stat])]): Option[String] = { + def lines(body: List[Stat]): List[String] = + body.flatMap(_.syntax.linesIterator.map(_.trim).toList) + + bodies match { + case (firstType, firstBody) :: rest => + val firstLines: List[String] = lines(firstBody) + rest.collectFirst { + case (otherType, otherBody) if lines(otherBody) != firstLines => + val (first, other): (String, String) = + firstLines + .zipAll(lines(otherBody), "", "") + .find { case (a, b) => a != b } + .getOrElse(("", "")) + s"The subquery generates different definitions for its root types [$firstType] " + + s"(`$first`) and [$otherType] (`$other`). The fields it selects must have the same " + + "types in every root type." + } + case Nil => none + } + } + override def fix(implicit doc: SemanticDocument): Patch = { val importPatch: List[IO[Patch]] = doc.tokens.collect { @@ -72,17 +97,22 @@ class GraphQLGen(val config: GraphQLGenConfig) extractSubquery(stats), extractRootTypes(mods) ) match { - case (Some(schemaType), Some(subquery), rootTypeName :: Nil) - if extractVariableDefs(stats).isEmpty => + case (Some(schemaType), Some(subquery), rootTypes) + if rootTypes.nonEmpty && extractVariableDefs(stats).isEmpty => config .getSchema(schemaType.value) .map( - _.toOption.fold(stats)(schema => - addVariableDefsTypeAlias( - none, - inferSubqueryVariableDefs(schema, rootTypeName, subquery.render) - )(stats) - ) + _.toOption + .flatMap(schema => + resolveSubqueryVariableDefs(schema, + rootTypes, + none, + subquery.render + ).toOption + ) + .fold(stats)(variableDefs => + addVariableDefsTypeAlias(none, variableDefs)(stats) + ) ) case _ => IO.pure(stats) } @@ -94,7 +124,10 @@ class GraphQLGen(val config: GraphQLGenConfig) _, _ ) => - IO.pure(Patch.replaceTree(obj, "")) + // The placeholder goes away, and with it the import of its annotation, if any. + IO.pure( + Patch.replaceTree(obj, "") + Patch.removeGlobalImport(GraphQLStubAnnotation.symbol) + ) case obj @ Defn.Trait.Initial( mods @ GraphQLSchemaAnnotation(_), templateName, @@ -236,29 +269,21 @@ class GraphQLGen(val config: GraphQLGenConfig) val objName = templateName.value (extractSubquerySchemaType(inits), extractRootTypes(mods)) match { - case (None, _) => + case (None, _) => IO.pure( errorDiagnostic( "Invalid annotation target: must be a class extending GraphQLSubquery[Schema].", obj.pos ) ) - case (Some(_), Nil) => + case (Some(_), Nil) => IO.pure( errorDiagnostic( "A GraphQLSubquery must declare its root type with a `@GraphQLType(\"...\")` annotation.", obj.pos ) ) - case (Some(_), rootTypes) if rootTypes.sizeIs > 1 => - IO.pure( - errorDiagnostic( - "A subquery processed by the generator (@GraphQL) must declare exactly one " + - "@GraphQLType; multiple types are only supported on hand-written subqueries.", - obj.pos - ) - ) - case (Some(schemaType), rootTypeName :: _) => + case (Some(schemaType), rootTypes) => extractSubquery(stats) match { case None => IO.pure( @@ -270,26 +295,26 @@ class GraphQLGen(val config: GraphQLGenConfig) case Some(subquery) => withSchema(schemaType.value, obj.pos) { schema => val explicitVariableDefs: Option[String] = extractVariableDefs(stats) - // For @GraphQL subqueries, infer the referenced variables from usage when the - // author didn't declare them; the inferred set is emitted as - // `type VariableDefs`. - val variableDefs: String = - explicitVariableDefs.getOrElse( - inferSubqueryVariableDefs(schema, rootTypeName, subquery.render) + // Validate the subquery against each of its root types first, reporting all + // problems as diagnostics (errors at the subquery, warnings at the + // definition). For @GraphQL subqueries, the referenced variables are inferred + // from usage when the author didn't declare them; the inferred set is emitted + // as `type VariableDefs`. + val validation: Result[String] = + resolveSubqueryVariableDefs( + schema, + rootTypes, + explicitVariableDefs, + subquery.render ) - // Validate the subquery against its root type first, reporting all problems - // as diagnostics (errors at the subquery, warnings at the definition). - val validation: Result[Unit] = - validateSubquery(schema, rootTypeName, variableDefs, subquery.render) val diagnostics: Patch = lintResult( - validation, + validation.map(_ => ()), gqlValuePos("subquery", stats).getOrElse(obj.pos), obj.pos ) - if (!validation.hasValue) diagnostics - else { + validation.toOption.fold(diagnostics) { variableDefs => // Validation passed, so parsing and variable-type resolution below succeed. val (operations, fragments) = GQLParser @@ -299,39 +324,49 @@ class GraphQLGen(val config: GraphQLGenConfig) // TODO Support multi-operation queries? val operation = operations.head - // Modifications to add the missing definitions. - val modObjDefs = scala.Function.chain( - List( - addVariableDefsTypeAlias(explicitVariableDefs, variableDefs), - addImports(schemaType.value), - addData( - schema, - operation, - config, - subquery.subqueries, - fragments, - schema.types.find(_.name == rootTypeName) - ), - addDataDecoder, - addConvenienceMethod(schemaType, operation, objName, config) + // Modifications to add the missing definitions, resolving the selected + // fields against `rootTypeName`. + def modObjDefs(rootTypeName: String): List[Stat] => List[Stat] = + scala.Function.chain( + List( + addVariableDefsTypeAlias(explicitVariableDefs, variableDefs), + addImports(schemaType.value), + addData( + schema, + operation, + config, + subquery.subqueries, + fragments, + schema.types.find(_.name == rootTypeName) + ), + addDataDecoder, + addConvenienceMethod(schemaType, operation, objName, config) + ) + ) + + // A single object is emitted, so every root type must generate the same one. + val bodies: List[(String, List[Stat])] = + rootTypes.map(rootTypeName => + rootTypeName -> modObjDefs(rootTypeName)(stats) ) - ) val newMods = GraphQLAnnotation.removeFrom(mods).filterNot { case Mod.Abstract() => true case _ => false } - // Congratulations! You got a full-fledged GraphQLOperation (hopefully). - diagnostics + Patch.replaceTree( - obj, - indented(obj)( - q"..$newMods object ${Term - .Name( - objName - )} ${buildTemplate(early, inits, (self.some, modObjDefs(stats)))}".toString - ) - ) + Patch.removeGlobalImport(GraphQLAnnotation.symbol) + generatedMismatch(bodies).fold( + // Congratulations! You got a full-fledged GraphQLOperation (hopefully). + diagnostics + Patch.replaceTree( + obj, + indented(obj)( + q"..$newMods object ${Term + .Name( + objName + )} ${buildTemplate(early, inits, (self.some, bodies.head._2))}".toString + ) + ) + Patch.removeGlobalImport(GraphQLAnnotation.symbol) + )(mismatch => diagnostics + errorDiagnostic(mismatch, obj.pos)) } } } diff --git a/gen/rules/src/main/scala/clue/gen/GraphQLValidation.scala b/gen/rules/src/main/scala/clue/gen/GraphQLValidation.scala index 4d7aa4fb..df4e2e30 100644 --- a/gen/rules/src/main/scala/clue/gen/GraphQLValidation.scala +++ b/gen/rules/src/main/scala/clue/gen/GraphQLValidation.scala @@ -105,10 +105,10 @@ trait GraphQLValidation extends QueryGen { // definition is neither. `defnPos` anchors structural/schema/warning diagnostics. // // `generating` is true when this definition is processed by the code generator (it carries a - // `@GraphQL` annotation): in that case a subquery must declare exactly one `@GraphQLType`, since - // generation (whether it synthesizes `Data` or copies a `.Typed`) targets a single type. When - // false (hand-written, validation only), multiple types are allowed and the selection is validated - // against each. + // `@GraphQL` annotation): in that case the variables a subquery doesn't declare are inferred from + // usage (the generator emits the declaration). When false (hand-written, validation only), the + // subquery must declare them itself, so an undeclared variable is reported. Either way a subquery + // may declare multiple `@GraphQLType`s, and the selection is validated against each. protected def validateGraphQLDefn( mods: List[Mod], inits: List[Init], @@ -149,28 +149,24 @@ trait GraphQLValidation extends QueryGen { defnPos ) ) - else if (generating && rootTypes.sizeIs > 1) - IO.pure( - errorDiagnostic( - "A subquery processed by the generator (@GraphQL) must declare exactly one " + - "@GraphQLType; multiple types are only supported on hand-written subqueries.", - defnPos - ) - ) else withSchema(schemaType.value, defnPos) { schema => + val explicitVariableDefs: Option[String] = extractVariableDefs(stats) lintResult( - validateSubqueryTypes( - schema, - rootTypes, - subqueryVariableDefs(schema, - rootTypes, - stats, - subquery.render, - infer = generating + if (generating) + resolveSubqueryVariableDefs( + schema, + rootTypes, + explicitVariableDefs, + subquery.render + ).map(_ => ()) + else + validateSubqueryTypes( + schema, + rootTypes, + explicitVariableDefs.orEmpty, + subquery.render ), - subquery.render - ), gqlValuePos("subquery", stats).getOrElse(defnPos), defnPos ) diff --git a/gen/rules/src/main/scala/clue/gen/QueryGen.scala b/gen/rules/src/main/scala/clue/gen/QueryGen.scala index 10477be7..2a6ec112 100644 --- a/gen/rules/src/main/scala/clue/gen/QueryGen.scala +++ b/gen/rules/src/main/scala/clue/gen/QueryGen.scala @@ -660,25 +660,47 @@ trait QueryGen extends Generator { .getOrElse("") /** - * The variables to validate a subquery against: the declared `type VariableDefs`, or — when the - * generator processes the subquery (`@GraphQL`), which also emits the declaration for it — the - * set inferred from usage. A hand-written subquery must declare them itself, so `infer` is false - * there and an undeclared variable is reported. + * Validate a subquery the generator processes (`@GraphQL`) against each of `rootTypeNames`, + * yielding the variables it requires: the declared `type VariableDefs` (`explicitVariableDefs`) + * or, when there is none, the set inferred from usage, which the generator then emits as the + * declaration. A single declaration is emitted, so the variables inferred against each root type + * must be the same. */ - protected def subqueryVariableDefs( - schema: Schema, - rootTypeNames: List[String], - stats: List[Stat], - subquery: String, - infer: Boolean - ): String = - extractVariableDefs(stats).getOrElse { - rootTypeNames match { - // Inference needs a single unambiguous root type, which is what `@GraphQL` requires anyway. - case rootTypeName :: Nil if infer => - inferSubqueryVariableDefs(schema, rootTypeName, subquery) - case _ => "" - } + protected def resolveSubqueryVariableDefs( + schema: Schema, + rootTypeNames: List[String], + explicitVariableDefs: Option[String], + subquery: String + ): Result[String] = + explicitVariableDefs match { + case Some(variableDefs) => + validateSubqueryTypes(schema, rootTypeNames, variableDefs, subquery).map(_ => variableDefs) + case None => + val inferred: List[(String, String)] = + rootTypeNames.map(name => name -> inferSubqueryVariableDefs(schema, name, subquery)) + // Each type is validated with its own inferred variables first, so a selection that is + // invalid for one of them is reported as such rather than as a disagreement. + inferred + .parTraverse_ { case (name, variableDefs) => + validateSubquery(schema, name, variableDefs, subquery) + } + .flatMap { _ => + inferred.map(_._2).distinct match { + case Nil => Result.success("") + case variableDefs :: Nil => Result.success(variableDefs) + case _ => + val perType: String = + inferred + .map { case (name, variableDefs) => + s"$name: ${if (variableDefs.isEmpty) "()" else variableDefs}" + } + .mkString(", ") + Result.failure( + s"The variables inferred for the subquery differ between its root types " + + s"[$perType]. Declare them explicitly with `type VariableDefs`." + ) + } + } } // Emit `type VariableDefs = "(...)"` into a generated subquery object when its variables were From 8570f30b1ba69d3e5494e6d83d4c0593ab03d86e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Piaggio?= Date: Mon, 16 Nov 2026 20:42:12 -0300 Subject: [PATCH 2/2] bump base version --- build.sbt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sbt b/build.sbt index dbba1e73..a4c89338 100644 --- a/build.sbt +++ b/build.sbt @@ -1,6 +1,6 @@ lazy val V = _root_.scalafix.sbt.BuildInfo -ThisBuild / tlBaseVersion := "0.61" +ThisBuild / tlBaseVersion := "0.62" Global / onChangedBuildSource := ReloadOnSourceChanges // The CI matrix covers Scala 3 only, which builds `sbt-clue` for sbt 2.x. Run the scripted tests