sudograph-generate 0.4.3

Procedural macro for Sudograph
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
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
// TODO I might be able to use traits, methods, impls whatever to make a lot of the generation
// TODO simpler per inputobject
// TODO once we have those implemented we can start really testing from the playground
// TODO then we can add update and delete resolvers
// TODO once all of those basics are working, we can start adding more functionality
// TODO once we have a baseline of functionality, we should add tests
// TODO after we add tests we can continue to add functionality, refactor, and then start
// TODO working on multi-canister functionality possibly
// TODO we might want to prioritize Motoko interop...since many newcomers seem to really be moving toward Motoko

mod structs {
    pub mod object_type;
    pub mod create_input;
    pub mod read_input;
    pub mod read_boolean_input;
    pub mod read_date_input;
    pub mod read_float_input;
    pub mod read_id_input;
    pub mod read_int_input;
    pub mod read_string_input;
    pub mod read_enum_input;
    pub mod read_relation_input;
    pub mod read_json_input;
    pub mod read_blob_input;
    pub mod order_input;
    pub mod update_input;
    pub mod delete_input;
    pub mod upsert_input;
}
mod query_resolvers {
    pub mod read;
}
mod mutation_resolvers {
    pub mod create;
    pub mod update;
    pub mod delete;
    pub mod upsert;
    pub mod init;
}
mod settings {
    pub mod generate_settings;
}
mod custom_resolvers {
    pub mod generate_custom_query_struct;
    pub mod generate_custom_mutation_struct;
    pub mod utilities;
}
mod enums {
    pub mod enum_type;
}

use proc_macro::TokenStream;
use quote::quote;
use syn::{
    parse_macro_input,
    LitStr
};
use std::{
    fs
};
use graphql_parser::schema::{
    parse_schema,
    Definition,
    TypeDefinition,
    ObjectType,
    Type,
    Document,
    Field,
    EnumType
};
use structs::object_type::generate_object_type_structs;
use structs::create_input::generate_create_input_rust_structs;
use structs::read_input::generate_read_input_rust_structs;
use structs::read_boolean_input::get_read_boolean_input_rust_struct;
use structs::read_date_input::get_read_date_input_rust_struct;
use structs::read_float_input::get_read_float_input_rust_struct;
use structs::read_id_input::get_read_id_input_rust_struct;
use structs::read_int_input::get_read_int_input_rust_struct;
use structs::read_string_input::get_read_string_input_rust_struct;
use structs::read_enum_input::get_read_enum_input_rust_struct;
use structs::read_relation_input::get_read_relation_input_rust_struct;
use structs::read_json_input::get_read_json_input_rust_struct;
use structs::read_blob_input::get_read_blob_input_rust_struct;
use structs::order_input::generate_order_input_rust_structs;
use structs::update_input::generate_update_input_rust_structs;
use structs::delete_input::generate_delete_input_rust_structs;
use structs::upsert_input::generate_upsert_input_rust_structs;
use enums::enum_type::generate_enums;
use query_resolvers::read::generate_read_query_resolvers;
use mutation_resolvers::create::generate_create_mutation_resolvers;
use mutation_resolvers::update::generate_update_mutation_resolvers;
use mutation_resolvers::delete::generate_delete_mutation_resolvers;
use mutation_resolvers::upsert::generate_upsert_mutation_resolvers;
use mutation_resolvers::init::generate_init_mutation_resolvers;
use settings::generate_settings::{
    generate_export_generated_query_function_attribute,
    generate_export_generated_mutation_function_attribute,
    generate_export_generated_init_function_attribute,
    generate_export_generated_post_upgrade_function_attribute,
    generate_clear_mutation
};
use custom_resolvers::{
    generate_custom_query_struct::{
        generate_merged_query_object_names,
        generate_custom_query_struct
    },
    generate_custom_mutation_struct::{
        generate_merged_mutation_object_names,
        generate_custom_mutation_struct
    }
};

