Skip to content

Commit e889cd3

Browse files
committed
Preserve AST definitions across schema transformations
1 parent 3223066 commit e889cd3

10 files changed

Lines changed: 263 additions & 6 deletions

‎src/main/java/graphql/schema/GraphQLAppliedDirective.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ public Builder() {
168168
public Builder(GraphQLAppliedDirective existing) {
169169
this.name = existing.getName();
170170
this.description = existing.getDescription();
171+
this.definition = existing.getDefinition();
171172
this.arguments.putAll(getByName(existing.getArguments(), GraphQLAppliedDirectiveArgument::getName));
172173
}
173174

‎src/main/java/graphql/schema/GraphQLAppliedDirectiveArgument.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ public Builder(GraphQLAppliedDirectiveArgument existing) {
199199
this.name = existing.getName();
200200
this.value = existing.getArgumentValue();
201201
this.type = existing.getType();
202+
this.definition = existing.getDefinition();
202203
}
203204

204205
public Builder type(GraphQLInputType type) {

‎src/main/java/graphql/schema/GraphQLEnumValueDefinition.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ public Builder() {
206206
public Builder(GraphQLEnumValueDefinition existing) {
207207
this.name = existing.getName();
208208
this.description = existing.getDescription();
209+
this.definition = existing.getDefinition();
209210
this.value = existing.getValue();
210211
this.deprecationReason = existing.getDeprecationReason();
211212
copyExistingDirectives(existing);

‎src/main/java/graphql/schema/GraphQLNamedSchemaElement.java‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,13 @@ public interface GraphQLNamedSchemaElement extends GraphQLSchemaElement {
2424
String getDescription();
2525

2626
/**
27-
* The AST {@link Node} this schema element is based on. Is null if the GraphQLSchema
28-
* is not based on a SDL document.
29-
* Some elements also have additional extension Nodes. See for example {@link GraphQLObjectType#getExtensionDefinitions()}
27+
* The original AST {@link Node} this schema element is based on. It can be null when there is no
28+
* corresponding source node or AST capture was disabled during schema generation.
29+
* Some elements also have additional extension nodes. See for example {@link GraphQLObjectType#getExtensionDefinitions()}.
30+
* <p>
31+
* Copying or transforming an element retains its original AST definition and extension definitions by reference,
32+
* unless they are explicitly replaced or cleared. The AST nodes are not updated to reflect changes to the runtime
33+
* element, such as renaming it or changing its type.
3034
*
3135
* @return Node which this element is based on. Can be null.
3236
*/

‎src/main/java/graphql/schema/GraphQLSchema.java‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,9 @@ public String getDescription() {
714714
/**
715715
* This helps you transform the current GraphQLSchema object into another one by starting a builder with all
716716
* the current values and allows you to transform it how you want.
717+
* <p>
718+
* The original AST definition and extension definitions are retained unless explicitly replaced or cleared.
719+
* They are not updated to reflect changes to the runtime schema.
717720
*
718721
* @param builderConsumer the consumer code that will be given a builder to transform
719722
*
@@ -728,6 +731,7 @@ public GraphQLSchema transform(Consumer<Builder> builderConsumer) {
728731
/**
729732
* This helps you transform the current GraphQLSchema object into another one by using a builder that only allows you to change
730733
* simple values and does not involve changing the complex schema type graph.
734+
* The original AST definition and extension definitions are retained without modification.
731735
*
732736
* @param builderConsumer the consumer code that will be given a builder to transform
733737
*
@@ -749,6 +753,7 @@ public static Builder newSchema() {
749753
/**
750754
* This allows you to build a schema from an existing schema. It copies everything from the existing
751755
* schema and then allows you to replace them.
756+
* The original AST definition and extension definitions are retained by reference, not rewritten.
752757
*
753758
* @param existingSchema the existing schema
754759
*
@@ -759,6 +764,7 @@ public static Builder newSchema(GraphQLSchema existingSchema) {
759764
.query(existingSchema.getQueryType())
760765
.mutation(existingSchema.getMutationType())
761766
.subscription(existingSchema.getSubscriptionType())
767+
.definition(existingSchema.getDefinition())
762768
.extensionDefinitions(existingSchema.getExtensionDefinitions())
763769
.introspectionSchemaType(existingSchema.getIntrospectionSchemaType())
764770
.codeRegistry(existingSchema.getCodeRegistry())

‎src/main/java/graphql/schema/GraphQLSchemaElement.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,9 @@ default GraphQLSchemaElement withNewChildren(SchemaElementChildrenContainer newC
5151
int hashCode();
5252

5353
/**
54-
* Each GraphQLSchemaElement should make a copy of itself when this is called. The copy should
55-
* be included its current contents as they currently exist into a new object.
54+
* Each GraphQLSchemaElement should make a copy of itself when this is called. The copy includes
55+
* its current contents in a new object. Any AST definition and extension definitions are retained
56+
* by reference, not deep-copied or rewritten to match the runtime element.
5657
*
5758
* @return a copy of this element
5859
*/

‎src/main/java/graphql/schema/SchemaTransformer.java‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,11 @@
3939
import static graphql.util.TraversalControl.CONTINUE;
4040

4141
/**
42-
* Transforms a {@link GraphQLSchema} object by calling bac on a provided visitor.
42+
* Transforms a {@link GraphQLSchema} object by calling back on a provided visitor.
43+
* <p>
44+
* Rebuilding the schema retains its original AST definition and extension definitions. Schema elements
45+
* copied or transformed through their builders also retain their original AST metadata unless explicitly
46+
* replaced or cleared. The AST nodes are not rewritten to reflect changes to the runtime schema.
4347
* <p>
4448
* To change a {@link GraphQLSchemaElement} node in the schema you need
4549
* to return {@link GraphQLTypeVisitor#changeNode(TraverserContext, GraphQLSchemaElement)}
@@ -741,6 +745,8 @@ public GraphQLSchema rebuildSchema(GraphQLCodeRegistry.Builder codeRegistry, Set
741745
.withSchemaAppliedDirectives(this.schemaAppliedDirectives)
742746
.codeRegistry(codeRegistry.build())
743747
.description(schema.getDescription())
748+
.definition(schema.getDefinition())
749+
.extensionDefinitions(schema.getExtensionDefinitions())
744750
.build();
745751
}
746752
}

‎src/main/java/graphql/schema/idl/SchemaGeneratorHelper.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,7 @@ GraphQLScalarType buildScalar(BuildContext buildCtx, ScalarTypeDefinition typeDe
472472
builder
473473
.description(description)
474474
.definition(buildCtx.isCaptureAstDefinitions() ? typeDefinition : null)
475+
.extensionDefinitions(buildCtx.isCaptureAstDefinitions() ? extensions : emptyList())
475476
.comparatorRegistry(buildCtx.getComparatorRegistry())
476477
.specifiedByUrl(getSpecifiedByUrl(typeDefinition, extensions));
477478

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
package graphql.schema
2+
3+
import graphql.schema.idl.SchemaParser
4+
import graphql.schema.idl.UnExecutableSchemaGenerator
5+
import graphql.util.TraverserContext
6+
import spock.lang.Specification
7+
8+
import static graphql.util.TreeTransformerUtil.changeNode
9+
10+
class AstDefinitionPreservationTest extends Specification {
11+
12+
def "copies retain AST metadata for #original.class.simpleName"() {
13+
given:
14+
def copies = [
15+
original.transform { },
16+
original.copy(),
17+
copyBuilder(original).build(),
18+
original.withNewChildren(original.childrenWithTypeReferences)
19+
]
20+
21+
expect:
22+
original.definition != null
23+
copies.each { copied -> assertAstPreserved(original, copied) }
24+
25+
where:
26+
[original, copyBuilder] << schemaElements()
27+
}
28+
29+
def "definitions can be explicitly cleared for #original.class.simpleName"() {
30+
when:
31+
def cleared = original.transform { it.definition(null) }
32+
33+
then:
34+
cleared.definition == null
35+
cleared.copy().definition == null
36+
original.definition != null
37+
38+
where:
39+
[original, copyBuilder] << schemaElements()
40+
}
41+
42+
def "renaming a runtime element retains the original source AST"() {
43+
given:
44+
def original = schema().queryType
45+
46+
when:
47+
def renamed = original.transform { it.name('RenamedQuery') }
48+
49+
then:
50+
renamed.name == 'RenamedQuery'
51+
renamed.definition.name == 'Query'
52+
assertAstPreserved(original, renamed)
53+
}
54+
55+
def "schema copies retain their definition and extension ASTs - #operation"() {
56+
given:
57+
def original = schema()
58+
59+
when:
60+
def copied = copySchema(original)
61+
62+
then:
63+
!copied.is(original)
64+
original.definition != null
65+
original.extensionDefinitions.size() == 1
66+
copied.definition.is(original.definition)
67+
copied.extensionDefinitions[0].is(original.extensionDefinitions[0])
68+
69+
where:
70+
operation | copySchema
71+
'transform' | { it.transform { } }
72+
'copy builder' | { GraphQLSchema.newSchema(it).build() }
73+
'transformWithoutTypes' | { it.transformWithoutTypes { } }
74+
}
75+
76+
def "schema AST metadata can be explicitly cleared"() {
77+
given:
78+
def original = schema()
79+
80+
when:
81+
def cleared = original.transform { it.definition(null).extensionDefinitions([]) }
82+
83+
then:
84+
cleared.definition == null
85+
cleared.extensionDefinitions.empty
86+
original.definition != null
87+
original.extensionDefinitions.size() == 1
88+
}
89+
90+
def "schema transformation retains ASTs when rebuilding ancestors - with deletes #withDeletes"() {
91+
given:
92+
def original = schema()
93+
def visitor = [visitGraphQLAppliedDirectiveArgument: {
94+
GraphQLAppliedDirectiveArgument argument, TraverserContext<GraphQLSchemaElement> context ->
95+
changeNode(context, argument.transform { it.valueProgrammatic('changed') })
96+
}] as GraphQLTypeVisitorStub
97+
98+
when:
99+
def transformed = withDeletes
100+
? SchemaTransformer.transformSchemaWithDeletes(original, visitor)
101+
: SchemaTransformer.transformSchema(original, visitor)
102+
103+
then:
104+
!transformed.is(original)
105+
transformed.definition.is(original.definition)
106+
transformed.extensionDefinitions[0].is(original.extensionDefinitions[0])
107+
assertAstPreserved(original.queryType, transformed.queryType)
108+
assertAstPreserved(original.getType('Color'), transformed.getType('Color'))
109+
assertAstPreserved(original.getType('Color').getValue('RED'), transformed.getType('Color').getValue('RED'))
110+
assertAppliedAstPreserved(original.queryType, transformed.queryType)
111+
assertAppliedAstPreserved(original.getType('Color').getValue('RED'), transformed.getType('Color').getValue('RED'))
112+
113+
where:
114+
withDeletes << [false, true]
115+
}
116+
117+
def "schema transformation without changes retains the original schema - with deletes #withDeletes"() {
118+
given:
119+
def original = schema()
120+
def visitor = new GraphQLTypeVisitorStub()
121+
122+
expect:
123+
def transformed = withDeletes
124+
? SchemaTransformer.transformSchemaWithDeletes(original, visitor)
125+
: SchemaTransformer.transformSchema(original, visitor)
126+
transformed.is(original)
127+
128+
where:
129+
withDeletes << [false, true]
130+
}
131+
132+
private static void assertAstPreserved(GraphQLNamedSchemaElement original, GraphQLNamedSchemaElement copied) {
133+
assert !copied.is(original)
134+
assert original.definition != null
135+
assert copied.definition.is(original.definition)
136+
if (original.metaClass.respondsTo(original, 'getExtensionDefinitions')) {
137+
assert original.extensionDefinitions.size() == 1
138+
assert copied.extensionDefinitions.size() == 1
139+
assert copied.extensionDefinitions[0].is(original.extensionDefinitions[0])
140+
}
141+
}
142+
143+
private static void assertAppliedAstPreserved(GraphQLDirectiveContainer original, GraphQLDirectiveContainer copied) {
144+
def directive = original.getAppliedDirective('tag')
145+
def copiedDirective = copied.getAppliedDirective('tag')
146+
assertAstPreserved(directive, copiedDirective)
147+
assertAstPreserved(directive.getArgument('arg'), copiedDirective.getArgument('arg'))
148+
assert copiedDirective.getArgument('arg').value == 'changed'
149+
}
150+
151+
private static List<List> schemaElements() {
152+
def original = schema()
153+
def field = original.queryType.getFieldDefinition('field')
154+
def applied = original.queryType.getAppliedDirective('tag')
155+
return [
156+
[original.queryType, { GraphQLObjectType.newObject(it) }],
157+
[original.getType('Node'), { GraphQLInterfaceType.newInterface(it) }],
158+
[original.getType('Choice'), { GraphQLUnionType.newUnionType(it) }],
159+
[original.getType('Color'), { GraphQLEnumType.newEnum(it) }],
160+
[original.getType('Custom'), { GraphQLScalarType.newScalar(it) }],
161+
[original.getType('Filter'), { GraphQLInputObjectType.newInputObject(it) }],
162+
[original.getDirective('tag'), { GraphQLDirective.newDirective(it) }],
163+
[field, { GraphQLFieldDefinition.newFieldDefinition(it) }],
164+
[field.getArgument('arg'), { GraphQLArgument.newArgument(it) }],
165+
[original.getType('Filter').getField('value'), { GraphQLInputObjectField.newInputObjectField(it) }],
166+
[original.getType('Color').getValue('RED'), { GraphQLEnumValueDefinition.newEnumValueDefinition(it) }],
167+
[applied, { GraphQLAppliedDirective.newDirective(it) }],
168+
[applied.getArgument('arg'), { GraphQLAppliedDirectiveArgument.newArgument(it) }]
169+
]
170+
}
171+
172+
private static GraphQLSchema schema() {
173+
def registry = new SchemaParser().parse('''
174+
directive @meta repeatable on DIRECTIVE_DEFINITION
175+
directive @tag(arg: String) @meta repeatable on SCHEMA | OBJECT | ENUM_VALUE
176+
extend directive @tag @meta
177+
schema @tag(arg: "schema") { query: Query }
178+
extend schema @tag(arg: "extension")
179+
type Query implements Node @tag(arg: "query") {
180+
id: ID!
181+
extra: String
182+
field(arg: Filter): Color
183+
choice: Choice
184+
custom: Custom
185+
}
186+
extend type Query { more: String }
187+
interface Node { id: ID! }
188+
extend interface Node { extra: String }
189+
type Other { other: String }
190+
union Choice = Query
191+
extend union Choice = Other
192+
scalar Custom
193+
extend scalar Custom @specifiedBy(url: "https://example.com/custom")
194+
enum Color { RED @tag(arg: "red") }
195+
extend enum Color { BLUE }
196+
input Filter { value: String }
197+
extend input Filter { other: String }
198+
''')
199+
return UnExecutableSchemaGenerator.makeUnExecutableSchema(registry)
200+
}
201+
}

‎src/test/groovy/graphql/schema/idl/SchemaGeneratorTest.groovy‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2588,6 +2588,41 @@ class SchemaGeneratorTest extends Specification {
25882588
}
25892589
25902590
2591+
def "scalar AST capture is #captureAstDefinitions with prepopulated wiring #prepopulated"() {
2592+
given:
2593+
def registry = new SchemaParser().parse('''
2594+
scalar Custom
2595+
extend scalar Custom @specifiedBy(url: "https://example.com/custom")
2596+
type Query { custom: Custom }
2597+
''')
2598+
def definition = registry.scalars().get('Custom')
2599+
def extensions = registry.scalarTypeExtensions().get('Custom')
2600+
def scalar = TestUtil.mockScalar('Custom').transform {
2601+
it.definition(prepopulated ? definition : null)
2602+
.extensionDefinitions(prepopulated ? extensions : [])
2603+
}
2604+
def wiring = RuntimeWiring.newRuntimeWiring().scalar(scalar).build()
2605+
def options = defaultOptions().captureAstDefinitions(captureAstDefinitions)
2606+
2607+
when:
2608+
def schema = new SchemaGenerator().makeExecutableSchema(options, registry, wiring)
2609+
def result = schema.getType('Custom') as GraphQLScalarType
2610+
2611+
then:
2612+
result.specifiedByUrl == 'https://example.com/custom'
2613+
result.definition.is(captureAstDefinitions ? definition : null)
2614+
result.extensionDefinitions.size() == (captureAstDefinitions ? 1 : 0)
2615+
!captureAstDefinitions || result.extensionDefinitions[0].is(extensions[0])
2616+
scalar.extensionDefinitions.size() == (prepopulated ? 1 : 0)
2617+
2618+
where:
2619+
captureAstDefinitions | prepopulated
2620+
true | false
2621+
false | false
2622+
true | true
2623+
false | true
2624+
}
2625+
25912626
def "classCastException when interface extension is before base and has recursion"() {
25922627
given:
25932628
def spec = '''

0 commit comments

Comments
 (0)