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
use std::sync::Arc;

use crate::{
    diagnostics::{ApolloDiagnostic, DiagnosticData, Label},
    hir, FileId, ValidationDatabase,
};

pub fn validate_operation_definitions(
    db: &dyn ValidationDatabase,
    file_id: FileId,
) -> Vec<ApolloDiagnostic> {
    let mut diagnostics = Vec::new();

    let operations = db.operations(file_id);
    for def in operations.iter() {
        diagnostics.extend(db.validate_directives(
            def.directives().to_vec(),
            def.operation_ty().into(),
            // assumption here is that operation definition's own directives can
            // use already defined variables
            def.variables.clone(),
        ));
        diagnostics.extend(db.validate_variable_definitions(def.variables.as_ref().clone()));

        // Validate the Selection Set recursively
        // Check that the root type exists
        if def.object_type(db.upcast()).is_some() {
            diagnostics.extend(
                db.validate_selection_set(def.selection_set().clone(), def.variables.clone()),
            );
        }
        diagnostics.extend(db.validate_unused_variable(def.clone()));
    }

    let subscription_operations = db.upcast().subscription_operations(file_id);
    let query_operations = db.upcast().query_operations(file_id);
    let mutation_operations = db.upcast().mutation_operations(file_id);

    diagnostics.extend(db.validate_subscription_operations(subscription_operations));
    diagnostics.extend(db.validate_query_operations(query_operations));
    diagnostics.extend(db.validate_mutation_operations(mutation_operations));

    // It is possible to have an unnamed (anonymous) operation definition only
    // if there is **one** operation definition.
    //
    // Return a Missing Indent error if there are multiple operations and one or
    // more are missing a name.
    let op_len = operations.len();
    if op_len > 1 {
        let missing_ident: Vec<ApolloDiagnostic> = operations
            .iter()
            .filter_map(|op| {
                if op.name().is_none() {
                    return Some(
                        ApolloDiagnostic::new(db, op.loc().into(), DiagnosticData::MissingIdent)
                            .label(Label::new(op.loc(), "provide a name for this definition"))
                            .help(format!("GraphQL allows a short-hand form for defining query operations when only that one operation exists in the document. There are {op_len} operations in this document.")),
                    );
                }
                None
            })
            .collect();
        diagnostics.extend(missing_ident);
    }

    diagnostics
}

pub fn validate_subscription_operations(
    db: &dyn ValidationDatabase,
    subscriptions: Arc<Vec<Arc<hir::OperationDefinition>>>,
) -> Vec<ApolloDiagnostic> {
    let mut diagnostics = Vec::new();

    // Subscription fields must not have an introspection field in the selection set.
    //
    // Return an Introspection Field error in case of an introspection field existing as the root field in the set.
    for op in subscriptions.iter() {
        for selection in op.selection_set().selection() {
            if let hir::Selection::Field(field) = selection {
                if field.is_introspection() {
                    let field_name = field.name();
                    diagnostics.push(
                        ApolloDiagnostic::new(
                            db,
                            field.loc().into(),
                            DiagnosticData::IntrospectionField {
                                field: field_name.into(),
                            },
                        )
                        .label(Label::new(
                            field.loc(),
                            format!("{field_name} is an introspection field"),
                        )),
                    );
                }
            }
        }
    }

    // A Subscription operation definition can only have **one** root level
    // field.
    if !subscriptions.is_empty() {
        let single_root_field: Vec<ApolloDiagnostic> = subscriptions
            .iter()
            .filter_map(|op| {
                let mut fields = op.fields(db.upcast()).as_ref().clone();
                fields.extend(op.fields_in_inline_fragments(db.upcast()).as_ref().clone());
                fields.extend(op.fields_in_fragment_spread(db.upcast()).as_ref().clone());
                if fields.len() > 1 {
                    let field_names: Vec<&str> = fields.iter().map(|f| f.name()).collect();
                    Some(
                        ApolloDiagnostic::new(
                            db,
                            op.loc().into(),
                            DiagnosticData::SingleRootField {
                                fields: fields.len(),
                                subscription: op.loc().into(),
                            },
                        )
                        .label(Label::new(
                            op.loc(),
                            format!("subscription with {} root fields", fields.len()),
                        ))
                        .help(format!(
                            "There are {} root fields: {}. This is not allowed.",
                            fields.len(),
                            field_names.join(", ")
                        )),
                    )
                } else {
                    None
                }
            })
            .collect();
        diagnostics.extend(single_root_field);
    }

    // All query, subscription and mutation operations must be against legally
    // defined schema root operation types.
    //
    //   * subscription operation - subscription root operation
    if !subscriptions.is_empty() && db.schema().subscription().is_none() {
        let unsupported_ops: Vec<ApolloDiagnostic> = subscriptions
            .iter()
            .map(|op| {
                let diagnostic = ApolloDiagnostic::new(db, op.loc().into(), DiagnosticData::UnsupportedOperation { ty: "subscription" })
                    .label(Label::new(op.loc(), "Subscription operation is not defined in the schema and is therefore not supported"));
                if let Some(schema_loc) = db.schema().loc() {
                    diagnostic.label(Label::new(schema_loc, "Consider defining a `subscription` root operation type here"))
                } else {
                    diagnostic.help("consider defining a `subscription` root operation type in your schema")
                }
            })
            .collect();
        diagnostics.extend(unsupported_ops)
    }

    diagnostics
}