#[proc_macro]
pub fn graphql_database(schema_file_path_token_stream: TokenStream) -> TokenStream {
    let schema_file_path_string_literal = parse_macro_input!(schema_file_path_token_stream as LitStr);
    let schema_file_path_string_value = schema_file_path_string_literal.value();

    // TODO some of this cwd strangeness is here just so that the canister is forced to recompile when the GraphQL schema file changes
    // TODO Hopefully this issue will help solve this more elegantly:https://users.rust-lang.org/t/logging-file-dependency-like-include-bytes-in-custom-macro/57441
    // TODO more information: https://github.com/rust-lang/rust/pull/24423
    // TODO more information: https://stackoverflow.com/questions/58768109/proper-way-to-handle-a-compile-time-relevant-text-file-passed-to-a-procedural-ma
    // TODO const temp: &str = include_str!(#schema_absolute_file_path_string); below is related to this as well
    // TODO whenever the schema file changes, include_str! somehow makes it so that the create will recompile, which is what we want!
    // TODO it would be nice if there were a simpler or more standard way to accomplish this
    let cwd = std::env::current_dir().expect("graphql_database::cwd");
    let schema_absolute_file_path = cwd.join(&schema_file_path_string_value);
    let schema_absolute_file_path_string_option = schema_absolute_file_path.to_str();
    let schema_absolute_file_path_string = schema_absolute_file_path_string_option.unwrap();

    let schema_file_contents = fs::read_to_string(&schema_absolute_file_path_string).unwrap();

    let graphql_ast = parse_schema::<String>(&schema_file_contents).unwrap();

    let all_object_types = get_object_types(
        &graphql_ast
    );

    let sudograph_settings_option = all_object_types.iter().find(|object_type| {
        return object_type.name == "SudographSettings";
    });

    let export_generated_query_function_attribute = generate_export_generated_query_function_attribute(sudograph_settings_option);
    let export_generated_mutation_function_attribute = generate_export_generated_mutation_function_attribute(sudograph_settings_option);
    let export_generated_init_function_attribute = generate_export_generated_init_function_attribute(sudograph_settings_option);
    let export_generated_post_upgrade_function_attribute = generate_export_generated_post_upgrade_function_attribute(sudograph_settings_option);

    let clear_mutation = generate_clear_mutation(sudograph_settings_option);

    let query_object_option = all_object_types.iter().find(|object_type| {
        return object_type.name == "Query";
    });

    let mutation_object_option = all_object_types.iter().find(|object_type| {
        return object_type.name == "Mutation";
    });

    let generated_custom_query_struct = generate_custom_query_struct(query_object_option);
    let generated_merged_query_object_names = generate_merged_query_object_names(query_object_option);

    let generated_custom_mutation_struct = generate_custom_mutation_struct(mutation_object_option);
    let generated_merged_mutation_object_names = generate_merged_mutation_object_names(mutation_object_option);

    let object_types = all_object_types.into_iter().filter(|object_type| {
        return
            object_type.name != "SudographSettings" &&
            object_type.name != "Query" &&
            object_type.name != "Mutation";
    }).collect();

    let generated_object_type_structs = generate_object_type_structs(
        &graphql_ast,
        &object_types
    );

    let generated_create_input_structs = generate_create_input_rust_structs(
        &graphql_ast,
        &object_types
    );

    let generated_read_input_structs = generate_read_input_rust_structs(
        &graphql_ast,
        &object_types
    );

    let read_boolean_input_rust_struct = get_read_boolean_input_rust_struct();
    let read_date_input_rust_struct = get_read_date_input_rust_struct();
    let read_float_input_rust_struct = get_read_float_input_rust_struct();
    let read_id_input_rust_struct = get_read_id_input_rust_struct();
    let read_int_input_rust_struct = get_read_int_input_rust_struct();
    let read_string_input_rust_struct = get_read_string_input_rust_struct();
    let read_enum_input_rust_struct = get_read_enum_input_rust_struct();
    let read_relation_input_rust_struct = get_read_relation_input_rust_struct();
    let read_json_input_rust_struct = get_read_json_input_rust_struct();
    let read_blob_input_rust_struct = get_read_blob_input_rust_struct();

    let generated_order_input_structs = generate_order_input_rust_structs(
        &graphql_ast,
        &object_types
    );

    let generated_update_input_structs = generate_update_input_rust_structs(
        &graphql_ast,
        &object_types
    );

    let generated_delete_input_structs = generate_delete_input_rust_structs(&object_types);

    let generated_upsert_input_structs = generate_upsert_input_rust_structs(
        &graphql_ast,
        &object_types
    );

    let enum_types = get_enum_types(&graphql_ast);

    let generated_enums = generate_enums(&enum_types);

    let generated_query_resolvers = generate_read_query_resolvers(&object_types);

    let generated_create_mutation_resolvers = generate_create_mutation_resolvers(&object_types);
    let generated_update_mutation_resolvers = generate_update_mutation_resolvers(&object_types);
    let generated_delete_mutation_resolvers = generate_delete_mutation_resolvers(&object_types);

    let generated_upsert_mutation_resolvers = generate_upsert_mutation_resolvers(
        &graphql_ast,
        &object_types
    );

    let generated_init_mutation_resolvers = generate_init_mutation_resolvers(
        &graphql_ast,
        &object_types
    );

    let generated_init_mutations = object_types.iter().fold(String::from(""), |result, object_type| {
        let object_type_name = &object_type.name;
        
        let init_function_name = String::from("init") + object_type_name;

        return result + &init_function_name + "\n";
    });

    let gen = quote! {
        use sudograph::serde::{
            Deserialize,
            Serialize,
            self
        };
        use sudograph::async_graphql;
        use sudograph::async_graphql::{
            SimpleObject,
            InputObject,
            Object,
            MaybeUndefined,
            Schema,
            EmptySubscription,
            scalar,
            Variables,
            Request,
            Enum,
            MergedObject,
            Scalar
        };
        use sudograph::sudodb::{
            ObjectTypeStore,
            create,
            read,
            update,
            delete,
            init_object_type,
            FieldTypeInput,
            FieldType,
            FieldInput,
            FieldValue,
            FieldValueScalar,
            FieldValueRelationMany,
            FieldValueRelationOne,
            ReadInput,
            ReadInputType,
            ReadInputOperation,
            FieldTypeRelationInfo,
            SelectionSet,
            SelectionSetInfo,
            OrderInput,
            UpdateOperation
        };
        use sudograph::serde_json::from_str;
        use sudograph::ic_cdk;
        use sudograph::ic_cdk::storage;
        use sudograph::to_json_string;
        use sudograph::ic_print;
        use sudograph::ic_cdk_macros::{
            query,
            update,
            init,
            post_upgrade,
            import
        };
        use std::error::Error;
        use std::collections::{
            BTreeMap,
            HashMap
        };
        use sudograph::rand::{
            Rng,
            SeedableRng,
            rngs::StdRng
        };
        // use sudograph::ic_cdk::export::candid::CandidType; // TODO reenable https://github.com/sudograph/sudograph/issues/123

        // TODO this is just to test out storing a source of randomness per update call
        // TODO the best way I believe would to somehow
        // TODO use the standard randomness ways of getting randomness
        // TODO used in the random crates...I think we would have to implement some
        // TODO random trait or something for the IC architecture
        // TODO second best would be if DFINITY were to implement a synchronous way of getting
        // TODO raw randomness from the IC environment
        // TODO third best is to use an async call to get randomness from the management canister
        // TODO but for now there are issues with asynchronous calls from within graphql resolvers
        type RandStore = BTreeMap<String, StdRng>;

        const temp: &str = include_str!(#schema_absolute_file_path_string);

        // We are creating our own custom ID scalar so that we can derive the Default trait
        // Default traits are needed so that serde has default values when the selection set
        // Does not provide all required values
        #[derive(
            Serialize,
            Deserialize,
            Default,
            Clone,
            Debug,
            // CandidType // TODO reenable https://github.com/sudograph/sudograph/issues/123
        )]
        // #[candid_path("::sudograph::ic_cdk::export::candid")] TODO reenable once https://github.com/dfinity/candid/issues/248 is released
        #[serde(crate="self::serde")]
        struct ID(String);

        impl ID {
            fn to_string(&self) -> String {
                return String::from(&self.0);
            }
        }

        scalar!(ID);

        #[derive(
            Serialize,
            Deserialize,
            Default,
            Clone,
            Debug,
            // CandidType // TODO reenable https://github.com/sudograph/sudograph/issues/123
        )]
        // #[candid_path("::sudograph::ic_cdk::export::candid")] TODO reenable once https://github.com/dfinity/candid/issues/248 is released
        #[serde(crate="self::serde")]
        struct Date(String);

        scalar!(Date);

        #[derive(
            Serialize,
            Deserialize,
            Default,
            Clone,
            Debug,
            // CandidType // TODO reenable https://github.com/sudograph/sudograph/issues/123
        )]
        // #[candid_path("::sudograph::ic_cdk::export::candid")] TODO reenable once https://github.com/dfinity/candid/issues/248 is released
        #[serde(crate="self::serde")]
        struct Blob(Vec<u8>);

        #[Scalar]
        impl sudograph::async_graphql::ScalarType for Blob {
            fn parse(value: sudograph::async_graphql::Value) -> sudograph::async_graphql::InputValueResult<Self> {
                match value {
                    sudograph::async_graphql::Value::String(value_string) => {
                        return Ok(Blob(value_string.into_bytes()));
                    },
                    sudograph::async_graphql::Value::List(value_list) => {
                        return Ok(Blob(value_list.iter().map(|item| {
                            match item {
                                // sudograph::async_graphql::Value::String(item_string) => {
                                    // TODO should we implement this too?
                                // },
                                sudograph::async_graphql::Value::Number(item_number) => {
                                    return item_number.as_u64().expect("should be a u64") as u8; // TODO potentially unsafe conversion here
                                },
                                _ => panic!("incorrect value") // TODO return an error explaining that a utf-8 encoded string is the only acceptable input
                            };
                        }).collect()));
                    },
                    _ => panic!("incorrect value") // TODO return an error explaining that a utf-8 encoded string is the only acceptable input
                };
            }

            fn to_value(&self) -> sudograph::async_graphql::Value {
                return sudograph::async_graphql::Value::List((&self.0).iter().map(|item_u8| {
                    return sudograph::async_graphql::Value::Number(sudograph::async_graphql::Number::from_f64(*item_u8 as f64).expect("should be able to convert to f64"));
                }).collect());
            }
        }

        // TODO each object type and each field will probably need their own relation inputs
        // TODO the relation inputs are going to have connect, disconnect, create, update, delete, etc
        #[derive(InputObject, Default, Debug)]
        struct CreateRelationManyInput {
            connect: Vec<ID>
        }

        #[derive(InputObject, Default, Debug)]
        struct CreateRelationOneInput {
            connect: ID
        }

        #[derive(InputObject)]
        struct UpdateRelationManyInput {
            connect: Option<Vec<ID>>,
            disconnect: Option<Vec<ID>>
        }

        #[derive(InputObject)]
        struct UpdateNullableRelationOneInput {
            connect: Option<ID>,
            disconnect: Option<bool>
        }

        #[derive(InputObject)]
        struct UpdateNonNullableRelationOneInput {
            connect: ID
        }

        #[derive(Enum, Copy, Clone, Eq, PartialEq)]
        enum OrderDirection {
            ASC,
            DESC
        }

        #[derive(InputObject)]
        struct UpdateBlobInput {
            replace: MaybeUndefined<Blob>,
            append: Option<Blob>
            // prepend: Option<Blob> // TODO going to wait on implementing this for now
        }

        #read_boolean_input_rust_struct
        #read_date_input_rust_struct
        #read_float_input_rust_struct
        #read_id_input_rust_struct
        #read_int_input_rust_struct
        #read_string_input_rust_struct
        #read_enum_input_rust_struct
        #read_relation_input_rust_struct
        #read_json_input_rust_struct
        #read_blob_input_rust_struct

        #(#generated_object_type_structs)*
        #(#generated_create_input_structs)*
        #(#generated_read_input_structs)*
        #(#generated_order_input_structs)*
        #(#generated_update_input_structs)*
        #(#generated_delete_input_structs)*
        // #(#generated_upsert_input_structs)*

        #(#generated_enums)*

        // TODO consider renaming this to something besides serialize
        trait SudoSerialize {
            fn sudo_serialize(&self) -> FieldValue;
        }

        impl SudoSerialize for bool {
            fn sudo_serialize(&self) -> FieldValue {
                return FieldValue::Scalar(Some(FieldValueScalar::Boolean(self.clone())));
            }
        }

        impl SudoSerialize for f32 {
            fn sudo_serialize(&self) -> FieldValue {
                return FieldValue::Scalar(Some(FieldValueScalar::Float(self.clone())));
            }
        }

        impl SudoSerialize for ID {
            fn sudo_serialize(&self) -> FieldValue {
                // TODO I do not think we actually need the to_string method anymore, ID is a tuple struct I believe
                return FieldValue::Scalar(Some(FieldValueScalar::String(self.to_string())));
            }
        }

        impl SudoSerialize for Date {
            fn sudo_serialize(&self) -> FieldValue {
                return FieldValue::Scalar(Some(FieldValueScalar::Date(String::from(&self.0))));
            }
        }

        impl SudoSerialize for i32 {
            fn sudo_serialize(&self) -> FieldValue {
                return FieldValue::Scalar(Some(FieldValueScalar::Int(self.clone())));
            }
        }

        impl SudoSerialize for String {
            fn sudo_serialize(&self) -> FieldValue {
                return FieldValue::Scalar(Some(FieldValueScalar::String(self.clone())));
            }
        }

        impl SudoSerialize for sudograph::serde_json::Value {
            fn sudo_serialize(&self) -> FieldValue {
                return FieldValue::Scalar(Some(FieldValueScalar::JSON(self.to_string())));
            }
        }

        impl SudoSerialize for Blob {
            fn sudo_serialize(&self) -> FieldValue {
                return FieldValue::Scalar(Some(FieldValueScalar::Blob((&self.0).to_vec())));
            }
        }

        impl<T: SudoSerialize> SudoSerialize for Option<T> {
            fn sudo_serialize(&self) -> FieldValue {
                match self {
                    Some(value) => {
                        return value.sudo_serialize();
                    },
                    None => {
                        return FieldValue::Scalar(None);
                    }
                }
            }
        }

        // TODO we might want to make sure we explicitly path everything...I am not quite sure
        // TODO why Default here is able to be used, becuase I believe it come from async-graphql
        // TODO and I am not importing it
        #[derive(Default)]
        pub struct GeneratedQuery;

        #[Object]
        impl GeneratedQuery {
            #(#generated_query_resolvers)*
        }

        #generated_custom_query_struct

        #[derive(MergedObject, Default)]
        struct Query(
            #(#generated_merged_query_object_names),*
        );

        #[derive(Default)]
        pub struct GeneratedMutation;

        #[Object]
        impl GeneratedMutation {
            #(#generated_create_mutation_resolvers)*
            #(#generated_update_mutation_resolvers)*
            #(#generated_delete_mutation_resolvers)*
            // #(#generated_upsert_mutation_resolvers)*
            #(#generated_init_mutation_resolvers)*
            #clear_mutation

            // TODO obviously this is an extremely horrible and dangerous thing
            // TODO perhaps only enable it in testing, or at least
            // TODO create a Sudograph setting that you must explicitly enable to allow this
            // async fn clear(&self) -> std::result::Result<bool, sudograph::async_graphql::Error> {
            //     let object_store = storage::get_mut::<ObjectTypeStore>();

            //     sudograph::sudodb::clear(object_store);

            //     return Ok(true);
            // }
        }

        #generated_custom_mutation_struct

        #[derive(MergedObject, Default)]
        struct Mutation(
            #(#generated_merged_mutation_object_names),*
        );

        #export_generated_query_function_attribute
        async fn graphql_query(query_string: String, variables_json_string: String) -> String {
            
            // TODO create a sudograph setting for logs
            // ic_cdk::println!("query_string: {}", query_string);
            // ic_cdk::println!("variables_json_string: {}", variables_json_string);

            // TODO figure out how to create global variable to store the schema in
            // TODO we can probably just store this in a map or something with ic storage
            let schema = Schema::new(
                Query::default(),
                Mutation::default(),
                EmptySubscription
            );

            // ic_cdk::println!("{}", schema.federation_sdl());

            // TODO sudosettings should turn these on and off
            // TODO it would be nice to print these out prettily
            // TODO also, it would be nice to turn off these kinds of logs
            // TODO I am thinking about having directives on the type Query set global things
            // ic_cdk::println!("query_string: {:?}", query_string);
            // ic_cdk::println!("variables_json_string: {:?}", variables_json_string);

            let request = Request::new(query_string).variables(Variables::from_json(sudograph::serde_json::from_str(&variables_json_string).expect("This should work")));

            let response = schema.execute(request).await;

            let json_result = to_json_string(&response);

            return json_result.expect("This should work");
        }

        #export_generated_mutation_function_attribute
        async fn graphql_mutation(mutation_string: String, variables_json_string: String) -> String {
            // TODO create a sudograph setting for logs
            // ic_cdk::println!("mutation_string: {}", mutation_string);
            // ic_cdk::println!("variables_json_string: {}", variables_json_string);

            let rand_store = storage::get_mut::<RandStore>();

            let rng_option = rand_store.get("RNG");

            if rng_option.is_none() {
                // TODO it seems it would be best to just do this once in the init function, but there is an error: https://forum.dfinity.org/t/cant-do-cross-canister-call-in-init-function/5187
                // TODO I think this cross-canister call is making the mutations take forever
                // TODO once the async types are fixed in ic_cdk, update and we should be able to move the randomness into the
                // TODO create resolver itself, so only it will need to do this call and take forever to do so
                // TODO and we should be able to get it to be only the first create
                let call_result: Result<(Vec<u8>,), _> = ic_cdk::api::call::call(ic_cdk::export::Principal::management_canister(), "raw_rand", ()).await;
    
                if let Ok(result) = call_result {
                    let rand_store = storage::get_mut::<RandStore>();
    
                    let randomness = result.0;
    
                    let mut rng: StdRng = SeedableRng::from_seed(randomness_vector_to_array(randomness));
    
                    rand_store.insert(String::from("RNG"), rng);
                }
            }

            // TODO figure out how to create global variable to store the schema in
            let schema = Schema::new(
                Query::default(),
                Mutation::default(),
                EmptySubscription
            );

            ic_print("graphql_mutation");

            let request = Request::new(mutation_string).variables(Variables::from_json(sudograph::serde_json::from_str(&variables_json_string).expect("This should work")));

            let response = schema.execute(request).await;

            // TODO create a sudograph setting for logs
            // ic_cdk::println!("response: {:?}", response);

            let json_result = to_json_string(&response).expect("This should work");

            // TODO create a sudograph setting for logs
            // ic_cdk::println!("json_result {}", &json_result);

            return json_result;
        }

        #export_generated_init_function_attribute
        async fn init() {
            initialize_database_entities().await;
        }

        #export_generated_post_upgrade_function_attribute
        async fn post_upgrade() {
            initialize_database_entities().await;
        }

        async fn initialize_database_entities() {
            let schema = Schema::new(
                Query::default(),
                Mutation::default(),
                EmptySubscription
            );

            let response = schema.execute(format!("
                    mutation {{
                        {generated_init_mutations}
                    }}
                ",
                generated_init_mutations = #generated_init_mutations
            )).await;

            // TODO make this error print prettily
            if response.errors.len() > 0 {
                panic!("{:?}", response.errors);
            }
        }

        // TODO double-check the math
        // TODO there is no protection on lengths here...the IC will give us 32 bytes, so a vector of length 32 with u8 values
        fn randomness_vector_to_array(randomness: Vec<u8>) -> [u8; 32] {
            let mut array = [0u8; 32];

            for i in 0..randomness.len() {
                // if i > array.len() {
                //     break;
                // }

                array[i] = randomness[i];
            }

            return array;
        }

        fn convert_selection_field_to_selection_set(
            object_type_name: &str,
            selection_field: sudograph::async_graphql::context::SelectionField<'_>,
            selection_set: SelectionSet
        ) -> SelectionSet {
            let selection_fields: Vec<sudograph::async_graphql::context::SelectionField<'_>> = selection_field.selection_set().collect();

            if selection_fields.len() == 0 {
                return selection_set;
            }

            // TODO we should probably also put this at the top level of the resolvers so that we do not parse it so many times
            // TODO But I need to figure out how to get the schema_file_contents down to the resolvers
            // TODO best way might be to use context data from the top level functions
            let graphql_ast = sudograph::graphql_parser::schema::parse_schema::<String>(#schema_file_contents).unwrap();

            let mut hash_map = HashMap::new();

            for selection_field in selection_fields {
                // TODO this is not exactly the object type name in all cases, but if the field is a scalar
                // TODO I am thinking it should not matter
                let child_type_name = get_type_name_for_object_type_name_and_field_name(
                    &graphql_ast,
                    object_type_name,
                    selection_field.name()
                );

                let child_selection_set = convert_selection_field_to_selection_set(
                    &child_type_name,
                    selection_field,
                    SelectionSet(None)
                );

                let child_selection_set_info = SelectionSetInfo {
                    selection_set: child_selection_set,
                    search_inputs: get_search_inputs_from_selection_field(
                        &graphql_ast,
                        object_type_name,
                        selection_field
                    ),
                    limit_option: get_limit_option_from_selection_field(selection_field),
                    offset_option: get_offset_option_from_selection_field(selection_field),
                    order_inputs: get_order_inputs_from_selection_field(selection_field)
                };

                hash_map.insert(String::from(selection_field.name()), child_selection_set_info);
            }

            return SelectionSet(Some(hash_map));
        }

        fn get_search_inputs_from_selection_field(
            graphql_ast: &sudograph::graphql_parser::schema::Document<String>,
            object_type_name: &str,
            selection_field: sudograph::async_graphql::context::SelectionField<'_>
        ) -> Vec<ReadInput> {            
            match selection_field.arguments() {
                Ok(arguments) => {
                    let search_argument_option = arguments.iter().find(|argument| {
                        return argument.0.as_str() == "search";
                    });

                    match search_argument_option {
                        Some(search_argument) => {
                            let relation_object_type_name = get_type_name_for_object_type_name_and_field_name(
                                graphql_ast,
                                object_type_name,
                                selection_field.name()
                            );

                            return get_search_inputs_from_value(
                                graphql_ast,
                                &relation_object_type_name,
                                &search_argument.1
                            )
                            .into_iter()
                            .flatten()
                            .collect();
                        },
                        None => {
                            return vec![];
                        }
                    };
                },
                _ => {
                    // TODO we might want to return the err result up here
                    return vec![];
                }
            };
        }

        // TODO not sure if this should be from an object value in particular or just a value
        fn get_search_inputs_from_value(
            graphql_ast: &sudograph::graphql_parser::schema::Document<String>,
            object_type_name: &str,
            value: &sudograph::async_graphql::Value
        ) -> Vec<Vec<ReadInput>> {
            match value {
                sudograph::async_graphql::Value::Object(object) => {
                    let search_inputs = object.keys().fold(vec![], |mut result, object_key| {
                        let object_value = object.get(object_key).expect("get_search_inputs_from_value::object_value");

                        if object_key == "and" {
                            result.push(vec![ReadInput {
                                input_type: ReadInputType::Scalar,
                                input_operation: ReadInputOperation::Equals,
                                field_name: String::from("and"),
                                field_value: FieldValue::Scalar(None),
                                relation_object_type_name: String::from(""),
                                relation_read_inputs: vec![],
                                and: match object_value {
                                    sudograph::async_graphql::Value::List(list) => list.iter().flat_map(|value| { get_search_inputs_from_value(
                                        graphql_ast,
                                        object_type_name,
                                        value
                                    )
                                    .into_iter()
                                    .flatten()
                                    .collect::<Vec<ReadInput>>() }).collect(),
                                    sudograph::async_graphql::Value::Object(_) => {
                                        get_search_inputs_from_value(
                                            graphql_ast,
                                            object_type_name,
                                            object_value
                                        )
                                        .into_iter()
                                        .flatten()
                                        .collect()
                                    },
                                    _ => panic!("panic for and")
                                },
                                or: vec![]
                            }]);

                            return result;
                        }

                        if object_key == "or" {
                            match object_value {
                                sudograph::async_graphql::Value::List(list) => {
                                    for value in list {
                                        result.push(
                                            vec![
                                                ReadInput {
                                                    input_type: ReadInputType::Scalar,
                                                    input_operation: ReadInputOperation::Equals,
                                                    field_name: String::from("or"),
                                                    field_value: FieldValue::Scalar(None),
                                                    relation_object_type_name: String::from(""),
                                                    relation_read_inputs: vec![],
                                                    and: vec![],
                                                    or: get_search_inputs_from_value(
                                                            graphql_ast,
                                                            object_type_name,
                                                            value
                                                        )
                                                        .into_iter()
                                                        .map(|read_inputs| {
                                                            return ReadInput {
                                                                input_type: ReadInputType::Scalar,
                                                                input_operation: ReadInputOperation::Equals,
                                                                field_name: String::from("and"),
                                                                field_value: FieldValue::Scalar(None),
                                                                relation_object_type_name: String::from(""),
                                                                relation_read_inputs: vec![],
                                                                and: read_inputs,
                                                                or: vec![]
                                                            };
                                                        })
                                                        .collect()
                                                }
                                            ]
                                        );
                                    }
                                },
                                sudograph::async_graphql::Value::Object(_) => {
                                    result.push(
                                        vec![
                                            ReadInput {
                                                input_type: ReadInputType::Scalar,
                                                input_operation: ReadInputOperation::Equals,
                                                field_name: String::from("or"),
                                                field_value: FieldValue::Scalar(None),
                                                relation_object_type_name: String::from(""),
                                                relation_read_inputs: vec![],
                                                and: vec![],
                                                or: get_search_inputs_from_value(
                                                        graphql_ast,
                                                        object_type_name,
                                                        object_value
                                                    )
                                                    .into_iter()
                                                    .map(|read_inputs| {
                                                        return ReadInput {
                                                            input_type: ReadInputType::Scalar,
                                                            input_operation: ReadInputOperation::Equals,
                                                            field_name: String::from("and"),
                                                            field_value: FieldValue::Scalar(None),
                                                            relation_object_type_name: String::from(""),
                                                            relation_read_inputs: vec![],
                                                            and: read_inputs,
                                                            or: vec![]
                                                        };
                                                    })
                                                    .collect()
                                            }
                                        ]
                                    );
                                },
                                _ => panic!()
                            };


                            return result;
                        }

                        let field = get_field_for_object_type_name_and_field_name(
                            graphql_ast,
                            object_type_name,
                            object_key
                        );

                        if
                            is_graphql_type_a_relation_many(
                                graphql_ast,
                                &field.field_type
                            ) == true ||
                            is_graphql_type_a_relation_one(
                                graphql_ast,
                                &field.field_type
                            ) == true
                        {
                            let relation_object_type_name = get_field_type_name(&field);

                            result.push(vec![ReadInput {
                                input_type: ReadInputType::Relation,
                                input_operation: ReadInputOperation::Equals,
                                field_name: object_key.to_string(),
                                field_value: FieldValue::Scalar(None),
                                relation_object_type_name: String::from(&relation_object_type_name),
                                relation_read_inputs: get_search_inputs_from_value(
                                    graphql_ast,
                                    &relation_object_type_name,
                                    object_value
                                )
                                .into_iter()
                                .flatten()
                                .collect(),
                                and: vec![],
                                or: vec![]
                            }]);

                            return result;
                        }
                        else {
                            match object_value {
                                sudograph::async_graphql::Value::Object(scalar_object) => {
                                    let scalar_search_inputs: Vec<ReadInput> = scalar_object.keys().map(|scalar_object_key| {
                                        let scalar_object_value = scalar_object.get(scalar_object_key).unwrap();
                                        
                                        let input_operation = match scalar_object_key.as_str() {
                                            "eq" => ReadInputOperation::Equals,
                                            "gt" => ReadInputOperation::GreaterThan,
                                            "gte" => ReadInputOperation::GreaterThanOrEqualTo,
                                            "lt" => ReadInputOperation::LessThan,
                                            "lte" => ReadInputOperation::LessThanOrEqualTo,
                                            "contains" => ReadInputOperation::Contains,
                                            "startsWith" => ReadInputOperation::StartsWith,
                                            "endsWith" => ReadInputOperation::EndsWith,
                                            _ => panic!()
                                        };

                                        let graphql_type_name = get_graphql_type_name(&field.field_type);

                                        // TODO this will get more difficult once we introduce custom scalars
                                        let field_value = match graphql_type_name.as_str() {
                                            "Blob" => match scalar_object_value {
                                                sudograph::async_graphql::Value::String(value_string) => FieldValue::Scalar(Some(FieldValueScalar::Blob(value_string.clone().into_bytes()))),
                                                sudograph::async_graphql::Value::List(value_list) => FieldValue::Scalar(Some(FieldValueScalar::Blob(value_list.iter().map(|item| {
                                                    match item {
                                                        // sudograph::async_graphql::Value::String(item_string) => {
                                                            // TODO should we implement this too?
                                                        // },
                                                        sudograph::async_graphql::Value::Number(item_number) => {
                                                            return item_number.as_u64().expect("should be a u64") as u8; // TODO potentially unsafe conversion here
                                                        },
                                                        _ => panic!("incorrect value") // TODO return an error explaining that a utf-8 encoded string is the only acceptable input
                                                    };
                                                }).collect()))),
                                                sudograph::async_graphql::Value::Null => FieldValue::Scalar(None),
                                                _ => panic!() // TODO return an error explaining that a utf-8 encoded string is the only acceptable input
                                            },
                                            "Boolean" => match scalar_object_value {
                                                sudograph::async_graphql::Value::Boolean(boolean) => FieldValue::Scalar(Some(FieldValueScalar::Boolean(boolean.clone()))),
                                                sudograph::async_graphql::Value::Null => FieldValue::Scalar(None),
                                                _ => panic!()
                                            },
                                            "Date" => match scalar_object_value {
                                                sudograph::async_graphql::Value::String(date_string) => FieldValue::Scalar(Some(FieldValueScalar::Date(date_string.to_string()))),
                                                sudograph::async_graphql::Value::Null => FieldValue::Scalar(None),
                                                _ => panic!()
                                            },
                                            "Float" => match scalar_object_value {
                                                sudograph::async_graphql::Value::Number(number) => FieldValue::Scalar(Some(FieldValueScalar::Float(number.as_f64().unwrap() as f32))),
                                                sudograph::async_graphql::Value::Null => FieldValue::Scalar(None),
                                                _ => panic!()
                                            },
                                            "ID" => match scalar_object_value {
                                                sudograph::async_graphql::Value::String(id_string) => FieldValue::Scalar(Some(FieldValueScalar::String(id_string.to_string()))),
                                                sudograph::async_graphql::Value::Null => FieldValue::Scalar(None),
                                                _ => panic!()
                                            },
                                            "Int" => match scalar_object_value {
                                                sudograph::async_graphql::Value::Number(number) => FieldValue::Scalar(Some(FieldValueScalar::Int(number.as_i64().unwrap() as i32))),
                                                sudograph::async_graphql::Value::Null => FieldValue::Scalar(None),
                                                _ => panic!()
                                            },
                                            "JSON" => match scalar_object_value {
                                                sudograph::async_graphql::Value::String(string) => FieldValue::Scalar(Some(FieldValueScalar::JSON(string.to_string()))),
                                                sudograph::async_graphql::Value::Null => FieldValue::Scalar(None),
                                                _ => panic!()
                                            },
                                            "String" => match scalar_object_value {
                                                sudograph::async_graphql::Value::String(string) => FieldValue::Scalar(Some(FieldValueScalar::String(string.to_string()))),
                                                sudograph::async_graphql::Value::Null => FieldValue::Scalar(None),
                                                _ => panic!()
                                            },
                                            _ => panic!("this scalar is not defined")
                                        };

                                        return ReadInput {
                                            input_type: ReadInputType::Scalar,
                                            input_operation: input_operation,
                                            field_name: object_key.to_string(),
                                            field_value,
                                            relation_object_type_name: String::from(""),
                                            relation_read_inputs: vec![],
                                            and: vec![],
                                            or: vec![]
                                        };
                                    }).collect();

                                    result.push(scalar_search_inputs);

                                    return result;
                                },
                                _ => {
                                    panic!();
                                }
                            };
                        }
                    });

                    return search_inputs;
                },
                _ => {
                    panic!(); // TODO probably return a result instead, I am getting really lazy with this
                }
            }
        }

        fn get_type_name_for_object_type_name_and_field_name(
            graphql_ast: &sudograph::graphql_parser::schema::Document<String>,
            object_type_name: &str,
            field_name: &str
        ) -> String {
            let object_type = get_object_type(
                graphql_ast,
                object_type_name
            );
            let field = get_field(
                &object_type,
                field_name
            );
            let field_type_name = get_field_type_name(&field);

            return field_type_name;
        }

        fn get_field_for_object_type_name_and_field_name<'a>(
            graphql_ast: &sudograph::graphql_parser::schema::Document<'a, String>,
            object_type_name: &str,
            field_name: &str
        ) -> sudograph::graphql_parser::schema::Field<'a, String> {
            let object_type = get_object_type(
                graphql_ast,
                object_type_name
            );
            let field = get_field(
                &object_type,
                field_name
            );

            return field;
        }

        fn get_object_types<'a>(graphql_ast: &sudograph::graphql_parser::schema::Document<'a, String>) -> Vec<sudograph::graphql_parser::schema::ObjectType<'a, String>> {
            let type_definitions: Vec<sudograph::graphql_parser::schema::TypeDefinition<String>> = graphql_ast.definitions.iter().filter_map(|definition| {
                match definition {
                    sudograph::graphql_parser::schema::Definition::TypeDefinition(type_definition) => {
                        return Some(type_definition.clone());
                    },
                    _ => {
                        return None;
                    }
                };
            }).collect();
        
            let object_types = type_definitions.into_iter().filter_map(|type_definition| {
                match type_definition {
                    sudograph::graphql_parser::schema::TypeDefinition::Object(object_type) => {
                        return Some(object_type);
                    },
                    _ => {
                        return None;
                    }
                }
            }).collect();
        
            return object_types;
        }

        fn get_object_type<'a>(
            graphql_ast: &sudograph::graphql_parser::schema::Document<'a, String>,
            object_type_name: &str
        ) -> sudograph::graphql_parser::schema::ObjectType<'a, String> {
            let object_types = get_object_types(graphql_ast);
            let object_type = object_types.iter().find(|object_type| {
                return object_type.name == object_type_name;
            }).expect("get_object_type::object_type");

            return object_type.clone();
        }

        fn get_field<'a>(
            object_type: &sudograph::graphql_parser::schema::ObjectType<'a, String>,
            field_name: &str
        ) -> sudograph::graphql_parser::schema::Field<'a, String> {
            // ic_cdk::println!("object_type {:?}", object_type);
            // ic_cdk::println!("object_type {}", field_name);
            return object_type.fields.iter().find(|field| {
                return field.name == field_name;
            }).expect("get_field").clone(); // TODO instead of returning these types of clones, returning references might be better since the AST stuff is read-only
        }

        fn get_field_type_name(
            field: &sudograph::graphql_parser::schema::Field<String>
        ) -> String {
            return get_graphql_type_name(&field.field_type);
        }

        // TODO this is now copied inside and outside of the quote
        fn get_graphql_type_name(graphql_type: &sudograph::graphql_parser::schema::Type<String>) -> String {
            match graphql_type {
                sudograph::graphql_parser::schema::Type::NamedType(named_type) => {
                    return String::from(named_type);
                },
                sudograph::graphql_parser::schema::Type::NonNullType(non_null_type) => {
                    return get_graphql_type_name(non_null_type);
                },
                sudograph::graphql_parser::schema::Type::ListType(list_type) => {
                    return get_graphql_type_name(list_type);
                }
            };
        }

        fn get_limit_option_from_selection_field(selection_field: sudograph::async_graphql::context::SelectionField<'_>) -> Option<u32> {
            match selection_field.arguments() {
                Ok(arguments) => {
                    let limit_argument_option = arguments.iter().find(|argument| {
                        return argument.0.as_str() == "limit";
                    });

                    match limit_argument_option {
                        Some(limit_argument) => {
                            match &limit_argument.1 {
                                sudograph::async_graphql::Value::Number(number) => {
                                    match number.as_u64() {
                                        Some(number_u64) => {
                                            return Some(number_u64 as u32);
                                        },
                                        None => {
                                            return None;
                                        }
                                    };
                                },
                                _ => {
                                    return None; // TODO we should probably return an error here
                                }
                            };
                        },
                        None => {
                            return None;
                        }
                    };
                },
                _ => {
                    // TODO should we panic or something here?
                    // TODO we should probably return the result up the chain
                    return None;
                }
            };
        }

        fn get_offset_option_from_selection_field(selection_field: sudograph::async_graphql::context::SelectionField<'_>) -> Option<u32> {
            match selection_field.arguments() {
                Ok(arguments) => {
                    let limit_argument_option = arguments.iter().find(|argument| {
                        return argument.0.as_str() == "offset";
                    });

                    match limit_argument_option {
                        Some(limit_argument) => {
                            match &limit_argument.1 {
                                sudograph::async_graphql::Value::Number(number) => {
                                    match number.as_u64() {
                                        Some(number_u64) => {
                                            return Some(number_u64 as u32);
                                        },
                                        None => {
                                            return None;
                                        }
                                    };
                                },
                                _ => {
                                    return None; // TODO we should probably return an error here
                                }
                            };
                        },
                        None => {
                            return None;
                        }
                    };
                },
                _ => {
                    // TODO should we panic or something here?
                    // TODO we should probably return the result up the chain
                    return None;
                }
            };
        }

        fn get_order_inputs_from_selection_field(selection_field: sudograph::async_graphql::context::SelectionField<'_>) -> Vec<sudograph::sudodb::OrderInput> {
            match selection_field.arguments() {
                Ok(arguments) => {
                    let order_argument_option = arguments.iter().find(|argument| {
                        return argument.0.as_str() == "order";
                    });

                    match order_argument_option {
                        Some(order_argument) => {
                            match &order_argument.1 {
                                sudograph::async_graphql::Value::Object(object) => {
                                    return object.keys().map(|key| {
                                        let value = object.get(key).expect("get_order_inputs_from_selection_field::value"); // TODO be better

                                        return sudograph::sudodb::OrderInput {
                                            field_name: String::from(key.as_str()),
                                            order_direction: match value {
                                                sudograph::async_graphql::Value::Enum(name) => {
                                                    if name.as_str() == "ASC" {
                                                        sudograph::sudodb::OrderDirection::ASC
                                                    }
                                                    // TODO to be really sure we should have an explicit branch for "DESC"
                                                    else {
                                                        sudograph::sudodb::OrderDirection::DESC
                                                    }
                                                },
                                                _ => panic!("bad")
                                            }
                                        };
                                    }).collect();
                                },
                                _ => {
                                    return vec![]; // TODO we should probably return an error here
                                }
                            };
                        },
                        None => {
                            return vec![];
                        }
                    };
                },
                _ => {
                    // TODO we might want to return the err result up here
                    return vec![];
                }
            };
        }

        fn get_field_arguments(
            context: &sudograph::async_graphql::Context<'_>,
            field_name: &str
        ) -> sudograph::async_graphql::ServerResult<Vec<(sudograph::async_graphql::Name, sudograph::async_graphql::Value)>> {
            let selection_field_option = context.field().selection_set().find(|selection_field| {
                return selection_field.name() == field_name;
            });

            match selection_field_option {
                Some(selection_field) => {
                    return selection_field.arguments();
                },
                None => {
                    return Ok(vec![]);
                }
            };
        }

        fn is_graphql_type_a_relation_many(
            graphql_ast: &sudograph::graphql_parser::schema::Document<String>,
            graphql_type: &sudograph::graphql_parser::schema::Type<String>
        ) -> bool {
            let object_types = get_object_types(graphql_ast);
            let graphql_type_name = get_graphql_type_name(graphql_type);
        
            let graphql_type_is_a_relation = object_types.iter().any(|object_type| {
                return object_type.name == graphql_type_name;
            });
        
            let graphql_type_is_a_list_type = is_graphql_type_a_list_type(
                graphql_ast,
                graphql_type
            );
        
            return 
                graphql_type_is_a_relation == true &&
                graphql_type_is_a_list_type == true
            ;
        }

        fn is_graphql_type_a_relation_one(
            graphql_ast: &sudograph::graphql_parser::schema::Document<String>,
            graphql_type: &sudograph::graphql_parser::schema::Type<String>
        ) -> bool {
            let object_types = get_object_types(graphql_ast);
            let graphql_type_name = get_graphql_type_name(graphql_type);
        
            let graphql_type_is_a_relation = object_types.iter().any(|object_type| {
                return object_type.name == graphql_type_name;
            });
        
            let graphql_type_is_a_list_type = is_graphql_type_a_list_type(
                graphql_ast,
                graphql_type
            );
        
            return 
                graphql_type_is_a_relation == true &&
                graphql_type_is_a_list_type == false
            ;
        }

        fn is_graphql_type_a_list_type(
            graphql_ast: &sudograph::graphql_parser::schema::Document<String>,
            graphql_type: &sudograph::graphql_parser::schema::Type<String>
        ) -> bool {
            match graphql_type {
                sudograph::graphql_parser::schema::Type::NamedType(_) => {
                    return false;
                },
                sudograph::graphql_parser::schema::Type::NonNullType(non_null_type) => {
                    return is_graphql_type_a_list_type(
                        graphql_ast,
                        non_null_type
                    );
                },
                sudograph::graphql_parser::schema::Type::ListType(_) => {
                    return true;
                }
            };
        }
    };

    return gen.into();
}

