apollo-compiler 1.31.1

A compiler for the GraphQL query language.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
use apollo_compiler::ast;
use apollo_compiler::ast::Value;
use apollo_compiler::name;
use apollo_compiler::parser::Parser;
use apollo_compiler::schema::ExtendedType;
use apollo_compiler::Node;

#[test]
fn it_raises_undefined_variable_in_query_error() {
    let input = r#"
query ExampleQuery {
  topProducts(first: $undefinedVariable) {
    name
  }

  me {
    ... on User {
      id
      name
      profilePic(size: $dimensions)
      status
    }
  }
}

type Query {
  topProducts(first: Int): Products
  me: User
}

type User {
    id: ID
    name: String
    profilePic(size: Int): String
    status(membership: String): String
}

type Products {
  weight: Float
  size: Int
  name: String
}
"#;

    let errors = Parser::new()
        .parse_mixed_validate(input, "schema.graphql")
        .unwrap_err()
        .to_string();
    assert!(
        errors.contains("variable `$undefinedVariable` is not defined"),
        "{errors}"
    );
    assert!(
        errors.contains("variable `$dimensions` is not defined"),
        "{errors}"
    );
}

#[test]
fn it_raises_unused_variable_in_query_error() {
    let input = r#"
query ExampleQuery($unusedVariable: Int) {
  topProducts {
    name
  }
  ... multipleSubscriptions
}

type Query {
  topProducts(first: Int): Product,
}

type Product {
  name: String
  price(setPrice: Int): Int
}
"#;

    let errors = Parser::new()
        .parse_mixed_validate(input, "schema.graphql")
        .unwrap_err()
        .to_string();
    assert!(
        errors.contains("unused variable: `$unusedVariable`"),
        "{errors}"
    );
}

#[test]
fn it_raises_undefined_variable_in_query_in_fragments_error() {
    let input = r#"
query ExampleQuery {
  topProducts {
    name
  }

  me {
    ... on User {
      id
      name
      status(membership: $goldStatus)
    }
  }

  ... fragmentOne
}

fragment fragmentOne on Query {
    profilePic(size: $dimensions)
}

type Query {
  topProducts: Product
  profilePic(size: Int): String
  me: User
}

type User {
    id: ID
    name: String
    status(membership: String): String
}

type Product {
  name: String
  price(setPrice: Int): Int
}
"#;

    let errors = Parser::new()
        .parse_mixed_validate(input, "schema.graphql")
        .unwrap_err()
        .to_string();
    assert!(
        errors.contains("variable `$goldStatus` is not defined"),
        "{errors}"
    );
    assert!(
        errors.contains("variable `$dimensions` is not defined"),
        "{errors}"
    );
}