pub fn validate_query_operations(
    db: &dyn ValidationDatabase,
    queries: Arc<Vec<Arc<hir::OperationDefinition>>>,
) -> Vec<ApolloDiagnostic> {
    let mut diagnostics = Vec::new();

    // All query, subscription and mutation operations must be against legally
    // defined schema root operation types.
    //
    //   * query operation - query root operation
    if !queries.is_empty() && db.schema().query().is_none() {
        let unsupported_ops: Vec<ApolloDiagnostic> =
            queries
                .iter()
                .filter_map(|op| {
                    if !op.is_introspection(db.upcast()) {
                        let diagnostic = ApolloDiagnostic::new(
                            db,
                            op.loc().into(),
                            DiagnosticData::UnsupportedOperation { ty: "query" },
                        )
                        .label(Label::new(
                            op.loc(),
                            "Query operation is not defined in the schema and is therefore not supported",
                        ));
                        if let Some(schema_loc) = db.schema().loc() {
                            Some(diagnostic.label(Label::new(
                                schema_loc,
                                "Consider defining a `query` root operation type here",
                            )))
                        } else {
                            Some(diagnostic.help(
                                "consider defining a `query` root operation type in your schema",
                            ))
                        }
                    } else {
                        None
                    }
                })
                .collect();
        diagnostics.extend(unsupported_ops)
    }

    diagnostics
}

pub fn validate_mutation_operations(
    db: &dyn ValidationDatabase,
    mutations: Arc<Vec<Arc<hir::OperationDefinition>>>,
) -> Vec<ApolloDiagnostic> {
    let mut diagnostics = Vec::new();

    // All query, subscription and mutation operations must be against legally
    // defined schema root operation types.
    //
    //   * mutation operation - mutation root operation
    if !mutations.is_empty() && db.schema().mutation().is_none() {
        let unsupported_ops: Vec<ApolloDiagnostic> = mutations
            .iter()
            .map(|op| {
                let diagnostic = ApolloDiagnostic::new(db, op.loc().into(), DiagnosticData::UnsupportedOperation { ty: "mutation" })
                    .label(Label::new(op.loc(), "Mutation operation is not defined in the schema and is therefore not supported"));
                if let Some(schema_loc) = db.schema().loc() {
                    diagnostic.label(Label::new(schema_loc, "Consider defining a `mutation` root operation type here"))
                } else {
                    diagnostic.help("consider defining a `mutation` root operation type in your schema")
                }
            })
            .collect();
        diagnostics.extend(unsupported_ops)
    }

    diagnostics
}

#[cfg(test)]
mod test {
    use crate::ApolloCompiler;

    #[test]
    fn it_fails_validation_with_missing_ident() {
        let input = r#"
query {
  cat {
    name
  }
}

query getPet {
  cat {
    name
  }
}

query getOtherPet {
  cat {
    nickname
  }
}

type Query {
  cat: Cat
}

type Cat {
  name: String
  nickname: String
  meowVolume: Int
}
"#;
        let mut compiler = ApolloCompiler::new();
        compiler.add_document(input, "schema.graphql");

        let diagnostics = compiler.validate();
        for diagnostic in &diagnostics {
            println!("{diagnostic}")
        }
        assert_eq!(diagnostics.len(), 1)
    }

    #[test]
    fn it_fails_validation_with_duplicate_operation_names() {
        let input = r#"
query getName {
  cat {
    name
  }
}

query getName {
  cat {
    name
    nickname
  }
}

type Query {
  cat: Pet
}

union CatOrDog = Cat | Dog

interface Pet {
  name: String
  nickname: String
}

type Dog implements Pet {
  name: String
  nickname: String
  barkVolume: Int
}

type Cat implements Pet {
  name: String
  nickname: String
  meowVolume: Int
}
"#;
        let mut compiler = ApolloCompiler::new();
        compiler.add_document(input, "schema.graphql");

        let diagnostics = compiler.validate();
        for diagnostic in &diagnostics {
            println!("{diagnostic}")
        }
        assert_eq!(diagnostics.len(), 1)
    }

    #[test]
    fn it_validates_unique_operation_names() {
        let input = r#"
query getCatName {
  cat {
    name
  }
}

query getPetNickname {
  cat {
    nickname
  }
}

type Query {
  cat: Pet
}

union CatOrDog = Cat | Dog

interface Pet {
  name: String
  nickname: String
}

type Dog implements Pet {
  name: String
  nickname: String
  barkVolume: Int
}

type Cat implements Pet {
  name: String
  nickname: String
  meowVolume: Int
}
"#;
        let mut compiler = ApolloCompiler::new();
        compiler.add_document(input, "schema.graphql");

        let diagnostics = compiler.validate();
        for diagnostic in &diagnostics {
            println!("{diagnostic}")
        }
        assert!(diagnostics.is_empty());
    }

    #[test]
    fn it_raises_an_error_for_illegal_operations() {
        let input = r#"
subscription sub {
  newMessage {
    body
    sender
  }
}

type Query {
  cat: Pet
}

union CatOrDog = Cat | Dog

interface Pet {
  name: String
}

type Dog implements Pet {
  name: String
  nickname: String
  barkVolume: Int
}

type Cat implements Pet {
  name: String
  nickname: String
  meowVolume: Int
}
"#;
        let mut compiler = ApolloCompiler::new();
        compiler.add_document(input, "schema.graphql");

        let diagnostics = compiler.validate();
        for diagnostic in &diagnostics {
            println!("{diagnostic}")
        }

        assert_eq!(diagnostics.len(), 1)
    }

    #[test]
    fn it_validates_fields_in_operations() {
        let input = r#"
query getProduct {
  name
  noName
  topProducts {
    inStock
    price
  }
}

type Query {
  name: String
  topProducts: Product
}

type Product {
  inStock: Boolean
  name: String
}
"#;

        let mut compiler = ApolloCompiler::new();
        compiler.add_document(input, "schema.graphql");

        let diagnostics = compiler.validate();
        for diagnostic in &diagnostics {
            println!("{diagnostic}");
        }

        assert_eq!(diagnostics.len(), 2)
    }
}