// TODO this is now copied inside and outside of the quote
// TODO many of the functions are copied, we need to organize this better
fn get_graphql_type_name(graphql_type: &Type<String>) -> String {
    match graphql_type {
        Type::NamedType(named_type) => {
            return String::from(named_type);
        },
        Type::NonNullType(non_null_type) => {
            return get_graphql_type_name(non_null_type);
        },
        Type::ListType(list_type) => {
            return get_graphql_type_name(list_type);
        }
    };
}

fn is_graphql_type_nullable(graphql_type: &Type<String>) -> bool {
    match graphql_type {
        Type::NonNullType(_) => {
            return false;
        },
        _ => {
            return true;
        }
    };
}

fn is_field_a_relation(
    graphql_ast: &Document<String>,
    field: &Field<String>
) -> bool {
    return
        is_graphql_type_a_relation_many(
            graphql_ast,
            &field.field_type
        ) == true ||
        is_graphql_type_a_relation_one(
            graphql_ast,
            &field.field_type
        ) == true;
}

fn is_graphql_type_a_relation_many(
    graphql_ast: &Document<String>,
    graphql_type: &Type<String>
) -> bool {
    let object_types = get_object_types(graphql_ast);
    let graphql_type_name = get_graphql_type_name(graphql_type);

    let graphql_type_is_a_relation = object_types.iter().any(|object_type| {
        return object_type.name == graphql_type_name;
    });

    let graphql_type_is_a_list_type = is_graphql_type_a_list_type(
        graphql_ast,
        graphql_type
    );

    return 
        graphql_type_is_a_relation == true &&
        graphql_type_is_a_list_type == true
    ;
}