/// apollo-parser already emits parse errors for variable syntax in const context,
/// but it is still possible to mutate Rust data structures to create `Value::Variable(x)`
/// that should be validation errors.
///
/// Here we parse a document that uses a string value `"x"` in all places a const value can show up
/// then programatically replace them with `$x` variable usage.
/// We expect the original document to be valid, and the modified documents to have
/// as many validation errors as occurrences of `"x"` strings in the original.
#[test]
fn variables_in_const_contexts() {
    let input = r#"
        directive @dir(
            arg: InputObj = {x: ["x"]} @dir2(arg: "x")
        ) repeatable on
            | QUERY
            | MUTATION
            | SUBSCRIPTION
            | FIELD
            | FRAGMENT_DEFINITION
            | FRAGMENT_SPREAD
            | INLINE_FRAGMENT
            | VARIABLE_DEFINITION
            | SCHEMA
            | SCALAR
            | OBJECT
            | FIELD_DEFINITION
            | ARGUMENT_DEFINITION
            | INTERFACE
            | UNION
            | ENUM
            | ENUM_VALUE
            | INPUT_OBJECT
            | INPUT_FIELD_DEFINITION

        directive @dir2(
            arg: String
        ) repeatable on
            | ARGUMENT_DEFINITION
            | INPUT_OBJECT
            | INPUT_FIELD_DEFINITION

        schema @dir(arg: {x: ["x"]}) {
            query: Query
        }
        extend schema @dir(arg: {x: ["x"]})

        scalar S @dir(arg: {x: ["x"]})
        extend scalar S @dir(arg: {x: ["x"]})

        type Query implements Inter @dir(arg: {x: ["x"]}) {
            field(
                arg1: String
                arg2: InputObj = {x: ["x"]} @dir(arg: {x: ["x"]})
            ): String @dir(arg: {x: ["x"]})
        }
        extend type Query @dir(arg: {x: ["x"]})

        interface Inter @dir(arg: {x: ["x"]}) {
            field(
                arg1: String
                arg2: InputObj = {x: ["x"]} @dir(arg: {x: ["x"]})
            ): String @dir(arg: {x: ["x"]})
        }
        extend interface Inter @dir(arg: {x: ["x"]})

        union U @dir(arg: {x: ["x"]}) = Query
        extend union U @dir(arg: {x: ["x"]})

        enum Maybe @dir(arg: {x: ["x"]}) {
            YES @dir(arg: {x: ["x"]})
            NO @dir(arg: {x: ["x"]})
        }
        extend enum Maybe @dir(arg: {x: ["x"]})

        input InputObj @dir2(arg: "x") {
            x: [String] = ["x"] @dir2(arg: "x")
        }
        extend input InputObj @dir2(arg: "x")

        query(
            $x: String
            $y: InputObj = {x: ["x"]} @dir(arg: {x: ["x"]})
        ) {
            field(arg1: $x, arg2: $y)
        }
    "#;
    fn mutate_dir_arg(directive: &mut Node<ast::Directive>) {
        mutate_input_obj_value(&mut directive.make_mut().arguments[0].make_mut().value)
    }

    fn mutate_input_obj_value(value: &mut Node<Value>) {
        let Value::Object(fields) = value.make_mut() else {
            panic!("expected object")
        };
        let Value::List(items) = fields[0].1.make_mut() else {
            panic!("expected list")
        };
        mutate_string_value(&mut items[0])
    }

    fn mutate_string_value(value: &mut Node<Value>) {
        *value.make_mut() = Value::Variable(name!(x))
    }

    let (schema, doc) = Parser::new()
        .parse_mixed_validate(input, "input.graphql")
        .unwrap();
    let mut doc = doc.into_inner();

    let operation = doc.operations.anonymous.as_mut().unwrap().make_mut();
    let variable_def = operation.variables[1].make_mut();
    mutate_input_obj_value(variable_def.default_value.as_mut().unwrap());
    mutate_dir_arg(&mut variable_def.directives[0]);

    assert!(
        !doc.to_string().contains("\"x\""),
        "Did not replace all string values with variables:\n{doc}",
    );
    let errors = doc.validate(&schema).unwrap_err().errors;
    let expected = expect_test::expect![[r#"
        Error: variable `$x` is not defined
            ╭─[ input.graphql:72:33 ]
            │
         72 │             $y: InputObj = {x: ["x"]} @dir(arg: {x: ["x"]})
            │                                 ─┬─  
            │                                  ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:72:54 ]
            │
         72 │             $y: InputObj = {x: ["x"]} @dir(arg: {x: ["x"]})
            │                                                      ─┬─  
            │                                                       ╰─── not found in this scope
        ────╯
    "#]];
    expected.assert_eq(&errors.to_string());
    let expected_executable_errors = 2;
    assert_eq!(errors.len(), expected_executable_errors);

    let mut schema = schema.into_inner();

    let dir_arg_def = schema.directive_definitions["dir"].make_mut().arguments[0].make_mut();
    let dir2 = dir_arg_def.directives[0].make_mut();
    mutate_input_obj_value(dir_arg_def.default_value.as_mut().unwrap());
    mutate_string_value(&mut dir2.arguments[0].make_mut().value);

    let def = schema.schema_definition.make_mut();
    mutate_dir_arg(&mut def.directives[0]);
    mutate_dir_arg(&mut def.directives[1]);

    let ExtendedType::Scalar(def) = &mut schema.types["S"] else {
        panic!("expected scalar")
    };
    let def = def.make_mut();
    mutate_dir_arg(&mut def.directives[0]);
    mutate_dir_arg(&mut def.directives[1]);

    let ExtendedType::Object(def) = &mut schema.types["Query"] else {
        panic!("expected object")
    };
    let def = def.make_mut();
    let field = def.fields[0].make_mut();
    let field_arg = field.arguments[1].make_mut();
    mutate_dir_arg(&mut def.directives[0]);
    mutate_dir_arg(&mut def.directives[1]);
    mutate_dir_arg(&mut field.directives[0]);
    mutate_dir_arg(&mut field_arg.directives[0]);
    mutate_input_obj_value(field_arg.default_value.as_mut().unwrap());

    let ExtendedType::Interface(def) = &mut schema.types["Inter"] else {
        panic!("expected interface")
    };
    let def = def.make_mut();
    let field = def.fields[0].make_mut();
    let field_arg = field.arguments[1].make_mut();
    mutate_dir_arg(&mut def.directives[0]);
    mutate_dir_arg(&mut def.directives[1]);
    mutate_dir_arg(&mut field.directives[0]);
    mutate_dir_arg(&mut field_arg.directives[0]);
    mutate_input_obj_value(field_arg.default_value.as_mut().unwrap());

    let ExtendedType::Union(def) = &mut schema.types["U"] else {
        panic!("expected union")
    };
    let def = def.make_mut();
    mutate_dir_arg(&mut def.directives[0]);
    mutate_dir_arg(&mut def.directives[1]);

    let ExtendedType::Enum(def) = &mut schema.types["Maybe"] else {
        panic!("expected enum")
    };
    let def = def.make_mut();
    mutate_dir_arg(&mut def.directives[0]);
    mutate_dir_arg(&mut def.directives[1]);
    mutate_dir_arg(&mut def.values["YES"].make_mut().directives[0]);
    mutate_dir_arg(&mut def.values["NO"].make_mut().directives[0]);

    let ExtendedType::InputObject(def) = &mut schema.types["InputObj"] else {
        panic!("expected input object")
    };
    let def = def.make_mut();
    let field = def.fields[0].make_mut();
    let Value::List(items) = field.default_value.as_mut().unwrap().make_mut() else {
        panic!("expected list")
    };
    mutate_string_value(&mut def.directives[0].make_mut().arguments[0].make_mut().value);
    mutate_string_value(&mut def.directives[1].make_mut().arguments[0].make_mut().value);
    mutate_string_value(&mut field.directives[0].make_mut().arguments[0].make_mut().value);
    mutate_string_value(&mut items[0]);

    assert!(
        !schema.to_string().contains("\"x\""),
        "Did not replace all string values with variables:\n{schema}",
    );
    let errors = schema.validate().unwrap_err().errors;
    let expected = expect_test::expect![[r#"
        Error: variable `$x` is not defined
           ╭─[ input.graphql:3:51 ]
           │
         3 │             arg: InputObj = {x: ["x"]} @dir2(arg: "x")
           │                                                   ─┬─  
           │                                                    ╰─── not found in this scope
        ───╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:32:31 ]
            │
         32 │         schema @dir(arg: {x: ["x"]}) {
            │                               ─┬─  
            │                                ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:35:38 ]
            │
         35 │         extend schema @dir(arg: {x: ["x"]})
            │                                      ─┬─  
            │                                       ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:37:33 ]
            │
         37 │         scalar S @dir(arg: {x: ["x"]})
            │                                 ─┬─  
            │                                  ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:38:40 ]
            │
         38 │         extend scalar S @dir(arg: {x: ["x"]})
            │                                        ─┬─  
            │                                         ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:40:52 ]
            │
         40 │         type Query implements Inter @dir(arg: {x: ["x"]}) {
            │                                                    ─┬─  
            │                                                     ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:43:60 ]
            │
         43 │                 arg2: InputObj = {x: ["x"]} @dir(arg: {x: ["x"]})
            │                                                            ─┬─  
            │                                                             ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:44:38 ]
            │
         44 │             ): String @dir(arg: {x: ["x"]})
            │                                      ─┬─  
            │                                       ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:46:42 ]
            │
         46 │         extend type Query @dir(arg: {x: ["x"]})
            │                                          ─┬─  
            │                                           ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:48:40 ]
            │
         48 │         interface Inter @dir(arg: {x: ["x"]}) {
            │                                        ─┬─  
            │                                         ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:51:60 ]
            │
         51 │                 arg2: InputObj = {x: ["x"]} @dir(arg: {x: ["x"]})
            │                                                            ─┬─  
            │                                                             ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:52:38 ]
            │
         52 │             ): String @dir(arg: {x: ["x"]})
            │                                      ─┬─  
            │                                       ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:54:47 ]
            │
         54 │         extend interface Inter @dir(arg: {x: ["x"]})
            │                                               ─┬─  
            │                                                ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:56:32 ]
            │
         56 │         union U @dir(arg: {x: ["x"]}) = Query
            │                                ─┬─  
            │                                 ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:57:39 ]
            │
         57 │         extend union U @dir(arg: {x: ["x"]})
            │                                       ─┬─  
            │                                        ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:59:35 ]
            │
         59 │         enum Maybe @dir(arg: {x: ["x"]}) {
            │                                   ─┬─  
            │                                    ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:60:32 ]
            │
         60 │             YES @dir(arg: {x: ["x"]})
            │                                ─┬─  
            │                                 ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:61:31 ]
            │
         61 │             NO @dir(arg: {x: ["x"]})
            │                               ─┬─  
            │                                ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:63:42 ]
            │
         63 │         extend enum Maybe @dir(arg: {x: ["x"]})
            │                                          ─┬─  
            │                                           ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:65:35 ]
            │
         65 │         input InputObj @dir2(arg: "x") {
            │                                   ─┬─  
            │                                    ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:66:44 ]
            │
         66 │             x: [String] = ["x"] @dir2(arg: "x")
            │                                            ─┬─  
            │                                             ╰─── not found in this scope
        ────╯
        Error: variable `$x` is not defined
            ╭─[ input.graphql:68:42 ]
            │
         68 │         extend input InputObj @dir2(arg: "x")
            │                                          ─┬─  
            │                                           ╰─── not found in this scope
        ────╯
    "#]];
    expected.assert_eq(&errors.to_string());
    let expected_schema_errors = 22;
    assert_eq!(errors.len(), expected_schema_errors);

    // Default values not validated yet: https://github.com/apollographql/apollo-rs/issues/928
    // * @dir(arg:)
    // * Query.field(arg2:)
    // * Inter.field(arg2:)
    // * InputObj.x
    let input_default_values_not_yet_validated = 4;
    assert_eq!(
        input.matches("\"x\"").count(),
        expected_schema_errors
            + expected_executable_errors
            + input_default_values_not_yet_validated
    )
}