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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
use super::{
    arguments::{parse_argument_into_param, ParamType, QueryParams},
    queries::{JoinCondition, QueryElement, QueryJoinNode, UserQuery},
};
use async_graphql_parser::{
    parse_query,
    types::{
        DocumentOperations, ExecutableDocument, Field, FragmentDefinition,
        FragmentSpread, OperationDefinition, OperationType, SelectionSet, TypeCondition,
    },
};
use fuel_indexer_database_types::DbType;
use fuel_indexer_schema::db::tables::IndexerSchema;
use std::collections::HashMap;
use thiserror::Error;

pub type GraphqlResult<T> = Result<T, GraphqlError>;

#[derive(Debug, Error)]
pub enum GraphqlError {
    #[error("GraphQl Parser error: {0:?}")]
    ParseError(#[from] async_graphql_parser::Error),
    #[error("Error building dynamic schema: {0:?}")]
    DynamicSchemaBuildError(#[from] async_graphql::dynamic::SchemaError),
    #[error("Could not parse introspection response: {0:?}")]
    IntrospectionQueryError(#[from] serde_json::Error),
    #[error("Unrecognized Type: {0:?}")]
    UnrecognizedType(String),
    #[error("Unrecognized Field in {0:?}: {1:?}")]
    UnrecognizedField(String, String),
    #[error("Unrecognized Argument in {0:?}: {1:?}")]
    UnrecognizedArgument(String, String),
    #[error("Operation not supported: {0:?}")]
    OperationNotSupported(String),
    #[error("Fragment for {0:?} can't be used within {1:?}.")]
    InvalidFragmentSelection(Fragment, String),
    #[error("Unsupported Value Type: {0:?}")]
    UnsupportedValueType(String),
    #[error("Failed to resolve query fragments.")]
    FragmentResolverFailed,
    #[error("Selection not supported.")]
    SelectionNotSupported,
    #[error("Unsupported negation for filter type: {0:?}")]
    UnsupportedNegation(String),
    #[error("Filters should have at least one predicate")]
    NoPredicatesInFilter,
    #[error("Unsupported filter operation type: {0:?}")]
    UnsupportedFilterOperation(String),
    #[error("Unable to parse value into string, bool, or i64: {0:?}")]
    UnableToParseValue(String),
    #[error("No available predicates to associate with logical operator")]
    MissingPartnerForBinaryLogicalOperator,
    #[error("Paginated query must have an order applied to at least one field")]
    UnorderedPaginatedQuery,
    #[error("Query error: {0:?}")]
    QueryError(String),
}

#[derive(Clone, Debug)]
pub enum Selection {
    Field {
        name: String,
        params: Vec<ParamType>,
        sub_selections: Selections,
        alias: Option<String>,
    },
    Fragment(String),
}

#[derive(Clone, Debug)]
pub struct Selections {
    has_fragments: bool,
    selections: Vec<Selection>,
}

impl Selections {
    pub fn new(
        schema: &IndexerSchema,
        field_type: Option<&String>,
        set: &SelectionSet,
    ) -> GraphqlResult<Selections> {
        let mut selections = Vec::with_capacity(set.items.len());
        let mut has_fragments = false;

        for item in &set.items {
            match &item.node {
                async_graphql_parser::types::Selection::Field(field) => {
                    // TODO: directives and sub-selections for nested types...
                    let Field {
                        name,
                        selection_set,
                        arguments,
                        alias,
                        ..
                    } = &field.node;
                    let subfield_type =
                        match schema.parsed().graphql_type(field_type, &name.to_string())
                        {
                            Some(typ) => typ,
                            None => {
                                if let Some(field_type) = field_type {
                                    return Err(GraphqlError::UnrecognizedField(
                                        field_type.into(),
                                        name.to_string(),
                                    ));
                                } else {
                                    return Err(GraphqlError::UnrecognizedType(
                                        name.to_string(),
                                    ));
                                }
                            }
                        };

                    let params = arguments
                        .iter()
                        .map(|(arg, value)| {
                            parse_argument_into_param(
                                Some(subfield_type),
                                &arg.to_string(),
                                value.node.clone(),
                                schema,
                            )
                        })
                        .collect::<Result<Vec<ParamType>, GraphqlError>>()?;

                    let sub_selections = Selections::new(
                        schema,
                        Some(subfield_type),
                        &selection_set.node,
                    )?;
                    selections.push(Selection::Field {
                        name: name.to_string(),
                        params,
                        sub_selections,
                        alias: if alias.is_some() {
                            Some(alias.clone().unwrap().to_string())
                        } else {
                            None
                        },
                    });
                }
                async_graphql_parser::types::Selection::FragmentSpread(frag) => {
                    let FragmentSpread { fragment_name, .. } = &frag.node;
                    has_fragments = true;
                    selections.push(Selection::Fragment(fragment_name.to_string()));
                }
                // TODO: Support inline fragments
                _ => return Err(GraphqlError::SelectionNotSupported),
            }
        }

        Ok(Selections {
            has_fragments,
            selections,
        })
    }

    pub fn resolve_fragments(
        &mut self,
        schema: &IndexerSchema,
        cond: Option<&String>,
        fragments: &HashMap<String, Fragment>,
    ) -> GraphqlResult<usize> {
        let mut has_fragments = false;
        let mut resolved = 0;
        let mut selections = Vec::new();

        for selection in &mut self.selections {
            match selection {
                Selection::Fragment(name) => {
                    if let Some(frag) = fragments.get(name) {
                        if !frag.check_cond(cond) {
                            if let Some(c) = cond {
                                return Err(GraphqlError::InvalidFragmentSelection(
                                    frag.clone(),
                                    c.to_string(),
                                ));
                            } else {
                                return Err(GraphqlError::FragmentResolverFailed);
                            }
                        }
                        resolved += 1;
                        selections.extend(frag.selections.get_selections());
                    } else {
                        has_fragments = true;
                        selections.push(Selection::Fragment(name.to_string()));
                    }
                }
                Selection::Field {
                    name,
                    params,
                    sub_selections,
                    alias,
                } => {
                    let field_type =
                        schema.parsed().graphql_type(cond, name).ok_or_else(|| {
                            if let Some(c) = cond {
                                GraphqlError::UnrecognizedField(
                                    c.to_string(),
                                    name.to_string(),
                                )
                            } else {
                                GraphqlError::UnrecognizedType(name.to_string())
                            }
                        })?;
                    let _ = sub_selections.resolve_fragments(
                        schema,
                        Some(&field_type.clone()),
                        fragments,
                    )?;

                    selections.push(Selection::Field {
                        name: name.to_string(),
                        params: params.to_vec(),
                        sub_selections: sub_selections.clone(),
                        alias: alias.clone(),
                    });
                }
            }
        }

        self.selections = selections;
        self.has_fragments = has_fragments;
        Ok(resolved)
    }

    pub fn get_selections(&self) -> Vec<Selection> {
        self.selections.clone()
    }
}

#[derive(Clone, Debug)]
pub struct Fragment {
    cond: String,
    selections: Selections,
}

impl Fragment {
    pub fn new(
        schema: &IndexerSchema,
        cond: String,
        selection_set: &async_graphql_parser::types::SelectionSet,
    ) -> GraphqlResult<Fragment> {
        let selections = Selections::new(schema, Some(&cond), selection_set)?;

        Ok(Fragment { cond, selections })
    }

    pub fn check_cond(&self, cond: Option<&String>) -> bool {
        if let Some(c) = cond {
            self.cond == *c
        } else {
            false
        }
    }

    pub fn has_fragments(&self) -> bool {
        self.selections.has_fragments
    }

    /// Return the number of fragments resolved
    pub fn resolve_fragments(
        &mut self,
        schema: &IndexerSchema,
        fragments: &HashMap<String, Fragment>,
    ) -> GraphqlResult<usize> {
        self.selections
            .resolve_fragments(schema, Some(&self.cond.clone()), fragments)
    }
}

#[derive(Debug)]
pub struct Operation {
    namespace: String,
    identifier: String,
    selections: Selections,
}

impl Operation {
    pub fn new(
        namespace: String,
        identifier: String,
        selections: Selections,
    ) -> Operation {
        Operation {
            namespace,
            identifier,
            selections,
        }
    }

    pub fn parse(&self, schema: &IndexerSchema) -> Vec<UserQuery> {
        let Operation {
            namespace,
            identifier,
            selections,
            ..
        } = self;

        let mut queries = Vec::new();

        for selection in selections.get_selections() {
            let mut elements: Vec<QueryElement> = Vec::new();
            let mut entities: Vec<String> = Vec::new();

            let mut joins: HashMap<String, QueryJoinNode> = HashMap::new();
            let mut query_params: QueryParams = QueryParams::default();

            let mut nested_entity_stack: Vec<String> = Vec::new();

            // Selections can have their own set of subselections and so on, so a queue
            // is created with the first level of selections. In order to track the containing
            // entity of the selection, an entity list of the same length is created.
            if let Selection::Field {
                name: entity_name,
                params: filters,
                sub_selections: selections,
                alias,
            } = selection
            {
                let mut queue: Vec<Selection> = Vec::new();

                // Selections and entities will be popped from their respective vectors
                // easy access to an element. In order to be compliant with the GraphQL
                // spec (which says that a query should be resovled top-down), the order
                // of the elements is reversed prior to insertion in the queues.
                entities.append(
                    &mut vec![entity_name.clone(); selections.selections.len()]
                        .drain(..)
                        .rev()
                        .collect::<Vec<String>>(),
                );
                queue.append(
                    &mut selections
                        .get_selections()
                        .drain(..)
                        .rev()
                        .collect::<Vec<Selection>>(),
                );

                if !filters.is_empty() {
                    query_params.add_params(
                        filters,
                        format!("{namespace}_{identifier}.{entity_name}"),
                    );
                }

                let mut last_seen_entities_len = entities.len();

                while let Some(current) = queue.pop() {
                    let entity_name = entities.pop().unwrap();

                    // If a selection was processed without adding additional selections
                    // to the queue, then check the entity of the selection against the
                    // current nesting level. If they differ, then the operation has moved
                    // out of a child entity into a parent entity.
                    if let Some(current_nesting_level) = nested_entity_stack.last() {
                        if entities.len() < last_seen_entities_len
                            && current_nesting_level != &entity_name
                        {
                            let _ = nested_entity_stack.pop();
                            elements.push(QueryElement::ObjectClosingBoundary);
                        }
                    }

                    last_seen_entities_len = entities.len();

                    if let Selection::Field {
                        name: field_name,
                        params: filters,
                        sub_selections: subselections,
                        alias,
                    } = current
                    {
                        if subselections.selections.is_empty() {
                            elements.push(QueryElement::Field {
                                key: alias.unwrap_or(field_name.clone()),
                                value: format!(
                                    "{namespace}_{identifier}.{entity_name}.{field_name}"
                                ),
                            });
                            if !filters.is_empty() {
                                query_params.add_params(
                                    filters,
                                    format!("{namespace}_{identifier}.{entity_name}"),
                                );
                            }
                        } else {
                            let mut new_entity = field_name.clone();
                            // If the current entity has a foreign key on the current
                            // selection, join the foreign table on that primary key
                            // and set the field as the innermost entity by pushing to the stack.
                            if let Some(field_to_foreign_key) = schema
                                .parsed()
                                .foreign_key_mappings()
                                .get(&entity_name.to_lowercase())
                            {
                                if let Some((foreign_key_table, foreign_key_col)) =
                                    field_to_foreign_key.get(&field_name.to_lowercase())
                                {
                                    let join_condition = JoinCondition {
                                        referencing_key_table: format!(
                                            "{namespace}_{identifier}.{entity_name}"
                                        ),
                                        referencing_key_col: field_name.clone(),
                                        primary_key_table: format!(
                                            "{namespace}_{identifier}.{foreign_key_table}"
                                        ),
                                        primary_key_col: foreign_key_col.clone(),
                                    };

                                    // Joins are modelled like a directed graph in
                                    // order to ensure that tables can be joined in
                                    // a dependent order, if necessary.
                                    match joins
                                        .get_mut(&join_condition.referencing_key_table)
                                    {
                                        Some(join_node) => {
                                            join_node.dependencies.insert(
                                                join_condition.primary_key_table.clone(),
                                                join_condition.clone(),
                                            );
                                        }
                                        None => {
                                            joins.insert(
                                                join_condition
                                                    .referencing_key_table
                                                    .clone(),
                                                QueryJoinNode {
                                                    dependencies: HashMap::from([(
                                                        join_condition
                                                            .primary_key_table
                                                            .clone(),
                                                        join_condition.clone(),
                                                    )]),
                                                    dependents: HashMap::new(),
                                                },
                                            );
                                        }
                                    };

                                    if *foreign_key_table != field_name {
                                        new_entity = foreign_key_table.to_string();
                                    }

                                    match joins.get_mut(&join_condition.primary_key_table)
                                    {
                                        Some(join_node) => {
                                            join_node.dependents.insert(
                                                join_condition
                                                    .referencing_key_table
                                                    .clone(),
                                                join_condition.clone(),
                                            );
                                        }
                                        None => {
                                            joins.insert(
                                                join_condition.primary_key_table.clone(),
                                                QueryJoinNode {
                                                    dependencies: HashMap::new(),
                                                    dependents: HashMap::from([(
                                                        join_condition
                                                            .referencing_key_table
                                                            .clone(),
                                                        join_condition.clone(),
                                                    )]),
                                                },
                                            );
                                        }
                                    };
                                    if !filters.is_empty() {
                                        query_params.add_params(
                                    filters,
                                    format!("{namespace}_{identifier}.{foreign_key_table}"),
                                        );
                                    }
                                }
                            }

                            // Add the subselections and entities to the ends of
                            // their respective vectors so that they are resolved
                            // immediately after their parent selection.
                            entities.append(&mut vec![
                                new_entity.clone();
                                subselections.selections.len()
                            ]);
                            nested_entity_stack.push(new_entity.clone());

                            elements.push(QueryElement::ObjectOpeningBoundary {
                                key: alias.unwrap_or(field_name.clone()),
                            });

                            queue.append(&mut subselections.get_selections());
                        }
                    }
                }

                // If the query document ends without selections from outer entities,
                // then append the requisite number of object closing boundaries in
                // order to properly format the JSON structure for the database query.
                if !nested_entity_stack.is_empty() {
                    elements.append(&mut vec![
                        QueryElement::ObjectClosingBoundary;
                        nested_entity_stack.len()
                    ]);
                }

                let query = UserQuery {
                    elements,
                    joins,
                    namespace_identifier: format!("{namespace}_{identifier}"),
                    entity_name,
                    query_params,
                    alias,
                };

                queries.push(query)
            }
        }

        queries
    }
}

#[derive(Debug)]
pub struct GraphqlQuery {
    operations: Vec<Operation>,
}

impl GraphqlQuery {
    pub fn parse(&self, schema: &IndexerSchema) -> Vec<UserQuery> {
        let queries: Vec<UserQuery> = self
            .operations
            .iter()
            .flat_map(|o| o.parse(schema))
            .collect::<Vec<UserQuery>>();

        queries
    }

    pub fn as_sql(
        &self,
        schema: &IndexerSchema,
        db_type: DbType,
    ) -> Result<Vec<String>, GraphqlError> {
        let queries = self.parse(schema);

        queries
            .into_iter()
            .map(|mut q| q.to_sql(&db_type))
            .collect::<Result<Vec<String>, GraphqlError>>()
    }
}

pub struct GraphqlQueryBuilder<'a> {
    schema: &'a IndexerSchema,
    document: ExecutableDocument,
}

impl<'a> GraphqlQueryBuilder<'a> {
    pub fn new(
        schema: &'a IndexerSchema,
        query: &'a str,
    ) -> GraphqlResult<GraphqlQueryBuilder<'a>> {
        let document = parse_query::<&str>(query)?;
        Ok(GraphqlQueryBuilder { schema, document })
    }

    pub fn build(self) -> GraphqlResult<GraphqlQuery> {
        let fragments = self.process_fragments()?;
        let operations = self.process_operations(fragments)?;
        Ok(GraphqlQuery { operations })
    }

    fn process_operation(
        &self,
        operation: &OperationDefinition,
        fragments: &HashMap<String, Fragment>,
    ) -> GraphqlResult<Operation> {
        match operation.ty {
            OperationType::Query => {
                // TODO: directives and variable definitions....
                let OperationDefinition { selection_set, .. } = operation;
                let mut selections =
                    Selections::new(self.schema, None, &selection_set.node)?;
                selections.resolve_fragments(self.schema, None, fragments)?;

                Ok(Operation::new(
                    self.schema.parsed().namespace().to_string(),
                    self.schema.parsed().identifier().to_string(),
                    selections,
                ))
            }
            OperationType::Mutation => {
                Err(GraphqlError::OperationNotSupported("Mutation".into()))
            }
            OperationType::Subscription => {
                Err(GraphqlError::OperationNotSupported("Subscription".into()))
            }
        }
    }

    fn process_operations(
        &self,
        fragments: HashMap<String, Fragment>,
    ) -> GraphqlResult<Vec<Operation>> {
        let mut operations = vec![];

        match &self.document.operations {
            DocumentOperations::Single(operation_def) => {
                let op = self.process_operation(&operation_def.node, &fragments)?;
                operations.push(op);
            }
            DocumentOperations::Multiple(operation_map) => {
                for (_name, operation_def) in operation_map.iter() {
                    let op = self.process_operation(&operation_def.node, &fragments)?;
                    operations.push(op);
                }
            }
        }

        Ok(operations)
    }

    fn process_fragments(&self) -> GraphqlResult<HashMap<String, Fragment>> {
        let mut fragments = HashMap::new();
        let mut to_resolve = Vec::new();

        for (name, fragment_def) in self.document.fragments.iter() {
            let FragmentDefinition {
                type_condition,
                selection_set,
                ..
            } = &fragment_def.node;

            let TypeCondition { on: cond } = &type_condition.node;

            if !self.schema.parsed().has_type(&cond.to_string()) {
                return Err(GraphqlError::UnrecognizedType(cond.to_string()));
            }

            let frag = Fragment::new(self.schema, cond.to_string(), &selection_set.node)?;

            if frag.has_fragments() {
                to_resolve.push((name.to_string(), frag));
            } else {
                fragments.insert(name.to_string(), frag);
            }
        }

        loop {
            let mut resolved = 0;
            let mut remaining = Vec::new();

            for (name, mut frag) in to_resolve.into_iter() {
                resolved += frag.resolve_fragments(self.schema, &fragments)?;

                if frag.has_fragments() {
                    remaining.push((name, frag))
                } else {
                    fragments.insert(name, frag);
                }
            }

            if !remaining.is_empty() && resolved == 0 {
                return Err(GraphqlError::FragmentResolverFailed);
            } else if remaining.is_empty() {
                break;
            }

            to_resolve = remaining;
        }

        Ok(fragments)
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use fuel_indexer_lib::graphql::GraphQLSchema;

    #[test]
    fn test_operation_parse_into_user_query() {
        let selections_on_block_field = Selections {
            has_fragments: false,
            selections: vec![
                Selection::Field {
                    name: "id".to_string(),
                    params: Vec::new(),
                    sub_selections: Selections {
                        has_fragments: false,
                        selections: Vec::new(),
                    },
                    alias: None,
                },
                Selection::Field {
                    name: "height".to_string(),
                    params: Vec::new(),
                    sub_selections: Selections {
                        has_fragments: false,
                        selections: Vec::new(),
                    },
                    alias: None,
                },
            ],
        };

        let selections_on_tx_field = Selections {
            has_fragments: false,
            selections: vec![
                Selection::Field {
                    name: "block".to_string(),
                    params: Vec::new(),
                    sub_selections: selections_on_block_field,
                    alias: None,
                },
                Selection::Field {
                    name: "id".to_string(),
                    params: Vec::new(),
                    sub_selections: Selections {
                        has_fragments: false,
                        selections: Vec::new(),
                    },
                    alias: None,
                },
                Selection::Field {
                    name: "timestamp".to_string(),
                    params: Vec::new(),
                    sub_selections: Selections {
                        has_fragments: false,
                        selections: Vec::new(),
                    },
                    alias: None,
                },
            ],
        };

        let query_selections = vec![Selection::Field {
            name: "tx".to_string(),
            params: Vec::new(),
            sub_selections: selections_on_tx_field,
            alias: None,
        }];

        let operation = Operation {
            namespace: "fuel_indexer_test".to_string(),
            identifier: "test_index".to_string(),
            selections: Selections {
                has_fragments: false,
                selections: query_selections,
            },
        };

        let schema = r#"
type Block @entity {
    id: ID!
    height: U64!
    timestamp: I64!
}

type Tx @entity {
    id: ID!
    timestamp: I64!
    block: Block
    input_data: Json!
}
"#;

        let schema = IndexerSchema::new(
            "fuel_indexer_test",
            "test_index",
            &GraphQLSchema::new(schema.to_string()),
            DbType::Postgres,
        )
        .unwrap();

        let expected = vec![UserQuery {
            elements: vec![
                QueryElement::ObjectOpeningBoundary {
                    key: "block".to_string(),
                },
                QueryElement::Field {
                    key: "height".to_string(),
                    value: "fuel_indexer_test_test_index.block.height".to_string(),
                },
                QueryElement::Field {
                    key: "id".to_string(),
                    value: "fuel_indexer_test_test_index.block.id".to_string(),
                },
                QueryElement::ObjectClosingBoundary,
                QueryElement::Field {
                    key: "id".to_string(),
                    value: "fuel_indexer_test_test_index.tx.id".to_string(),
                },
                QueryElement::Field {
                    key: "timestamp".to_string(),
                    value: "fuel_indexer_test_test_index.tx.timestamp".to_string(),
                },
            ],
            joins: HashMap::from([
                (
                    "fuel_indexer_test_test_index.tx".to_string(),
                    QueryJoinNode {
                        dependencies: HashMap::from([(
                            "fuel_indexer_test_test_index.block".to_string(),
                            JoinCondition {
                                referencing_key_table: "fuel_indexer_test_test_index.tx"
                                    .to_string(),
                                referencing_key_col: "block".to_string(),
                                primary_key_table: "fuel_indexer_test_test_index.block"
                                    .to_string(),
                                primary_key_col: "id".to_string(),
                            },
                        )]),
                        dependents: HashMap::new(),
                    },
                ),
                (
                    "fuel_indexer_test_test_index.block".to_string(),
                    QueryJoinNode {
                        dependents: HashMap::from([(
                            "fuel_indexer_test_test_index.tx".to_string(),
                            JoinCondition {
                                referencing_key_table: "fuel_indexer_test_test_index.tx"
                                    .to_string(),
                                referencing_key_col: "block".to_string(),
                                primary_key_table: "fuel_indexer_test_test_index.block"
                                    .to_string(),
                                primary_key_col: "id".to_string(),
                            },
                        )]),
                        dependencies: HashMap::new(),
                    },
                ),
            ]),
            namespace_identifier: "fuel_indexer_test_test_index".to_string(),
            entity_name: "tx".to_string(),
            query_params: QueryParams::default(),
            alias: None,
        }];
        assert_eq!(expected, operation.parse(&schema));
    }
}