fn is_graphql_type_a_relation_one(
    graphql_ast: &Document<String>,
    graphql_type: &Type<String>
) -> bool {
    let object_types = get_object_types(graphql_ast);
    let graphql_type_name = get_graphql_type_name(graphql_type);

    let graphql_type_is_a_relation = object_types.iter().any(|object_type| {
        return object_type.name == graphql_type_name;
    });

    let graphql_type_is_a_list_type = is_graphql_type_a_list_type(
        graphql_ast,
        graphql_type
    );

    return 
        graphql_type_is_a_relation == true &&
        graphql_type_is_a_list_type == false
    ;
}

fn is_graphql_type_an_enum(
    graphql_ast: &Document<String>,
    graphql_type: &Type<String>
) -> bool {
    let enum_types = get_enum_types(graphql_ast);
    let graphql_type_name = get_graphql_type_name(graphql_type);

    let graphql_type_is_an_enum = enum_types.iter().any(|enum_type| {
        return enum_type.name == graphql_type_name;
    });

    return graphql_type_is_an_enum;
}

fn is_graphql_type_a_blob(graphql_type: &Type<String>) -> bool {
    let graphql_type_name = get_graphql_type_name(graphql_type);
    
    return graphql_type_name == "Blob";
}

fn is_graphql_type_a_list_type(
    graphql_ast: &Document<String>,
    graphql_type: &Type<String>
) -> bool {
    match graphql_type {
        Type::NamedType(_) => {
            return false;
        },
        Type::NonNullType(non_null_type) => {
            return is_graphql_type_a_list_type(
                graphql_ast,
                non_null_type
            );
        },
        Type::ListType(_) => {
            return true;
        }
    };
}

fn get_object_types<'a>(graphql_ast: &Document<'a, String>) -> Vec<ObjectType<'a, String>> {
    let type_definitions: Vec<TypeDefinition<String>> = graphql_ast.definitions.iter().filter_map(|definition| {
        match definition {
            Definition::TypeDefinition(type_definition) => {
                return Some(type_definition.clone());
            },
            _ => {
                return None;
            }
        };
    }).collect();

    let object_types: Vec<ObjectType<String>> = type_definitions.into_iter().filter_map(|type_definition| {
        match type_definition {
            TypeDefinition::Object(object_type) => {
                return Some(object_type);
            },
            _ => {
                return None;
            }
        }
    }).collect();

    return object_types;
}

fn get_enum_types<'a>(graphql_ast: &Document<'a, String>) -> Vec<EnumType<'a, String>> {
    let type_definitions: Vec<TypeDefinition<String>> = graphql_ast.definitions.iter().filter_map(|definition| {
        match definition {
            Definition::TypeDefinition(type_definition) => {
                return Some(type_definition.clone());
            },
            _ => {
                return None;
            }
        };
    }).collect();

    let enum_types: Vec<EnumType<String>> = type_definitions.into_iter().filter_map(|type_definition| {
        match type_definition {
            TypeDefinition::Enum(enum_type) => {
                return Some(enum_type);
            },
            _ => {
                return None;
            }
        }
    }).collect();

    return enum_types;
}

// TODO this search needs to exclude the relation's own entity field...
// TODO you could have a relation to your same type, but you need to skip your original field
fn get_opposing_relation_field<'a>(
    graphql_ast: &'a Document<'a, String>,
    relation_field: &Field<String>
) -> Option<Field<'a, String>> {
    let relation_name = get_directive_argument_value_from_field(
        relation_field,
        "relation",
        "name"
    )?;

    let opposing_object_type_name = get_graphql_type_name(&relation_field.field_type);
    
    let object_types = get_object_types(graphql_ast);

    return object_types.iter().filter(|object_type| {
        return object_type.name == opposing_object_type_name; // TODO a find might make more sense than a filter
    }).fold(None, |_, object_type| {
        return object_type.fields.iter().fold(None, |result, field| {
            if result != None {
                return result;
            }

            let opposing_relation_name = get_directive_argument_value_from_field(
                field,
                "relation",
                "name"
            )?;

            if opposing_relation_name == relation_name {
                return Some(field.clone());
            }
            else {
                return result;
            }
        });
    });
}

fn get_directive_argument_value_from_field(
    field: &Field<String>,
    directive_name: &str,
    argument_name: &str
) -> Option<String> {
    let directive = field.directives.iter().find(|directive| {
        return directive.name == directive_name;
    })?;

    let argument = directive.arguments.iter().find(|argument| {
        return argument.0 == argument_name;
    })?;

    return Some(argument.1.to_string());
}

fn get_object_type_from_field<'a>(
    graphql_ast: &Document<'a, String>,
    field: &Field<String>
) -> Option<ObjectType<'a, String>> {
    let object_type_name = get_graphql_type_name(&field.field_type);

    let object_types = get_object_types(graphql_ast);

    return object_types.into_iter().find(|object_type| {
        return object_type.name == object_type_name;
    }).clone();
}

fn get_enum_type_from_field<'a>(
    graphql_ast: &Document<'a, String>,
    field: &Field<String>
) -> Option<EnumType<'a, String>> {
    let enum_type_name = get_graphql_type_name(&field.field_type);

    let enum_types = get_enum_types(graphql_ast);

    return enum_types.into_iter().find(|enum_type| {
        return enum_type.name == enum_type_name;
    }).clone();
}

fn get_scalar_fields<'a>(
    graphql_ast: &Document<String>,
    object_type: &ObjectType<'a, String>
) -> Vec<Field<'a, String>> {
    return object_type.fields.iter().cloned().filter(|field| {            
        return 
            is_graphql_type_a_relation_many(
                graphql_ast,
                &field.field_type
            ) == false &&
            is_graphql_type_a_relation_one(
                graphql_ast,
                &field.field_type
            ) == false;
    }).collect();
}

fn get_relation_fields<'a>(
    graphql_ast: &Document<String>,
    object_type: &ObjectType<'a, String>
) -> Vec<Field<'a, String>> {
    return object_type.fields.iter().cloned().filter(|field| {            
        return 
            is_graphql_type_a_relation_many(
                graphql_ast,
                &field.field_type
            ) == true ||
            is_graphql_type_a_relation_one(
                graphql_ast,
                &field.field_type
            ) == true;
    }).collect();
}