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
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
|
%global _empty_manifest_terminate_build 0
Name: python-graphql-compiler
Version: 1.11.0
Release: 1
Summary: Turn complex GraphQL queries into optimized database queries.
License: Apache 2.0
URL: https://github.com/kensho-technologies/graphql-compiler
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/a1/0b/35d89eee17c0ec72239e38289088964709af4abfc0c76e0c302b3f9bf559/graphql-compiler-1.11.0.tar.gz
BuildArch: noarch
Requires: python3-arrow
Requires: python3-funcy
Requires: python3-graphql-core
Requires: python3-pytz
Requires: python3-six
Requires: python3-sqlalchemy
%description
# graphql-compiler
[](https://travis-ci.org/kensho-technologies/graphql-compiler)
[](https://coveralls.io/github/kensho-technologies/graphql-compiler?branch=master)
[](https://opensource.org/licenses/Apache-2.0)
[](https://pypi.python.org/pypi/graphql-compiler)
[](https://pypi.python.org/pypi/graphql-compiler)
[](https://pypi.python.org/pypi/graphql-compiler)
[](https://pypi.python.org/pypi/graphql-compiler)
Turn complex GraphQL queries into optimized database queries.
```
pip install graphql-compiler
```
## Quick Overview
Through the GraphQL compiler, users can write powerful queries that uncover
deep relationships in the data while not having to worry about the underlying database query
language. The GraphQL compiler turns read-only queries written in GraphQL syntax to different
query languages.
Furthermore, the GraphQL compiler validates queries through the use of a GraphQL schema
that specifies the underlying schema of the database. We can currently autogenerate a
GraphQL schema by introspecting an OrientDB database, (see [End to End Example](#end-to-end-example)).
In the near future, we plan to add schema autogeneration from SQLAlchemy metadata as well.
For a more detailed overview and getting started guide, please see
[our blog post](https://blog.kensho.com/compiled-graphql-as-a-database-query-language-72e106844282).
## Table of contents
* [Features](#features)
* [End to End Example](#end-to-end-example)
* [Definitions](#definitions)
* [Directives](#directives)
* [@optional](#optional)
* [@output](#output)
* [@fold](#fold)
* [@tag](#tag)
* [@filter](#filter)
* [@recurse](#recurse)
* [@output_source](#output_source)
* [Supported filtering operations](#supported-filtering-operations)
* [Comparison operators](#comparison-operators)
* [name_or_alias](#name_or_alias)
* [between](#between)
* [in_collection](#in_collection)
* [not_in_collection](#not_in_collection)
* [has_substring](#has_substring)
* [contains](#contains)
* [not_contains](#not_contains)
* [intersects](#intersects)
* [has_edge_degree](#has_edge_degree)
* [Type coercions](#type-coercions)
* [Meta fields](#meta-fields)
* [\__typename](#__typename)
* [\_x_count](#_x_count)
* [The GraphQL schema](#the-graphql-schema)
* [Execution model](#execution-model)
* [SQL](#sql)
* [Configuring SQLAlchemy](#configuring-sqlalchemy)
* [End-To-End SQL Example](#end-to-end-sql-example)
* [Configuring the SQL Database to Match the GraphQL Schema](#configuring-the-sql-database-to-match-the-graphql-schema)
* [Miscellaneous](#miscellaneous)
* [Pretty-Printing GraphQL Queries](#pretty-printing-graphql-queries)
* [Expanding `@optional` vertex fields](#expanding-optional-vertex-fields)
* [Optional `type_equivalence_hints` compilation parameter](#optional-type_equivalence_hints-parameter)
* [SchemaGraph](#schemagraph)
* [Cypher query parameters](#cypher-query-parameters)
* [FAQ](#faq)
* [License](#license)
## Features
* **Databases and Query Languages:** We currently support a single database, OrientDB version 2.2.28+, and two query languages that OrientDB supports: the OrientDB dialect of gremlin, and OrientDB's own custom SQL-like query language that we refer to as MATCH, after the name of its graph traversal operator. With OrientDB, MATCH should be the preferred choice for most users, since it tends to run faster than gremlin, and has other desirable properties. See the Execution model section for more details.
Support for relational databases including PostgreSQL, MySQL, SQLite,
and Microsoft SQL Server is a work in progress. A subset of compiler features are available for
these databases. See the [SQL](#sql) section for more details.
* **GraphQL Language Features:** We prioritized and implemented a subset of all functionality supported by the GraphQL language. We hope to add more functionality over time.
## End-to-End Example
Even though this example specifically targets an OrientDB database, it is meant as a generic
end-to-end example of how to use the GraphQL compiler.
```python
from graphql.utils.schema_printer import print_schema
from graphql_compiler import (
get_graphql_schema_from_orientdb_schema_data, graphql_to_match
)
from graphql_compiler.schema_generation.orientdb.utils import ORIENTDB_SCHEMA_RECORDS_QUERY
# Step 1: Get schema metadata from hypothetical Animals database.
client = your_function_that_returns_an_orientdb_client()
schema_records = client.command(ORIENTDB_SCHEMA_RECORDS_QUERY)
schema_data = [record.oRecordData for record in schema_records]
# Step 2: Generate GraphQL schema from metadata.
schema, type_equivalence_hints = get_graphql_schema_from_orientdb_schema_data(schema_data)
print(print_schema(schema))
# schema {
# query: RootSchemaQuery
# }
#
# directive @filter(op_name: String!, value: [String!]!) on FIELD | INLINE_FRAGMENT
#
# directive @tag(tag_name: String!) on FIELD
#
# directive @output(out_name: String!) on FIELD
#
# directive @output_source on FIELD
#
# directive @optional on FIELD
#
# directive @recurse(depth: Int!) on FIELD
#
# directive @fold on FIELD
#
# type Animal {
# name: String
# net_worth: Int
# limbs: Int
# }
#
# type RootSchemaQuery{
# Animal: [Animal]
# }
# Step 3: Write GraphQL query that returns the names of all animals with a certain net worth.
# Note that we prefix net_worth with '$' and surround it with quotes to indicate it's a parameter.
graphql_query = '''
{
Animal {
name @output(out_name: "animal_name")
net_worth @filter(op_name: "=", value: ["$net_worth"])
}
}
'''
parameters = {
'net_worth': '100',
}
# Step 4: Use autogenerated GraphQL schema to compile query into the target database language.
compilation_result = graphql_to_match(schema, graphql_query, parameters, type_equivalence_hints)
print(compilation_result.query)
# SELECT Animal___1.name AS `animal_name`
# FROM ( MATCH { class: Animal, where: ((net_worth = decimal("100"))), as: Animal___1 }
# RETURN $matches)
```
## Definitions
- **Vertex field**: A field corresponding to a vertex in the graph. In the below example, `Animal`
and `out_Entity_Related` are vertex fields. The `Animal` field is the field at which querying
starts, and is therefore the **root vertex field**. In any scope, fields with the prefix `out_`
denote vertex fields connected by an outbound edge, whereas ones with the prefix `in_` denote
vertex fields connected by an inbound edge.
```graphql
{
Animal {
name @output(out_name: "name")
out_Entity_Related {
... on Species {
description @output(out_name: "description")
}
}
}
}
```
- **Property field**: A field corresponding to a property of a vertex in the graph. In the
above example, the `name` and `description` fields are property fields. In any given scope,
**property fields must appear before vertex fields**.
- **Result set**: An assignment of vertices in the graph to scopes (locations) in the query.
As the database processes the query, new result sets may be created (e.g. when traversing edges),
and result sets may be discarded when they do not satisfy filters or type coercions. After all
parts of the query are processed by the database, all remaining result sets are used to form the
query result, by taking their values at all properties marked for output.
- **Scope**: The part of a query between any pair of curly braces. The compiler infers the type
of each scope. For example, in the above query, the scope beginning with `Animal {` is of
type `Animal`, the one beginning with `out_Entity_Related {` is of type `Entity`, and the one
beginning with `... on Species {` is of type `Species`.
- **Type coercion**: An operation that produces a new scope of narrower type than the
scope in which it exists. Any result sets that cannot satisfy the narrower type are filtered out
and not returned. In the above query, `... on Species` is a type coercion which takes
its enclosing scope of type `Entity`, and coerces it into a narrower scope of
type `Species`. This is possible since `Entity` is an interface, and `Species` is a type
that implements the `Entity` interface.
## Directives
### @optional
Without this directive, when a query includes a vertex field, any results matching that query
must be able to produce a value for that vertex field. Applied to a vertex field,
this directive prevents result sets that are unable to produce a value for that field from
being discarded, and allowed to continue processing the remainder of the query.
#### Example Use
```graphql
{
Animal {
name @output(out_name: "name")
out_Animal_ParentOf @optional {
name @output(out_name: "child_name")
}
}
}
```
For each `Animal`:
- if it is a parent of another animal, at least one row containing the
parent and child animal's names, in the `name` and `child_name` columns respectively;
- if it is not a parent of another animal, a row with its name in the `name` column,
and a `null` value in the `child_name` column.
#### Constraints and Rules
- `@optional` can only be applied to vertex fields, except the root vertex field.
- It is allowed to expand vertex fields within an `@optional` scope.
However, doing so is currently associated with a performance penalty in `MATCH`.
For more detail, see: [Expanding `@optional` vertex fields](#expanding-optional-vertex-fields).
- `@recurse`, `@fold`, or `@output_source` may not be used at the same vertex field as `@optional`.
- `@output_source` and `@fold` may not be used anywhere within a scope
marked `@optional`.
If a given result set is unable to produce a value for a vertex field marked `@optional`,
any fields marked `@output` within that vertex field return the `null` value.
When filtering (via `@filter`) or type coercion (via e.g. `... on Animal`) are applied
at or within a vertex field marked `@optional`, the `@optional` is given precedence:
- If a given result set cannot produce a value for the optional vertex field, it is preserved:
the `@optional` directive is applied first, and no filtering or type coercion can happen.
- If a given result set is able to produce a value for the optional vertex field,
the `@optional` does not apply, and that value is then checked against the filtering or type
coercion. These subsequent operations may then cause the result set to be discarded if it does
not match.
For example, suppose we have two `Person` vertices with names `Albert` and `Betty` such that there is a `Person_Knows` edge from `Albert` to `Betty`.
Then the following query:
```graphql
{
Person {
out_Person_Knows @optional {
name @filter(op_name: "=", value: ["$name"])
}
name @output(out_name: "person_name")
}
}
```
with runtime parameter
```python
{
"name": "Charles"
}
```
would output an empty list because the `Person_Knows` edge from `Albert` to `Betty` satisfies the `@optional` directive, but `Betty` doesn't match the filter checking for a node with name `Charles`.
However, if no such `Person_Knows` edge existed from `Albert`, then the output would be
```python
{
name: 'Albert'
}
```
because no such edge can satisfy the `@optional` directive, and no filtering happens.
### @output
Denotes that the value of a property field should be included in the output.
Its `out_name` argument specifies the name of the column in which the
output value should be returned.
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
}
}
```
This query returns the name of each `Animal` in the graph, in a column named `animal_name`.
#### Constraints and Rules
- `@output` can only be applied to property fields.
- The value provided for `out_name` may only consist of upper or lower case letters
(`A-Z`, `a-z`), or underscores (`_`).
- The value provided for `out_name` cannot be prefixed with `___` (three underscores). This
namespace is reserved for compiler internal use.
- For any given query, all `out_name` values must be unique. In other words, output columns must
have unique names.
If the property field marked `@output` exists within a scope marked `@optional`, result sets that
are unable to assign a value to the optional scope return the value `null` as the output
of that property field.
### @fold
Applying `@fold` on a scope "folds" all outputs from within that scope: rather than appearing
on separate rows in the query result, the folded outputs are coalesced into lists starting
at the scope marked `@fold`.
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
out_Animal_ParentOf @fold {
name @output(out_name: "child_names")
}
}
}
```
Each returned row has two columns: `animal_name` with the name of each `Animal` in the graph,
and `child_names` with a list of the names of all children of the `Animal` named `animal_name`.
If a given `Animal` has no children, its `child_names` list is empty.
#### Constraints and Rules
- `@fold` can only be applied to vertex fields, except the root vertex field.
- May not exist at the same vertex field as `@recurse`, `@optional`, or `@output_source`.
- Any scope that is either marked with `@fold` or is nested within a `@fold` marked scope,
may expand at most one vertex field.
- There must be at least one `@output` field within a `@fold` scope.
- All `@output` fields within a `@fold` traversal must be present at the innermost scope.
It is invalid to expand vertex fields within a `@fold` after encountering an `@output` directive.
- `@tag`, `@recurse`, `@optional`, `@output_source` and `@fold` may not be used anywhere
within a scope marked `@fold`.
- Use of type coercions or `@filter` at or within the vertex field marked `@fold` is allowed.
Only data that satisfies the given type coercions and filters is returned by the `@fold`.
- If the compiler is able to prove that the type coercion in the `@fold` scope is actually a no-op,
it may optimize it away. See the
[Optional `type_equivalence_hints` compilation parameter](#optional-type_equivalence_hints-parameter)
section for more details.
#### Example
The following GraphQL is *not allowed* and will produce a `GraphQLCompilationError`.
This query is *invalid* for two separate reasons:
- It expands vertex fields after an `@output` directive (outputting `animal_name`)
- The `in_Animal_ParentOf` scope, which is within a scope marked `@fold`,
expands two vertex fields instead of at most one.
```graphql
{
Animal {
out_Animal_ParentOf @fold {
name @output(out_name: "animal_name")
in_Animal_ParentOf {
out_Animal_OfSpecies {
uuid @output(out_name: "species_id")
}
out_Entity_Related {
... on Animal {
name @output(out_name: "relative_name")
}
}
}
}
}
}
```
The following is a valid use of `@fold`:
```graphql
{
Animal {
out_Animal_ParentOf @fold {
in_Animal_ParentOf {
in_Animal_ParentOf {
out_Entity_Related {
... on Animal {
name @output(out_name: "final_name")
}
}
}
}
}
}
}
```
### @tag
The `@tag` directive enables filtering based on values encountered elsewhere in the same query.
Applied on a property field, it assigns a name to the value of that property field, allowing that
value to then be used as part of a `@filter` directive.
To supply a tagged value to a `@filter` directive, place the tag name (prefixed with a `%` symbol)
in the `@filter`'s `value` array. See [Passing parameters](#passing-parameters)
for more details.
#### Example Use
```graphql
{
Animal {
name @tag(tag_name: "parent_name")
out_Animal_ParentOf {
name @filter(op_name: "<", value: ["%parent_name"])
@output(out_name: "child_name")
}
}
}
```
Each row returned by this query contains, in the `child_name` column, the name of an `Animal`
that is the child of another `Animal`, and has a name that is lexicographically smaller than
the name of its parent.
#### Constraints and Rules
- `@tag` can only be applied to property fields.
- The value provided for `tag_name` may only consist of upper or lower case letters
(`A-Z`, `a-z`), or underscores (`_`).
- For any given query, all `tag_name` values must be unique.
- Cannot be applied to property fields within a scope marked `@fold`.
- Using a `@tag` and a `@filter` that references the tag within the same vertex is allowed,
so long as the two do not appear on the exact same property field.
### @filter
Allows filtering of the data to be returned, based on any of a set of filtering operations.
Conceptually, it is the GraphQL equivalent of the SQL `WHERE` keyword.
See [Supported filtering operations](#supported-filtering-operations)
for details on the various types of filtering that the compiler currently supports.
These operations are currently hardcoded in the compiler; in the future,
we may enable the addition of custom filtering operations via compiler plugins.
Multiple `@filter` directives may be applied to the same field at once. Conceptually,
it is as if the different `@filter` directives were joined by SQL `AND` keywords.
Using a `@tag` and a `@filter` that references the tag within the same vertex is allowed,
so long as the two do not appear on the exact same property field.
#### Passing Parameters
The `@filter` directive accepts two types of parameters: runtime parameters and tagged parameters.
**Runtime parameters** are represented with a `$` prefix (e.g. `$foo`), and denote parameters
whose values will be known at runtime. The compiler will compile the GraphQL query leaving a
spot for the value to fill at runtime. After compilation, the user will have to supply values for
all runtime parameters, and their values will be inserted into the final query before it can be
executed against the database.
Consider the following query:
```graphql
{
Animal {
name @output(out_name: "animal_name")
color @filter(op_name: "=", value: ["$animal_color"])
}
}
```
It returns one row for every `Animal` vertex that has a color equal to `$animal_color`. Each row
contains the animal's name in a column named `animal_name`. The parameter `$animal_color` is
a runtime parameter -- the user must pass in a value (e.g. `{"animal_color": "blue"}`) that
will be inserted into the query before querying the database.
**Tagged parameters** are represented with a `%` prefix (e.g. `%foo`) and denote parameters
whose values are derived from a property field encountered elsewhere in the query.
If the user marks a property field with a `@tag` directive and a suitable name,
that value becomes available to use as a tagged parameter in all subsequent `@filter` directives.
Consider the following query:
```graphql
{
Animal {
name @tag(out_name: "parent_name")
out_Animal_ParentOf {
name @filter(op_name: "has_substring", value: ["%parent_name"])
@output(out_name: "child_name")
}
}
}
```
It returns the names of animals that contain their parent's name as a substring of their own.
The database captures the value of the parent animal's name as the `parent_name` tag, and this
value is then used as the `%parent_name` tagged parameter in the child animal's `@filter`.
We considered and **rejected** the idea of allowing literal values (e.g. `123`)
as `@filter` parameters, for several reasons:
- The GraphQL type of the `@filter` directive's `value` field cannot reasonably encompass
all the different types of arguments that people might supply. Even counting scalar types only,
there's already `ID, Int, Float, Boolean, String, Date, DateTime...` -- way too many to include.
- Literal values would be used when the parameter's value is known to be fixed. We can just as
easily accomplish the same thing by using a runtime parameter with a fixed value. That approach
has the added benefit of potentially reducing the number of different queries that have to be
compiled: two queries with different literal values would have to be compiled twice, whereas
using two different sets of runtime arguments only requires the compilation of one query.
- We were concerned about the potential for accidental misuse of literal values. SQL systems have
supported stored procedures and parameterized queries for decades, and yet ad-hoc SQL query
construction via simple string interpolation is still a serious problem and is the source of
many SQL injection vulnerabilities. We felt that disallowing literal values in the query will
drastically reduce both the use and the risks of unsafe string interpolation,
at an acceptable cost.
#### Constraints and Rules
- The value provided for `op_name` may only consist of upper or lower case letters
(`A-Z`, `a-z`), or underscores (`_`).
- Values provided in the `value` list must start with either `$`
(denoting a runtime parameter) or `%` (denoting a tagged parameter),
followed by exclusively upper or lower case letters (`A-Z`, `a-z`) or underscores (`_`).
- The `@tag` directives corresponding to any tagged parameters in a given `@filter` query
must be applied to fields that appear either at the same vertex as the one with the `@filter`,
or strictly before the field with the `@filter` directive.
- "Can't compare apples and oranges" -- the GraphQL type of the parameters supplied to the `@filter`
must match the GraphQL types the compiler infers based on the field the `@filter` is applied to.
- If the `@tag` corresponding to a tagged parameter originates from within a vertex field
marked `@optional`, the emitted code for the `@filter` checks if the `@optional` field was
assigned a value. If no value was assigned to the `@optional` field, comparisons against the
tagged parameter from within that field return `True`.
- For example, assuming `%from_optional` originates from an `@optional` scope, when no value is
assigned to the `@optional` field:
- using `@filter(op_name: "=", value: ["%from_optional"])` is equivalent to not
having the filter at all;
- using `@filter(op_name: "between", value: ["$lower", "%from_optional"])` is equivalent to
`@filter(op_name: ">=", value: ["$lower"])`.
- Using a `@tag` and a `@filter` that references the tag within the same vertex is allowed,
so long as the two do not appear on the exact same property field.
### @recurse
Applied to a vertex field, specifies that the edge connecting that vertex field to the current
vertex should be visited repeatedly, up to `depth` times. The recursion always starts
at `depth = 0`, i.e. the current vertex -- see the below sections for a more thorough explanation.
#### Example Use
Say the user wants to fetch the names of the children and grandchildren of each `Animal`.
That could be accomplished by running the following two queries and concatenating their results:
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf {
name @output(out_name: "descendant")
}
}
}
```
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf {
out_Animal_ParentOf {
name @output(out_name: "descendant")
}
}
}
}
```
If the user then wanted to also add great-grandchildren to the `descendants` output, that would
require yet another query, and so on. Instead of concatenating the results of multiple queries,
the user can simply use the `@recurse` directive. The following query returns the child and
grandchild descendants:
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf {
out_Animal_ParentOf @recurse(depth: 1) {
name @output(out_name: "descendant")
}
}
}
}
```
Each row returned by this query contains the name of an `Animal` in the `ancestor` column
and the name of its child or grandchild in the `descendant` column.
The `out_Animal_ParentOf` vertex field marked `@recurse` is already enclosed within
another `out_Animal_ParentOf` vertex field, so the recursion starts at the
"child" level (the `out_Animal_ParentOf` not marked with `@recurse`).
Therefore, the `descendant` column contains the names of an `ancestor`'s
children (from `depth = 0` of the recursion) and the names of its grandchildren (from `depth = 1`).
Recursion using this directive is possible since the types of the enclosing scope and the recursion
scope work out: the `@recurse` directive is applied to a vertex field of type `Animal` and
its vertex field is enclosed within a scope of type `Animal`.
Additional cases where recursion is allowed are described in detail below.
The `descendant` column cannot have the name of the `ancestor` animal since the `@recurse`
is already within one `out_Animal_ParentOf` and not at the root `Animal` vertex field.
Similarly, it cannot have descendants that are more than two steps removed
(e.g., great-grandchildren), since the `depth` parameter of `@recurse` is set to `1`.
Now, let's see what happens when we eliminate the outer `out_Animal_ParentOf` vertex field
and simply have the `@recurse` applied on the `out_Animal_ParentOf` in the root vertex field scope:
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf @recurse(depth: 1) {
name @output(out_name: "self_or_descendant")
}
}
}
```
In this case, when the recursion starts at `depth = 0`, the `Animal` within the recursion scope
will be the same `Animal` at the root vertex field, and therefore, in the `depth = 0` step of
the recursion, the value of the `self_or_descendant` field will be equal to the value of
the `ancestor` field.
#### Constraints and Rules
- "The types must work out" -- when applied within a scope of type `A`,
to a vertex field of type `B`, at least one of the following must be true:
- `A` is a GraphQL union;
- `B` is a GraphQL interface, and `A` is a type that implements that interface;
- `A` and `B` are the same type.
- `@recurse` can only be applied to vertex fields other than the root vertex field of a query.
- Cannot be used within a scope marked `@optional` or `@fold`.
- The `depth` parameter of the recursion must always have a value greater than or equal to 1.
Using `depth = 1` produces the current vertex and its neighboring vertices along the
specified edge.
- Type coercions and `@filter` directives within a scope marked `@recurse` do not limit the
recursion depth. Conceptually, recursion to the specified depth happens first,
and then type coercions and `@filter` directives eliminate some of the locations reached
by the recursion.
- As demonstrated by the examples above, the recursion always starts at depth 0,
so the recursion scope always includes the vertex at the scope that encloses
the vertex field marked `@recurse`.
### @output_source
See the [Completeness of returned results](#completeness-of-returned-results) section
for a description of the directive and examples.
#### Constraints and Rules
- May exist at most once in any given GraphQL query.
- Can exist only on a vertex field, and only on the last vertex field used in the query.
- Cannot be used within a scope marked `@optional` or `@fold`.
## Supported filtering operations
### Comparison operators
Supported comparison operators:
- Equal to: `=`
- Not equal to: `!=`
- Greater than: `>`
- Less than: `<`
- Greater than or equal to: `>=`
- Less than or equal to: `<=`
#### Example Use
##### Equal to (`=`):
```graphql
{
Species {
name @filter(op_name: "=", value: ["$species_name"])
uuid @output(out_name: "species_uuid")
}
}
```
This returns one row for every `Species` whose name is equal to the value of the `$species_name`
parameter. Each row contains the `uuid` of the `Species` in a column named `species_uuid`.
##### Greater than or equal to (`>=`):
```
{
Animal {
name @output(out_name: "name")
birthday @output(out_name: "birthday")
@filter(op_name: ">=", value: ["$point_in_time"])
}
}
```
This returns one row for every `Animal` vertex that was born after or on a `$point_in_time`.
Each row contains the animal's name and birthday in columns named `name` and `birthday`, respectively.
#### Constraints and Rules
- All comparison operators must be on a property field.
### name_or_alias
Allows you to filter on vertices which contain the exact string `$wanted_name_or_alias` in their
`name` or `alias` fields.
#### Example Use
```graphql
{
Animal @filter(op_name: "name_or_alias", value: ["$wanted_name_or_alias"]) {
name @output(out_name: "name")
}
}
```
This returns one row for every `Animal` vertex whose name and/or alias is equal to `$wanted_name_or_alias`.
Each row contains the animal's name in a column named `name`.
The value provided for `$wanted_name_or_alias` must be the full name and/or alias of the `Animal`.
Substrings will not be matched.
#### Constraints and Rules
- Must be on a vertex field that has `name` and `alias` properties.
### between
#### Example Use
```graphql
{
Animal {
name @output(out_name: "name")
birthday @filter(op_name: "between", value: ["$lower", "$upper"])
@output(out_name: "birthday")
}
}
```
This returns:
- One row for every `Animal` vertex whose birthday is in between `$lower` and `$upper` dates (inclusive).
Each row contains the animal's name in a column named `name`.
#### Constraints and Rules
- Must be on a property field.
- The lower and upper bounds represent an inclusive interval, which means that the output may
contain values that match them exactly.
### in_collection
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
color @output(out_name: "color")
@filter(op_name: "in_collection", value: ["$colors"])
}
}
```
This returns one row for every `Animal` vertex which has a color contained in a list of colors.
Each row contains the `Animal`'s name and color in columns named `animal_name` and `color`, respectively.
#### Constraints and Rules
- Must be on a property field that is not of list type.
### not_in_collection
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
color @output(out_name: "color")
@filter(op_name: "not_in_collection", value: ["$colors"])
}
}
```
This returns one row for every `Animal` vertex which has a color not contained in a list of colors.
Each row contains the `Animal`'s name and color in columns named `animal_name` and `color`, respectively.
#### Constraints and Rules
- Must be on a property field that is not of list type.
### has_substring
#### Example Use
```graphql
{
Animal {
name @filter(op_name: "has_substring", value: ["$substring"])
@output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose name contains the value supplied
for the `$substring` parameter. Each row contains the matching `Animal`'s name
in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of string type.
### contains
#### Example Use
```graphql
{
Animal {
alias @filter(op_name: "contains", value: ["$wanted"])
name @output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose list of aliases contains the value supplied
for the `$wanted` parameter. Each row contains the matching `Animal`'s name
in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of list type.
### not_contains
#### Example Use
```graphql
{
Animal {
alias @filter(op_name: "not_contains", value: ["$wanted"])
name @output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose list of aliases does not contain the value supplied
for the `$wanted` parameter. Each row contains the matching `Animal`'s name
in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of list type.
### intersects
#### Example Use
```graphql
{
Animal {
alias @filter(op_name: "intersects", value: ["$wanted"])
name @output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose list of aliases has a non-empty intersection
with the list of values supplied for the `$wanted` parameter.
Each row contains the matching `Animal`'s name in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of list type.
### has_edge_degree
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
out_Animal_ParentOf @filter(op_name: "has_edge_degree", value: ["$child_count"]) @optional {
uuid
}
}
}
```
This returns one row for every `Animal` vertex that has exactly `$child_count` children
(i.e. where the `out_Animal_ParentOf` edge appears exactly `$child_count` times).
Each row contains the matching `Animal`'s name, in a column named `animal_name`.
The `uuid` field within the `out_Animal_ParentOf` vertex field is added simply to satisfy
the GraphQL syntax rule that requires at least one field to exist within any `{}`.
Since this field is not marked with any directive, it has no effect on the query.
*N.B.:* Please note the `@optional` directive on the vertex field being filtered above.
If in your use case you expect to set `$child_count` to 0, you must also mark that
vertex field `@optional`. Recall that absence of `@optional` implies that at least one
such edge must exist. If the `has_edge_degree` filter is used with a parameter set to 0,
that requires the edge to not exist. Therefore, if the `@optional` is not present in this situation,
no valid result sets can be produced, and the resulting query will return no results.
#### Constraints and Rules
- Must be on a vertex field that is not the root vertex of the query.
- Tagged values are not supported as parameters for this filter.
- If the runtime parameter for this operator can be `0`, it is *strongly recommended* to also apply
`@optional` to the vertex field being filtered (see N.B. above for details).
## Type coercions
Type coercions are operations that create a new scope whose type is different than the type of the
enclosing scope of the coercion -- they coerce the enclosing scope into a different type.
Type coercions are represented with GraphQL inline fragments.
#### Example Use
```graphql
{
Species {
name @output(out_name: "species_name")
out_Species_Eats {
... on Food {
name @output(out_name: "food_name")
}
}
}
}
```
Here, the `out_Species_Eats` vertex field is of the `Union__Food__FoodOrSpecies__Species` union type. To proceed
with the query, the user must choose which of the types in the `Union__Food__FoodOrSpecies__Species` union to use.
In this example, `... on Food` indicates that the `Food` type was chosen, and any vertices
at that scope that are not of type `Food` are filtered out and discarded.
```graphql
{
Species {
name @output(out_name: "species_name")
out_Entity_Related {
... on Species {
name @output(out_name: "food_name")
}
}
}
}
```
In this query, the `out_Entity_Related` is of `Entity` type. However, the query only wants to
return results where the related entity is a `Species`, which `... on Species` ensures is the case.
## Meta fields
### \_\_typename
The compiler supports the standard GraphQL meta field `__typename`, which returns the runtime type
of the scope where the field is found. Assuming the GraphQL schema matches the database's schema,
the runtime type will always be a subtype of (or exactly equal to) the static type of the scope
determined by the GraphQL type system. Below, we provide an example query in which
the runtime type is a subtype of the static type, but is not equal to it.
The `__typename` field is treated as a property field of type `String`, and supports
all directives that can be applied to any other property field.
#### Example Use
```graphql
{
Entity {
__typename @output(out_name: "entity_type")
name @output(out_name: "entity_name")
}
}
```
This query returns one row for each `Entity` vertex. The scope in which `__typename` appears is
of static type `Entity`. However, `Animal` is a type of `Entity`, as are `Species`, `Food`,
and others. Vertices of all subtypes of `Entity` will therefore be returned, and the `entity_type`
column that outputs the `__typename` field will show their runtime type: `Animal`, `Species`,
`Food`, etc.
### \_x\_count
The `_x_count` meta field is a non-standard meta field defined by the GraphQL compiler that makes it
possible to interact with the _number_ of elements in a scope marked `@fold`. By applying directives
like `@output` and `@filter` to this meta field, queries can output the number of elements captured
in the `@fold` and filter down results to select only those with the desired fold sizes.
We use the `_x_` prefix to signify that this is an extension meta field introduced by the compiler,
and not part of the canonical set of GraphQL meta fields defined by the GraphQL specification.
We do not use the GraphQL standard double-underscore (`__`) prefix for meta fields,
since all names with that prefix are
[explicitly reserved and prohibited from being used](https://facebook.github.io/graphql/draft/#sec-Reserved-Names)
in directives, fields, or any other artifacts.
#### Adding the `_x_count` meta field to your schema
Since the `_x_count` meta field is not currently part of the GraphQL standard, it has to be
explicitly added to all interfaces and types in your schema. There are two ways to do this.
The preferred way to do this is to use the `EXTENDED_META_FIELD_DEFINITIONS` constant as
a starting point for building your interfaces' and types' field descriptions:
```
from graphql import GraphQLInt, GraphQLField, GraphQLObjectType, GraphQLString
from graphql_compiler import EXTENDED_META_FIELD_DEFINITIONS
fields = EXTENDED_META_FIELD_DEFINITIONS.copy()
fields.update({
'foo': GraphQLField(GraphQLString),
'bar': GraphQLField(GraphQLInt),
# etc.
})
graphql_type = GraphQLObjectType('MyType', fields)
# etc.
```
If you are not able to programmatically define the schema, and instead simply have a pre-made
GraphQL schema object that you are able to mutate, the alternative approach is via the
`insert_meta_fields_into_existing_schema()` helper function defined by the compiler:
```
# assuming that existing_schema is your GraphQL schema object
insert_meta_fields_into_existing_schema(existing_schema)
# existing_schema was mutated in-place and all custom meta-fields were added
```
#### Example Use
```graphql
{
Animal {
name @output(out_name: "name")
out_Animal_ParentOf @fold {
_x_count @output(out_name: "number_of_children")
name @output(out_name: "child_names")
}
}
}
```
This query returns one row for each `Animal` vertex. Each row contains its name, and the number and names
of its children. While the output type of the `child_names` selection is a list of strings,
the output type of the `number_of_children` selection is an integer.
```graphql
{
Animal {
name @output(out_name: "name")
out_Animal_ParentOf @fold {
_x_count @filter(op_name: ">=", value: ["$min_children"])
@output(out_name: "number_of_children")
name @filter(op_name: "has_substring", value: ["$substr"])
@output(out_name: "child_names")
}
}
}
```
Here, we've modified the above query to add two more filtering constraints to the returned rows:
- child `Animal` vertices must contain the value of `$substr` as a substring in their name, and
- `Animal` vertices must have at least `$min_children` children that satisfy the above filter.
Importantly, any filtering on `_x_count` is applied *after* any other filters and type coercions
that are present in the `@fold` in question. This order of operations matters a lot: selecting
`Animal` vertices with 3+ children, then filtering the children based on their names is not the same
as filtering the children first, and then selecting `Animal` vertices that have 3+ children that
matched the earlier filter.
#### Constraints and Rules
- The `_x_count` field is only allowed to appear within a vertex field marked `@fold`.
- Filtering on `_x_count` is always applied *after* any other filters and type coercions present
in that `@fold`.
- Filtering or outputting the value of the `_x_count` field must always be done at the innermost
scope of the `@fold`. It is invalid to expand vertex fields within a `@fold` after filtering
or outputting the value of the `_x_count` meta field.
#### How is filtering on `_x_count` different from `@filter` with `has_edge_degree`?
The `has_edge_degree` filter allows filtering based on the number of edges of a particular type.
There are situations in which filtering with `has_edge_degree` and filtering using `=` on `_x_count`
produce equivalent queries. Here is one such pair of queries:
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @filter(op_name: "has_edge_degree", value: ["$num_animals"]) {
uuid
}
}
}
```
and
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @fold {
_x_count @filter(op_name: "=", value: ["$num_animals"])
}
}
}
```
In both of these queries, we ask for the names of the `Species` vertices that have precisely
`$num_animals` members. However, we have expressed this question in two different ways: once
as a property of the `Species` vertex ("the degree of the `in_Animal_OfSpecies` is `$num_animals`"),
and once as a property of the list of `Animal` vertices produced by the `@fold` ("the number of
elements in the `@fold` is `$num_animals`").
When we add additional filtering within the `Animal` vertices of the `in_Animal_OfSpecies` vertex
field, this distinction becomes very important. Compare the following two queries:
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @filter(op_name: "has_edge_degree", value: ["$num_animals"]) {
out_Animal_LivesIn {
name @filter(op_name: "=", value: ["$location"])
}
}
}
}
```
versus
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @fold {
out_Animal_LivesIn {
_x_count @filter(op_name: "=", value: ["$num_animals"])
name @filter(op_name: "=", value: ["$location"])
}
}
}
}
```
In the first, for the purposes of the `has_edge_degree` filtering, the location where the animals
live is irrelevant: the `has_edge_degree` only makes sure that the `Species` vertex has the
correct number of edges of type `in_Animal_OfSpecies`, and that's it. In contrast, the second query
ensures that only `Species` vertices that have `$num_animals` animals that live in the selected
location are returned -- the location matters since the `@filter` on the `_x_count` field applies
to the number of elements in the `@fold` scope.
## The GraphQL schema
This section assumes that the reader is familiar with the way schemas work in the
[reference implementation of GraphQL](http://graphql.org/learn/schema/).
The GraphQL schema used with the compiler must contain the custom directives and custom `Date`
and `DateTime` scalar types defined by the compiler:
```
directive @recurse(depth: Int!) on FIELD
directive @filter(value: [String!]!, op_name: String!) on FIELD | INLINE_FRAGMENT
directive @tag(tag_name: String!) on FIELD
directive @output(out_name: String!) on FIELD
directive @output_source on FIELD
directive @optional on FIELD
directive @fold on FIELD
scalar DateTime
scalar Date
```
If constructing the schema programmatically, one can simply import the the Python object
representations of the custom directives and the custom types:
```
from graphql_compiler import DIRECTIVES # the list of custom directives
from graphql_compiler import GraphQLDate, GraphQLDateTime # the custom types
```
Since the GraphQL and OrientDB type systems have different rules, there is no one-size-fits-all
solution to writing the GraphQL schema for a given database schema.
However, the following rules of thumb are useful to keep in mind:
- Generally, represent OrientDB abstract classes as GraphQL interfaces. In GraphQL's type system,
GraphQL interfaces cannot inherit from other GraphQL interfaces.
- Generally, represent OrientDB non-abstract classes as GraphQL types,
listing the GraphQL interfaces that they implement. In GraphQL's type system, GraphQL types
cannot inherit from other GraphQL types.
- Inheritance relationships between two OrientDB non-abstract classes,
or between two OrientDB abstract classes, introduce some difficulties in GraphQL.
When modelling your data in OrientDB, it's best to avoid such inheritance if possible.
- If it is impossible to avoid having two non-abstract OrientDB classes `A` and `B` such that
`B` inherits from `A`, you have two options:
- You may choose to represent the `A` OrientDB class as a GraphQL interface,
which the GraphQL type corresponding to `B` can implement.
In this case, the GraphQL schema preserves the inheritance relationship
between `A` and `B`, but sacrifices the representation of any inheritance relationships
`A` may have with any OrientDB superclasses.
- You may choose to represent both `A` and `B` as GraphQL types. The tradeoff in this case is
exactly the opposite from the previous case: the GraphQL schema
sacrifices the inheritance relationship between `A` and `B`, but preserves the
inheritance relationships of `A` with its superclasses.
In this case, it is recommended to create a GraphQL union type `A | B`,
and to use that GraphQL union type for any vertex fields that
in OrientDB would be of type `A`.
- If it is impossible to avoid having two abstract OrientDB classes `A` and `B` such that
`B` inherits from `A`, you similarly have two options:
- You may choose to represent `B` as a GraphQL type that can implement the GraphQL interface
corresponding to `A`. This makes the GraphQL schema preserve the inheritance relationship
between `A` and `B`, but sacrifices the ability for other GraphQL types to inherit from `B`.
- You may choose to represent both `A` and `B` as GraphQL interfaces, sacrificing the schema's
representation of the inheritance between `A` and `B`, but allowing GraphQL types
to inherit from both `A` and `B`. If necessary, you can then create a GraphQL
union type `A | B` and use it for any vertex fields that in OrientDB would be of type `A`.
- It is legal to fully omit classes and fields that are not representable in GraphQL. The compiler
currently does not support OrientDB's `EmbeddedMap` type nor embedded non-primitive typed fields,
so such fields can simply be omitted in the GraphQL representation of their classes.
Alternatively, the entire OrientDB class and all edges that may point to it may be omitted
entirely from the GraphQL schema.
## Execution model
Since the GraphQL compiler can target multiple different query languages, each with its own
behaviors and limitations, the execution model must also be defined as a function of the
compilation target language. While we strive to minimize the differences between
compilation targets, some differences are unavoidable.
The compiler abides by the following principles:
- When the database is queried with a compiled query string, its response must always be in the
form of a list of results.
- The precise format of each such result is defined by each compilation target separately.
- `gremlin`, `MATCH` and `SQL` return data in a tabular format, where each result is
a row of the table, and fields marked for output are columns.
- However, future compilation targets may have a different format. For example, each result
may appear in the nested tree format used by the standard GraphQL specification.
- Each such result must satisfy all directives and types in its corresponding GraphQL query.
- The returned list of results is **not** guaranteed to be complete!
- In other words, there may have been additional result sets that satisfy all directives and
types in the corresponding GraphQL query, but were not returned by the database.
- However, compilation target implementations are encouraged to return complete results
if at all practical. The `MATCH` compilation target is guaranteed to produce complete results.
### Completeness of returned results
To explain the completeness of returned results in more detail, assume the database contains
the following example graph:
```
a ---->_ x
|____ /|
_|_/
/ |____
/ \/
b ----> y
```
Let `a, b, x, y` be the values of the `name` property field of four vertices.
Let the vertices named `a` and `b` be of type `S`, and let `x` and `y` be of type `T`.
Let vertex `a` be connected to both `x` and `y` via directed edges of type `E`.
Similarly, let vertex `b` also be connected to both `x` and `y` via directed edges of type `E`.
Consider the GraphQL query:
```
{
S {
name @output(out_name: "s_name")
out_E {
name @output(out_name: "t_name")
}
}
}
```
Between the data in the database and the query's structure, it is clear that combining any of
`a` or `b` with any of `x` or `y` would produce a valid result. Therefore,
the complete result list, shown here in JSON format, would be:
```
[
{"s_name": "a", "t_name": "x"},
{"s_name": "a", "t_name": "y"},
{"s_name": "b", "t_name": "x"},
{"s_name": "b", "t_name": "y"},
]
```
This is precisely what the `MATCH` compilation target is guaranteed to produce.
The remainder of this section is only applicable to the `gremlin` compilation target. If using
`MATCH`, all of the queries listed in the remainder of this section will produce the same, complete
result list.
Since the `gremlin` compilation target does not guarantee a complete result list,
querying the database using a query string generated by the `gremlin` compilation target
will produce only a partial result list resembling the following:
```
[
{"s_name": "a", "t_name": "x"},
{"s_name": "b", "t_name": "x"},
]
```
Due to limitations in the underlying query language, `gremlin` will by default produce at most one
result for each of the starting locations in the query. The above GraphQL query started at
the type `S`, so each `s_name` in the returned result list is therefore distinct. Furthermore,
there is no guarantee (and no way to know ahead of time) whether `x` or `y` will be returned as
the `t_name` value in each result, as they are both valid results.
Users may apply the `@output_source` directive on the last scope of the query
to alter this behavior:
```graphql
{
S {
name @output(out_name: "s_name")
out_E @output_source {
name @output(out_name: "t_name")
}
}
}
```
Rather than producing at most one result for each `S`, the query will now produce
at most one result for each distinct value that can be found at `out_E`, where the directive
is applied:
```graphql
[
{"s_name": "a", "t_name": "x"},
{"s_name": "a", "t_name": "y"},
]
```
Conceptually, applying the `@output_source` directive makes it as if the query were written in
the opposite order:
```graphql
{
T {
name @output(out_name: "t_name")
in_E {
name @output(out_name: "s_name")
}
}
}
```
## SQL
The following table outlines GraphQL compiler features, and their support (if any) by various
relational database flavors:
| Feature/Dialect | Required Edges | @filter | @output | @recurse | @fold | @optional | @output_source |
|----------------------|----------------|---------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------|----------|-------|-----------|----------------|
| PostgreSQL | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| SQLite | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| Microsoft SQL Server | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| MySQL | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| MariaDB | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
### Configuring SQLAlchemy
Relational databases are supported by compiling to SQLAlchemy core as an intermediate
language, and then relying on SQLAlchemy's compilation of the dialect specific SQL string to query
the target database.
For the SQL backend, GraphQL types are assumed to have a SQL table of the same name, and with the
same properties. For example, a schema type
```
type Animal {
name: String
}
```
is expected to correspond to a SQLAlchemy table object of the same name, case insensitive. For this
schema type this could look like:
```python
from sqlalchemy import MetaData, Table, Column, String
# table for GraphQL type Animal
metadata = MetaData()
animal_table = Table(
'animal', # name of table matches type name from schema
metadata,
Column('name', String(length=12)), # Animal.name GraphQL field has corresponding 'name' column
)
```
If a table of the schema type name does not exist, an exception will be raised at compile time. See
[Configuring the SQL Database to Match the GraphQL Schema](#configuring-the-sql-database-to-match-the-graphql-schema)
for a possible option to resolve such naming discrepancies.
### End-To-End SQL Example
An end-to-end example including relevant GraphQL schema and SQLAlchemy engine preparation follows.
This is intended to show the setup steps for the SQL backend of the GraphQL compiler, and
does not represent best practices for configuring and running SQLAlchemy in a production system.
```python
from graphql import parse
from graphql.utils.build_ast_schema import build_ast_schema
from sqlalchemy import MetaData, Table, Column, String, create_engine
from graphql_compiler.compiler.ir_lowering_sql.metadata import SqlMetadata
from graphql_compiler import graphql_to_sql
# Step 1: Configure a GraphQL schema (note that this can also be done programmatically)
schema_text = '''
schema {
query: RootSchemaQuery
}
# IMPORTANT NOTE: all compiler directives are expected here, but not shown to keep the example brief
directive @filter(op_name: String!, value: [String!]!) on FIELD | INLINE_FRAGMENT
# < more directives here, see the GraphQL schema section of this README for more details. >
directive @output(out_name: String!) on FIELD
type Animal {
name: String
}
'''
schema = build_ast_schema(parse(schema_text))
# Step 2: For all GraphQL types, bind all corresponding SQLAlchemy Tables to a single SQLAlchemy
# metadata instance, using the expected naming detailed above.
# See https://docs.sqlalchemy.org/en/latest/core/metadata.html for more details on this step.
metadata = MetaData()
animal_table = Table(
'animal', # name of table matches type name from schema
metadata,
# Animal.name schema field has corresponding 'name' column in animal table
Column('name', String(length=12)),
)
# Step 3: Prepare a SQLAlchemy engine to query the target relational database.
# See https://docs.sqlalchemy.org/en/latest/core/engines.html for more detail on this step.
engine = create_engine('<connection string>')
# Step 4: Wrap the SQLAlchemy metadata and dialect as a SqlMetadata GraphQL compiler object
sql_metadata = SqlMetadata(engine.dialect, metadata)
# Step 5: Prepare and compile a GraphQL query against the schema
graphql_query = '''
{
Animal {
name @output(out_name: "animal_name")
@filter(op_name: "in_collection", value: ["$names"])
}
}
'''
parameters = {
'names': ['animal name 1', 'animal name 2'],
}
compilation_result = graphql_to_sql(schema, graphql_query, parameters, sql_metadata)
# Step 6: Execute compiled query against a SQLAlchemy engine/connection.
# See https://docs.sqlalchemy.org/en/latest/core/connections.html for more details.
query = compilation_result.query
query_results = [dict(result_proxy) for result_proxy in engine.execute(query)]
```
### Configuring the SQL Database to Match the GraphQL Schema
For simplicity, the SQL backend expects an exact match between SQLAlchemy Tables and GraphQL types,
and between SQLAlchemy Columns and GraphQL fields. What if the table name or column name in the
database doesn't conform to these rules? Eventually the plan is to make this aspect of the
SQL backend more configurable. In the near-term, a possible way to address this is by using
SQL views.
For example, suppose there is a table in the database called `animal_table` and it has a column
called `animal_name`. If the desired schema has type
```
type Animal {
name: String
}
```
Then this could be exposed via a view like:
```sql
CREATE VIEW animal AS
SELECT
animal_name AS name
FROM animal_table
```
At this point, the `animal` view can be used in the SQLAlchemy Table for the purposes of compiling.
## Miscellaneous
### Pretty-Printing GraphQL Queries
To pretty-print GraphQL queries, use the included pretty-printer:
```
python -m graphql_compiler.tool <input_file.graphql >output_file.graphql
```
It's modeled after Python's `json.tool`, reading from stdin and writing to stdout.
### Expanding [`@optional`](#optional) vertex fields
Including an optional statement in GraphQL has no performance issues on its own,
but if you continue expanding vertex fields within an optional scope,
there may be significant performance implications.
Going forward, we will refer to two different kinds of `@optional` directives.
- A *"simple"* optional is a vertex with an `@optional` directive that does not expand
any vertex fields within it.
For example:
```graphql
{
Animal {
name @output(out_name: "name")
in_Animal_ParentOf @optional {
name @output(out_name: "parent_name")
}
}
}
```
OrientDB `MATCH` currently allows the last step in any traversal to be optional.
Therefore, the equivalent `MATCH` traversal for the above `GraphQL` is as follows:
```
SELECT
Animal___1.name as `name`,
Animal__in_Animal_ParentOf___1.name as `parent_name`
FROM (
MATCH {
class: Animal,
as: Animal___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf___1
}
RETURN $matches
)
```
- A *"compound"* optional is a vertex with an `@optional` directive which does expand
vertex fields within it.
For example:
```graphql
{
Animal {
name @output(out_name: "name")
in_Animal_ParentOf @optional {
name @output(out_name: "parent_name")
in_Animal_ParentOf {
name @output(out_name: "grandparent_name")
}
}
}
}
```
Currently, this cannot represented by a simple `MATCH` query.
Specifically, the following is *NOT* a valid `MATCH` statement,
because the optional traversal follows another edge:
```
-- NOT A VALID QUERY
SELECT
Animal___1.name as `name`,
Animal__in_Animal_ParentOf___1.name as `parent_name`
FROM (
MATCH {
class: Animal,
as: Animal___1
}.in('Animal_ParentOf') {
optional: true,
as: Animal__in_Animal_ParentOf___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf__in_Animal_ParentOf___1
}
RETURN $matches
)
```
Instead, we represent a *compound* optional by taking an union (`UNIONALL`) of two distinct
`MATCH` queries. For instance, the `GraphQL` query above can be represented as follows:
```
SELECT EXPAND($final_match)
LET
$match1 = (
SELECT
Animal___1.name AS `name`
FROM (
MATCH {
class: Animal,
as: Animal___1,
where: (
(in_Animal_ParentOf IS null)
OR
(in_Animal_ParentOf.size() = 0)
),
}
)
),
$match2 = (
SELECT
Animal___1.name AS `name`,
Animal__in_Animal_ParentOf___1.name AS `parent_name`
FROM (
MATCH {
class: Animal,
as: Animal___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf__in_Animal_ParentOf___1
}
)
),
$final_match = UNIONALL($match1, $match2)
```
In the first case where the optional edge is not followed,
we have to explicitly filter out all vertices where the edge *could have been followed*.
This is to eliminate duplicates between the two `MATCH` selections.
The previous example is not *exactly* how we implement *compound* optionals
(we also have `SELECT` statements within `$match1` and `$match2`),
but it illustrates the the general idea.
#### Performance Penalty
If we have many *compound* optionals in the given `GraphQL`,
the above procedure results in the union of a large number of `MATCH` queries.
Specifically, for `n` compound optionals, we generate 2<sup>n</sup> different `MATCH` queries.
For each of the 2<sup>n</sup> subsets `S` of the `n` optional edges:
- We remove the `@optional` restriction for each traversal in `S`.
- For each traverse `t` in the complement of `S`, we entirely discard `t`
along with all the vertices and directives within it, and we add a filter
on the previous traverse to ensure that the edge corresponding to `t` does not exist.
Therefore, we get a performance penalty that grows exponentially
with the number of *compound* optional edges.
This is important to keep in mind when writing queries with many optional directives.
If some of those *compound* optionals contain `@optional` vertex fields of their own,
the performance penalty grows since we have to account for all possible subsets of `@optional`
statements that can be satisfied simultaneously.
### Optional `type_equivalence_hints` parameter
This compilation parameter is a workaround for the limitations of the GraphQL and Gremlin
type systems:
- GraphQL does not allow `type` to inherit from another `type`, only to implement an `interface`.
- Gremlin does not have first-class support for inheritance at all.
Assume the following GraphQL schema:
```graphql
type Animal {
name: String
}
type Cat {
name: String
}
type Dog {
name: String
}
union AnimalCatDog = Animal | Cat | Dog
type Foo {
adjacent_animal: AnimalCatDog
}
```
An appropriate `type_equivalence_hints` value here would be `{ Animal: AnimalCatDog }`.
This lets the compiler know that the `AnimalCatDog` union type is implicitly equivalent to
the `Animal` type, as there are no other types that inherit from `Animal` in the database schema.
This allows the compiler to perform accurate type coercions in Gremlin, as well as optimize away
type coercions across edges of union type if the coercion is coercing to the
union's equivalent type.
Setting `type_equivalence_hints = { Animal: AnimalCatDog }` during compilation
would enable the use of a `@fold` on the `adjacent_animal` vertex field of `Foo`:
```graphql
{
Foo {
adjacent_animal @fold {
... on Animal {
name @output(out_name: "name")
}
}
}
}
```
### SchemaGraph
When building a GraphQL schema from the database metadata, we first build a `SchemaGraph` from
the metadata and then, from the `SchemaGraph`, build the GraphQL schema. The `SchemaGraph` is also
a representation of the underlying database schema, but it has three main advantages that make it a
more powerful schema introspection tool:
1. It's able to store and expose a schema's index information. The interface for accessing index
information is provisional though and might change in the near future.
2. Its classes are allowed to inherit from non-abstract classes.
3. It exposes many utility functions, such as `get_subclass_set`, that make it easier to explore
the schema.
See below for a mock example of how to build and use the `SchemaGraph`:
```python
from graphql_compiler.schema_generation.orientdb.schema_graph_builder import (
get_orientdb_schema_graph
)
from graphql_compiler.schema_generation.orientdb.utils import (
ORIENTDB_INDEX_RECORDS_QUERY, ORIENTDB_SCHEMA_RECORDS_QUERY
)
# Get schema metadata from hypothetical Animals database.
client = your_function_that_returns_an_orientdb_client()
schema_records = client.command(ORIENTDB_SCHEMA_RECORDS_QUERY)
schema_data = [record.oRecordData for record in schema_records]
# Get index data.
index_records = client.command(ORIENTDB_INDEX_RECORDS_QUERY)
index_query_data = [record.oRecordData for record in index_records]
# Build SchemaGraph.
schema_graph = get_orientdb_schema_graph(schema_data, index_query_data)
# Get all the subclasses of a class.
print(schema_graph.get_subclass_set('Animal'))
# {'Animal', 'Dog'}
# Get all the outgoing edge classes of a vertex class.
print(schema_graph.get_vertex_schema_element_or_raise('Animal').out_connections)
# {'Animal_Eats', 'Animal_FedAt', 'Animal_LivesIn'}
# Get the vertex classes allowed as the destination vertex of an edge class.
print(schema_graph.get_edge_schema_element_or_raise('Animal_Eats').out_connections)
# {'Fruit', 'Food'}
# Get the superclass of all classes allowed as the destination vertex of an edge class.
print(schema_graph.get_edge_schema_element_or_raise('Animal_Eats').base_out_connection)
# Food
# Get the unique indexes defined on a class.
print(schema_graph.get_unique_indexes_for_class('Animal'))
# [IndexDefinition(name='uuid', 'base_classname'='Animal', fields={'uuid'}, unique=True, ordered=False, ignore_nulls=False)]
```
In the future, we plan to add `SchemaGraph` generation from SQLAlchemy metadata. We also plan to
add a mechanism where one can query a `SchemaGraph` using GraphQL queries.
### Cypher query parameters
RedisGraph [doesn't support query parameters](https://github.com/RedisGraph/RedisGraph/issues/544#issuecomment-507963576), so we perform manual parameter interpolation in the
`graphql_to_redisgraph_cypher` function. However, for Neo4j, we can use Neo4j's client to do
parameter interpolation on its own so that we don't reinvent the wheel.
The function `insert_arguments_into_query` does so based on the query language, which isn't
fine-grained enough here-- for Cypher backends, we only want to insert parameters if the backend
is RedisGraph, but not if it's Neo4j.
Instead, the correct approach for Neo4j Cypher is as follows, given a Neo4j Python client called `neo4j_client`:
```python
compilation_result = compile_graphql_to_cypher(
schema, graphql_query, type_equivalence_hints=type_equivalence_hints)
with neo4j_client.driver.session() as session:
result = session.run(compilation_result.query, parameters)
```
## Amending Parsed Custom Scalar Types
Information about the description, serialization and parsing of custom scalar type
objects is lost when a GraphQL schema is parsed from a string. This causes issues when
working with custom scalar type objects. In order to avoid these issues, one can use the code
snippet below to amend the definitions of the custom scalar types used by the compiler.
```python
from graphql_compiler.schema import CUSTOM_SCALAR_TYPES
from graphql_compiler.schema_generation.utils import amend_custom_scalar_types
amend_custom_scalar_types(your_schema, CUSTOM_SCALAR_TYPES)
```
## FAQ
**Q: Do you really use GraphQL, or do you just use GraphQL-like syntax?**
A: We really use GraphQL. Any query that the compiler will accept is entirely valid GraphQL,
and we actually use the Python port of the GraphQL core library for parsing and type checking.
However, since the database queries produced by compiling GraphQL are subject to the limitations
of the database system they run on, our execution model is somewhat different compared to
the one described in the standard GraphQL specification. See the
[Execution model](#execution-model) section for more details.
**Q: Does this project come with a GraphQL server implementation?**
A: No -- there are many existing frameworks for running a web server. We simply built a tool
that takes GraphQL query strings (and their parameters) and returns a query string you can
use with your database. The compiler does not execute the query string against the database,
nor does it deserialize the results. Therefore, it is agnostic to the choice of
server framework and database client library used.
**Q: Do you plan to support other databases / more GraphQL features in the future?**
A: We'd love to, and we could really use your help! Please consider contributing to this project
by opening issues, opening pull requests, or participating in discussions.
**Q: I think I found a bug, what do I do?**
A: Please check if an issue has already been created for the bug, and open a new one if not.
Make sure to describe the bug in as much detail as possible, including any stack traces or
error messages you may have seen, which database you're using, and what query you compiled.
**Q: I think I found a security vulnerability, what do I do?**
A: Please reach out to us at
[graphql-compiler-maintainer@kensho.com](mailto:graphql-compiler-maintainer@kensho.com)
so we can triage the issue and take appropriate action.
## License
Licensed under the Apache 2.0 License. Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
Copyright 2017-present Kensho Technologies, LLC. The present date is determined by the timestamp
of the most recent commit in the repository.
%package -n python3-graphql-compiler
Summary: Turn complex GraphQL queries into optimized database queries.
Provides: python-graphql-compiler
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-graphql-compiler
# graphql-compiler
[](https://travis-ci.org/kensho-technologies/graphql-compiler)
[](https://coveralls.io/github/kensho-technologies/graphql-compiler?branch=master)
[](https://opensource.org/licenses/Apache-2.0)
[](https://pypi.python.org/pypi/graphql-compiler)
[](https://pypi.python.org/pypi/graphql-compiler)
[](https://pypi.python.org/pypi/graphql-compiler)
[](https://pypi.python.org/pypi/graphql-compiler)
Turn complex GraphQL queries into optimized database queries.
```
pip install graphql-compiler
```
## Quick Overview
Through the GraphQL compiler, users can write powerful queries that uncover
deep relationships in the data while not having to worry about the underlying database query
language. The GraphQL compiler turns read-only queries written in GraphQL syntax to different
query languages.
Furthermore, the GraphQL compiler validates queries through the use of a GraphQL schema
that specifies the underlying schema of the database. We can currently autogenerate a
GraphQL schema by introspecting an OrientDB database, (see [End to End Example](#end-to-end-example)).
In the near future, we plan to add schema autogeneration from SQLAlchemy metadata as well.
For a more detailed overview and getting started guide, please see
[our blog post](https://blog.kensho.com/compiled-graphql-as-a-database-query-language-72e106844282).
## Table of contents
* [Features](#features)
* [End to End Example](#end-to-end-example)
* [Definitions](#definitions)
* [Directives](#directives)
* [@optional](#optional)
* [@output](#output)
* [@fold](#fold)
* [@tag](#tag)
* [@filter](#filter)
* [@recurse](#recurse)
* [@output_source](#output_source)
* [Supported filtering operations](#supported-filtering-operations)
* [Comparison operators](#comparison-operators)
* [name_or_alias](#name_or_alias)
* [between](#between)
* [in_collection](#in_collection)
* [not_in_collection](#not_in_collection)
* [has_substring](#has_substring)
* [contains](#contains)
* [not_contains](#not_contains)
* [intersects](#intersects)
* [has_edge_degree](#has_edge_degree)
* [Type coercions](#type-coercions)
* [Meta fields](#meta-fields)
* [\__typename](#__typename)
* [\_x_count](#_x_count)
* [The GraphQL schema](#the-graphql-schema)
* [Execution model](#execution-model)
* [SQL](#sql)
* [Configuring SQLAlchemy](#configuring-sqlalchemy)
* [End-To-End SQL Example](#end-to-end-sql-example)
* [Configuring the SQL Database to Match the GraphQL Schema](#configuring-the-sql-database-to-match-the-graphql-schema)
* [Miscellaneous](#miscellaneous)
* [Pretty-Printing GraphQL Queries](#pretty-printing-graphql-queries)
* [Expanding `@optional` vertex fields](#expanding-optional-vertex-fields)
* [Optional `type_equivalence_hints` compilation parameter](#optional-type_equivalence_hints-parameter)
* [SchemaGraph](#schemagraph)
* [Cypher query parameters](#cypher-query-parameters)
* [FAQ](#faq)
* [License](#license)
## Features
* **Databases and Query Languages:** We currently support a single database, OrientDB version 2.2.28+, and two query languages that OrientDB supports: the OrientDB dialect of gremlin, and OrientDB's own custom SQL-like query language that we refer to as MATCH, after the name of its graph traversal operator. With OrientDB, MATCH should be the preferred choice for most users, since it tends to run faster than gremlin, and has other desirable properties. See the Execution model section for more details.
Support for relational databases including PostgreSQL, MySQL, SQLite,
and Microsoft SQL Server is a work in progress. A subset of compiler features are available for
these databases. See the [SQL](#sql) section for more details.
* **GraphQL Language Features:** We prioritized and implemented a subset of all functionality supported by the GraphQL language. We hope to add more functionality over time.
## End-to-End Example
Even though this example specifically targets an OrientDB database, it is meant as a generic
end-to-end example of how to use the GraphQL compiler.
```python
from graphql.utils.schema_printer import print_schema
from graphql_compiler import (
get_graphql_schema_from_orientdb_schema_data, graphql_to_match
)
from graphql_compiler.schema_generation.orientdb.utils import ORIENTDB_SCHEMA_RECORDS_QUERY
# Step 1: Get schema metadata from hypothetical Animals database.
client = your_function_that_returns_an_orientdb_client()
schema_records = client.command(ORIENTDB_SCHEMA_RECORDS_QUERY)
schema_data = [record.oRecordData for record in schema_records]
# Step 2: Generate GraphQL schema from metadata.
schema, type_equivalence_hints = get_graphql_schema_from_orientdb_schema_data(schema_data)
print(print_schema(schema))
# schema {
# query: RootSchemaQuery
# }
#
# directive @filter(op_name: String!, value: [String!]!) on FIELD | INLINE_FRAGMENT
#
# directive @tag(tag_name: String!) on FIELD
#
# directive @output(out_name: String!) on FIELD
#
# directive @output_source on FIELD
#
# directive @optional on FIELD
#
# directive @recurse(depth: Int!) on FIELD
#
# directive @fold on FIELD
#
# type Animal {
# name: String
# net_worth: Int
# limbs: Int
# }
#
# type RootSchemaQuery{
# Animal: [Animal]
# }
# Step 3: Write GraphQL query that returns the names of all animals with a certain net worth.
# Note that we prefix net_worth with '$' and surround it with quotes to indicate it's a parameter.
graphql_query = '''
{
Animal {
name @output(out_name: "animal_name")
net_worth @filter(op_name: "=", value: ["$net_worth"])
}
}
'''
parameters = {
'net_worth': '100',
}
# Step 4: Use autogenerated GraphQL schema to compile query into the target database language.
compilation_result = graphql_to_match(schema, graphql_query, parameters, type_equivalence_hints)
print(compilation_result.query)
# SELECT Animal___1.name AS `animal_name`
# FROM ( MATCH { class: Animal, where: ((net_worth = decimal("100"))), as: Animal___1 }
# RETURN $matches)
```
## Definitions
- **Vertex field**: A field corresponding to a vertex in the graph. In the below example, `Animal`
and `out_Entity_Related` are vertex fields. The `Animal` field is the field at which querying
starts, and is therefore the **root vertex field**. In any scope, fields with the prefix `out_`
denote vertex fields connected by an outbound edge, whereas ones with the prefix `in_` denote
vertex fields connected by an inbound edge.
```graphql
{
Animal {
name @output(out_name: "name")
out_Entity_Related {
... on Species {
description @output(out_name: "description")
}
}
}
}
```
- **Property field**: A field corresponding to a property of a vertex in the graph. In the
above example, the `name` and `description` fields are property fields. In any given scope,
**property fields must appear before vertex fields**.
- **Result set**: An assignment of vertices in the graph to scopes (locations) in the query.
As the database processes the query, new result sets may be created (e.g. when traversing edges),
and result sets may be discarded when they do not satisfy filters or type coercions. After all
parts of the query are processed by the database, all remaining result sets are used to form the
query result, by taking their values at all properties marked for output.
- **Scope**: The part of a query between any pair of curly braces. The compiler infers the type
of each scope. For example, in the above query, the scope beginning with `Animal {` is of
type `Animal`, the one beginning with `out_Entity_Related {` is of type `Entity`, and the one
beginning with `... on Species {` is of type `Species`.
- **Type coercion**: An operation that produces a new scope of narrower type than the
scope in which it exists. Any result sets that cannot satisfy the narrower type are filtered out
and not returned. In the above query, `... on Species` is a type coercion which takes
its enclosing scope of type `Entity`, and coerces it into a narrower scope of
type `Species`. This is possible since `Entity` is an interface, and `Species` is a type
that implements the `Entity` interface.
## Directives
### @optional
Without this directive, when a query includes a vertex field, any results matching that query
must be able to produce a value for that vertex field. Applied to a vertex field,
this directive prevents result sets that are unable to produce a value for that field from
being discarded, and allowed to continue processing the remainder of the query.
#### Example Use
```graphql
{
Animal {
name @output(out_name: "name")
out_Animal_ParentOf @optional {
name @output(out_name: "child_name")
}
}
}
```
For each `Animal`:
- if it is a parent of another animal, at least one row containing the
parent and child animal's names, in the `name` and `child_name` columns respectively;
- if it is not a parent of another animal, a row with its name in the `name` column,
and a `null` value in the `child_name` column.
#### Constraints and Rules
- `@optional` can only be applied to vertex fields, except the root vertex field.
- It is allowed to expand vertex fields within an `@optional` scope.
However, doing so is currently associated with a performance penalty in `MATCH`.
For more detail, see: [Expanding `@optional` vertex fields](#expanding-optional-vertex-fields).
- `@recurse`, `@fold`, or `@output_source` may not be used at the same vertex field as `@optional`.
- `@output_source` and `@fold` may not be used anywhere within a scope
marked `@optional`.
If a given result set is unable to produce a value for a vertex field marked `@optional`,
any fields marked `@output` within that vertex field return the `null` value.
When filtering (via `@filter`) or type coercion (via e.g. `... on Animal`) are applied
at or within a vertex field marked `@optional`, the `@optional` is given precedence:
- If a given result set cannot produce a value for the optional vertex field, it is preserved:
the `@optional` directive is applied first, and no filtering or type coercion can happen.
- If a given result set is able to produce a value for the optional vertex field,
the `@optional` does not apply, and that value is then checked against the filtering or type
coercion. These subsequent operations may then cause the result set to be discarded if it does
not match.
For example, suppose we have two `Person` vertices with names `Albert` and `Betty` such that there is a `Person_Knows` edge from `Albert` to `Betty`.
Then the following query:
```graphql
{
Person {
out_Person_Knows @optional {
name @filter(op_name: "=", value: ["$name"])
}
name @output(out_name: "person_name")
}
}
```
with runtime parameter
```python
{
"name": "Charles"
}
```
would output an empty list because the `Person_Knows` edge from `Albert` to `Betty` satisfies the `@optional` directive, but `Betty` doesn't match the filter checking for a node with name `Charles`.
However, if no such `Person_Knows` edge existed from `Albert`, then the output would be
```python
{
name: 'Albert'
}
```
because no such edge can satisfy the `@optional` directive, and no filtering happens.
### @output
Denotes that the value of a property field should be included in the output.
Its `out_name` argument specifies the name of the column in which the
output value should be returned.
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
}
}
```
This query returns the name of each `Animal` in the graph, in a column named `animal_name`.
#### Constraints and Rules
- `@output` can only be applied to property fields.
- The value provided for `out_name` may only consist of upper or lower case letters
(`A-Z`, `a-z`), or underscores (`_`).
- The value provided for `out_name` cannot be prefixed with `___` (three underscores). This
namespace is reserved for compiler internal use.
- For any given query, all `out_name` values must be unique. In other words, output columns must
have unique names.
If the property field marked `@output` exists within a scope marked `@optional`, result sets that
are unable to assign a value to the optional scope return the value `null` as the output
of that property field.
### @fold
Applying `@fold` on a scope "folds" all outputs from within that scope: rather than appearing
on separate rows in the query result, the folded outputs are coalesced into lists starting
at the scope marked `@fold`.
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
out_Animal_ParentOf @fold {
name @output(out_name: "child_names")
}
}
}
```
Each returned row has two columns: `animal_name` with the name of each `Animal` in the graph,
and `child_names` with a list of the names of all children of the `Animal` named `animal_name`.
If a given `Animal` has no children, its `child_names` list is empty.
#### Constraints and Rules
- `@fold` can only be applied to vertex fields, except the root vertex field.
- May not exist at the same vertex field as `@recurse`, `@optional`, or `@output_source`.
- Any scope that is either marked with `@fold` or is nested within a `@fold` marked scope,
may expand at most one vertex field.
- There must be at least one `@output` field within a `@fold` scope.
- All `@output` fields within a `@fold` traversal must be present at the innermost scope.
It is invalid to expand vertex fields within a `@fold` after encountering an `@output` directive.
- `@tag`, `@recurse`, `@optional`, `@output_source` and `@fold` may not be used anywhere
within a scope marked `@fold`.
- Use of type coercions or `@filter` at or within the vertex field marked `@fold` is allowed.
Only data that satisfies the given type coercions and filters is returned by the `@fold`.
- If the compiler is able to prove that the type coercion in the `@fold` scope is actually a no-op,
it may optimize it away. See the
[Optional `type_equivalence_hints` compilation parameter](#optional-type_equivalence_hints-parameter)
section for more details.
#### Example
The following GraphQL is *not allowed* and will produce a `GraphQLCompilationError`.
This query is *invalid* for two separate reasons:
- It expands vertex fields after an `@output` directive (outputting `animal_name`)
- The `in_Animal_ParentOf` scope, which is within a scope marked `@fold`,
expands two vertex fields instead of at most one.
```graphql
{
Animal {
out_Animal_ParentOf @fold {
name @output(out_name: "animal_name")
in_Animal_ParentOf {
out_Animal_OfSpecies {
uuid @output(out_name: "species_id")
}
out_Entity_Related {
... on Animal {
name @output(out_name: "relative_name")
}
}
}
}
}
}
```
The following is a valid use of `@fold`:
```graphql
{
Animal {
out_Animal_ParentOf @fold {
in_Animal_ParentOf {
in_Animal_ParentOf {
out_Entity_Related {
... on Animal {
name @output(out_name: "final_name")
}
}
}
}
}
}
}
```
### @tag
The `@tag` directive enables filtering based on values encountered elsewhere in the same query.
Applied on a property field, it assigns a name to the value of that property field, allowing that
value to then be used as part of a `@filter` directive.
To supply a tagged value to a `@filter` directive, place the tag name (prefixed with a `%` symbol)
in the `@filter`'s `value` array. See [Passing parameters](#passing-parameters)
for more details.
#### Example Use
```graphql
{
Animal {
name @tag(tag_name: "parent_name")
out_Animal_ParentOf {
name @filter(op_name: "<", value: ["%parent_name"])
@output(out_name: "child_name")
}
}
}
```
Each row returned by this query contains, in the `child_name` column, the name of an `Animal`
that is the child of another `Animal`, and has a name that is lexicographically smaller than
the name of its parent.
#### Constraints and Rules
- `@tag` can only be applied to property fields.
- The value provided for `tag_name` may only consist of upper or lower case letters
(`A-Z`, `a-z`), or underscores (`_`).
- For any given query, all `tag_name` values must be unique.
- Cannot be applied to property fields within a scope marked `@fold`.
- Using a `@tag` and a `@filter` that references the tag within the same vertex is allowed,
so long as the two do not appear on the exact same property field.
### @filter
Allows filtering of the data to be returned, based on any of a set of filtering operations.
Conceptually, it is the GraphQL equivalent of the SQL `WHERE` keyword.
See [Supported filtering operations](#supported-filtering-operations)
for details on the various types of filtering that the compiler currently supports.
These operations are currently hardcoded in the compiler; in the future,
we may enable the addition of custom filtering operations via compiler plugins.
Multiple `@filter` directives may be applied to the same field at once. Conceptually,
it is as if the different `@filter` directives were joined by SQL `AND` keywords.
Using a `@tag` and a `@filter` that references the tag within the same vertex is allowed,
so long as the two do not appear on the exact same property field.
#### Passing Parameters
The `@filter` directive accepts two types of parameters: runtime parameters and tagged parameters.
**Runtime parameters** are represented with a `$` prefix (e.g. `$foo`), and denote parameters
whose values will be known at runtime. The compiler will compile the GraphQL query leaving a
spot for the value to fill at runtime. After compilation, the user will have to supply values for
all runtime parameters, and their values will be inserted into the final query before it can be
executed against the database.
Consider the following query:
```graphql
{
Animal {
name @output(out_name: "animal_name")
color @filter(op_name: "=", value: ["$animal_color"])
}
}
```
It returns one row for every `Animal` vertex that has a color equal to `$animal_color`. Each row
contains the animal's name in a column named `animal_name`. The parameter `$animal_color` is
a runtime parameter -- the user must pass in a value (e.g. `{"animal_color": "blue"}`) that
will be inserted into the query before querying the database.
**Tagged parameters** are represented with a `%` prefix (e.g. `%foo`) and denote parameters
whose values are derived from a property field encountered elsewhere in the query.
If the user marks a property field with a `@tag` directive and a suitable name,
that value becomes available to use as a tagged parameter in all subsequent `@filter` directives.
Consider the following query:
```graphql
{
Animal {
name @tag(out_name: "parent_name")
out_Animal_ParentOf {
name @filter(op_name: "has_substring", value: ["%parent_name"])
@output(out_name: "child_name")
}
}
}
```
It returns the names of animals that contain their parent's name as a substring of their own.
The database captures the value of the parent animal's name as the `parent_name` tag, and this
value is then used as the `%parent_name` tagged parameter in the child animal's `@filter`.
We considered and **rejected** the idea of allowing literal values (e.g. `123`)
as `@filter` parameters, for several reasons:
- The GraphQL type of the `@filter` directive's `value` field cannot reasonably encompass
all the different types of arguments that people might supply. Even counting scalar types only,
there's already `ID, Int, Float, Boolean, String, Date, DateTime...` -- way too many to include.
- Literal values would be used when the parameter's value is known to be fixed. We can just as
easily accomplish the same thing by using a runtime parameter with a fixed value. That approach
has the added benefit of potentially reducing the number of different queries that have to be
compiled: two queries with different literal values would have to be compiled twice, whereas
using two different sets of runtime arguments only requires the compilation of one query.
- We were concerned about the potential for accidental misuse of literal values. SQL systems have
supported stored procedures and parameterized queries for decades, and yet ad-hoc SQL query
construction via simple string interpolation is still a serious problem and is the source of
many SQL injection vulnerabilities. We felt that disallowing literal values in the query will
drastically reduce both the use and the risks of unsafe string interpolation,
at an acceptable cost.
#### Constraints and Rules
- The value provided for `op_name` may only consist of upper or lower case letters
(`A-Z`, `a-z`), or underscores (`_`).
- Values provided in the `value` list must start with either `$`
(denoting a runtime parameter) or `%` (denoting a tagged parameter),
followed by exclusively upper or lower case letters (`A-Z`, `a-z`) or underscores (`_`).
- The `@tag` directives corresponding to any tagged parameters in a given `@filter` query
must be applied to fields that appear either at the same vertex as the one with the `@filter`,
or strictly before the field with the `@filter` directive.
- "Can't compare apples and oranges" -- the GraphQL type of the parameters supplied to the `@filter`
must match the GraphQL types the compiler infers based on the field the `@filter` is applied to.
- If the `@tag` corresponding to a tagged parameter originates from within a vertex field
marked `@optional`, the emitted code for the `@filter` checks if the `@optional` field was
assigned a value. If no value was assigned to the `@optional` field, comparisons against the
tagged parameter from within that field return `True`.
- For example, assuming `%from_optional` originates from an `@optional` scope, when no value is
assigned to the `@optional` field:
- using `@filter(op_name: "=", value: ["%from_optional"])` is equivalent to not
having the filter at all;
- using `@filter(op_name: "between", value: ["$lower", "%from_optional"])` is equivalent to
`@filter(op_name: ">=", value: ["$lower"])`.
- Using a `@tag` and a `@filter` that references the tag within the same vertex is allowed,
so long as the two do not appear on the exact same property field.
### @recurse
Applied to a vertex field, specifies that the edge connecting that vertex field to the current
vertex should be visited repeatedly, up to `depth` times. The recursion always starts
at `depth = 0`, i.e. the current vertex -- see the below sections for a more thorough explanation.
#### Example Use
Say the user wants to fetch the names of the children and grandchildren of each `Animal`.
That could be accomplished by running the following two queries and concatenating their results:
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf {
name @output(out_name: "descendant")
}
}
}
```
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf {
out_Animal_ParentOf {
name @output(out_name: "descendant")
}
}
}
}
```
If the user then wanted to also add great-grandchildren to the `descendants` output, that would
require yet another query, and so on. Instead of concatenating the results of multiple queries,
the user can simply use the `@recurse` directive. The following query returns the child and
grandchild descendants:
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf {
out_Animal_ParentOf @recurse(depth: 1) {
name @output(out_name: "descendant")
}
}
}
}
```
Each row returned by this query contains the name of an `Animal` in the `ancestor` column
and the name of its child or grandchild in the `descendant` column.
The `out_Animal_ParentOf` vertex field marked `@recurse` is already enclosed within
another `out_Animal_ParentOf` vertex field, so the recursion starts at the
"child" level (the `out_Animal_ParentOf` not marked with `@recurse`).
Therefore, the `descendant` column contains the names of an `ancestor`'s
children (from `depth = 0` of the recursion) and the names of its grandchildren (from `depth = 1`).
Recursion using this directive is possible since the types of the enclosing scope and the recursion
scope work out: the `@recurse` directive is applied to a vertex field of type `Animal` and
its vertex field is enclosed within a scope of type `Animal`.
Additional cases where recursion is allowed are described in detail below.
The `descendant` column cannot have the name of the `ancestor` animal since the `@recurse`
is already within one `out_Animal_ParentOf` and not at the root `Animal` vertex field.
Similarly, it cannot have descendants that are more than two steps removed
(e.g., great-grandchildren), since the `depth` parameter of `@recurse` is set to `1`.
Now, let's see what happens when we eliminate the outer `out_Animal_ParentOf` vertex field
and simply have the `@recurse` applied on the `out_Animal_ParentOf` in the root vertex field scope:
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf @recurse(depth: 1) {
name @output(out_name: "self_or_descendant")
}
}
}
```
In this case, when the recursion starts at `depth = 0`, the `Animal` within the recursion scope
will be the same `Animal` at the root vertex field, and therefore, in the `depth = 0` step of
the recursion, the value of the `self_or_descendant` field will be equal to the value of
the `ancestor` field.
#### Constraints and Rules
- "The types must work out" -- when applied within a scope of type `A`,
to a vertex field of type `B`, at least one of the following must be true:
- `A` is a GraphQL union;
- `B` is a GraphQL interface, and `A` is a type that implements that interface;
- `A` and `B` are the same type.
- `@recurse` can only be applied to vertex fields other than the root vertex field of a query.
- Cannot be used within a scope marked `@optional` or `@fold`.
- The `depth` parameter of the recursion must always have a value greater than or equal to 1.
Using `depth = 1` produces the current vertex and its neighboring vertices along the
specified edge.
- Type coercions and `@filter` directives within a scope marked `@recurse` do not limit the
recursion depth. Conceptually, recursion to the specified depth happens first,
and then type coercions and `@filter` directives eliminate some of the locations reached
by the recursion.
- As demonstrated by the examples above, the recursion always starts at depth 0,
so the recursion scope always includes the vertex at the scope that encloses
the vertex field marked `@recurse`.
### @output_source
See the [Completeness of returned results](#completeness-of-returned-results) section
for a description of the directive and examples.
#### Constraints and Rules
- May exist at most once in any given GraphQL query.
- Can exist only on a vertex field, and only on the last vertex field used in the query.
- Cannot be used within a scope marked `@optional` or `@fold`.
## Supported filtering operations
### Comparison operators
Supported comparison operators:
- Equal to: `=`
- Not equal to: `!=`
- Greater than: `>`
- Less than: `<`
- Greater than or equal to: `>=`
- Less than or equal to: `<=`
#### Example Use
##### Equal to (`=`):
```graphql
{
Species {
name @filter(op_name: "=", value: ["$species_name"])
uuid @output(out_name: "species_uuid")
}
}
```
This returns one row for every `Species` whose name is equal to the value of the `$species_name`
parameter. Each row contains the `uuid` of the `Species` in a column named `species_uuid`.
##### Greater than or equal to (`>=`):
```
{
Animal {
name @output(out_name: "name")
birthday @output(out_name: "birthday")
@filter(op_name: ">=", value: ["$point_in_time"])
}
}
```
This returns one row for every `Animal` vertex that was born after or on a `$point_in_time`.
Each row contains the animal's name and birthday in columns named `name` and `birthday`, respectively.
#### Constraints and Rules
- All comparison operators must be on a property field.
### name_or_alias
Allows you to filter on vertices which contain the exact string `$wanted_name_or_alias` in their
`name` or `alias` fields.
#### Example Use
```graphql
{
Animal @filter(op_name: "name_or_alias", value: ["$wanted_name_or_alias"]) {
name @output(out_name: "name")
}
}
```
This returns one row for every `Animal` vertex whose name and/or alias is equal to `$wanted_name_or_alias`.
Each row contains the animal's name in a column named `name`.
The value provided for `$wanted_name_or_alias` must be the full name and/or alias of the `Animal`.
Substrings will not be matched.
#### Constraints and Rules
- Must be on a vertex field that has `name` and `alias` properties.
### between
#### Example Use
```graphql
{
Animal {
name @output(out_name: "name")
birthday @filter(op_name: "between", value: ["$lower", "$upper"])
@output(out_name: "birthday")
}
}
```
This returns:
- One row for every `Animal` vertex whose birthday is in between `$lower` and `$upper` dates (inclusive).
Each row contains the animal's name in a column named `name`.
#### Constraints and Rules
- Must be on a property field.
- The lower and upper bounds represent an inclusive interval, which means that the output may
contain values that match them exactly.
### in_collection
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
color @output(out_name: "color")
@filter(op_name: "in_collection", value: ["$colors"])
}
}
```
This returns one row for every `Animal` vertex which has a color contained in a list of colors.
Each row contains the `Animal`'s name and color in columns named `animal_name` and `color`, respectively.
#### Constraints and Rules
- Must be on a property field that is not of list type.
### not_in_collection
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
color @output(out_name: "color")
@filter(op_name: "not_in_collection", value: ["$colors"])
}
}
```
This returns one row for every `Animal` vertex which has a color not contained in a list of colors.
Each row contains the `Animal`'s name and color in columns named `animal_name` and `color`, respectively.
#### Constraints and Rules
- Must be on a property field that is not of list type.
### has_substring
#### Example Use
```graphql
{
Animal {
name @filter(op_name: "has_substring", value: ["$substring"])
@output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose name contains the value supplied
for the `$substring` parameter. Each row contains the matching `Animal`'s name
in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of string type.
### contains
#### Example Use
```graphql
{
Animal {
alias @filter(op_name: "contains", value: ["$wanted"])
name @output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose list of aliases contains the value supplied
for the `$wanted` parameter. Each row contains the matching `Animal`'s name
in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of list type.
### not_contains
#### Example Use
```graphql
{
Animal {
alias @filter(op_name: "not_contains", value: ["$wanted"])
name @output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose list of aliases does not contain the value supplied
for the `$wanted` parameter. Each row contains the matching `Animal`'s name
in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of list type.
### intersects
#### Example Use
```graphql
{
Animal {
alias @filter(op_name: "intersects", value: ["$wanted"])
name @output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose list of aliases has a non-empty intersection
with the list of values supplied for the `$wanted` parameter.
Each row contains the matching `Animal`'s name in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of list type.
### has_edge_degree
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
out_Animal_ParentOf @filter(op_name: "has_edge_degree", value: ["$child_count"]) @optional {
uuid
}
}
}
```
This returns one row for every `Animal` vertex that has exactly `$child_count` children
(i.e. where the `out_Animal_ParentOf` edge appears exactly `$child_count` times).
Each row contains the matching `Animal`'s name, in a column named `animal_name`.
The `uuid` field within the `out_Animal_ParentOf` vertex field is added simply to satisfy
the GraphQL syntax rule that requires at least one field to exist within any `{}`.
Since this field is not marked with any directive, it has no effect on the query.
*N.B.:* Please note the `@optional` directive on the vertex field being filtered above.
If in your use case you expect to set `$child_count` to 0, you must also mark that
vertex field `@optional`. Recall that absence of `@optional` implies that at least one
such edge must exist. If the `has_edge_degree` filter is used with a parameter set to 0,
that requires the edge to not exist. Therefore, if the `@optional` is not present in this situation,
no valid result sets can be produced, and the resulting query will return no results.
#### Constraints and Rules
- Must be on a vertex field that is not the root vertex of the query.
- Tagged values are not supported as parameters for this filter.
- If the runtime parameter for this operator can be `0`, it is *strongly recommended* to also apply
`@optional` to the vertex field being filtered (see N.B. above for details).
## Type coercions
Type coercions are operations that create a new scope whose type is different than the type of the
enclosing scope of the coercion -- they coerce the enclosing scope into a different type.
Type coercions are represented with GraphQL inline fragments.
#### Example Use
```graphql
{
Species {
name @output(out_name: "species_name")
out_Species_Eats {
... on Food {
name @output(out_name: "food_name")
}
}
}
}
```
Here, the `out_Species_Eats` vertex field is of the `Union__Food__FoodOrSpecies__Species` union type. To proceed
with the query, the user must choose which of the types in the `Union__Food__FoodOrSpecies__Species` union to use.
In this example, `... on Food` indicates that the `Food` type was chosen, and any vertices
at that scope that are not of type `Food` are filtered out and discarded.
```graphql
{
Species {
name @output(out_name: "species_name")
out_Entity_Related {
... on Species {
name @output(out_name: "food_name")
}
}
}
}
```
In this query, the `out_Entity_Related` is of `Entity` type. However, the query only wants to
return results where the related entity is a `Species`, which `... on Species` ensures is the case.
## Meta fields
### \_\_typename
The compiler supports the standard GraphQL meta field `__typename`, which returns the runtime type
of the scope where the field is found. Assuming the GraphQL schema matches the database's schema,
the runtime type will always be a subtype of (or exactly equal to) the static type of the scope
determined by the GraphQL type system. Below, we provide an example query in which
the runtime type is a subtype of the static type, but is not equal to it.
The `__typename` field is treated as a property field of type `String`, and supports
all directives that can be applied to any other property field.
#### Example Use
```graphql
{
Entity {
__typename @output(out_name: "entity_type")
name @output(out_name: "entity_name")
}
}
```
This query returns one row for each `Entity` vertex. The scope in which `__typename` appears is
of static type `Entity`. However, `Animal` is a type of `Entity`, as are `Species`, `Food`,
and others. Vertices of all subtypes of `Entity` will therefore be returned, and the `entity_type`
column that outputs the `__typename` field will show their runtime type: `Animal`, `Species`,
`Food`, etc.
### \_x\_count
The `_x_count` meta field is a non-standard meta field defined by the GraphQL compiler that makes it
possible to interact with the _number_ of elements in a scope marked `@fold`. By applying directives
like `@output` and `@filter` to this meta field, queries can output the number of elements captured
in the `@fold` and filter down results to select only those with the desired fold sizes.
We use the `_x_` prefix to signify that this is an extension meta field introduced by the compiler,
and not part of the canonical set of GraphQL meta fields defined by the GraphQL specification.
We do not use the GraphQL standard double-underscore (`__`) prefix for meta fields,
since all names with that prefix are
[explicitly reserved and prohibited from being used](https://facebook.github.io/graphql/draft/#sec-Reserved-Names)
in directives, fields, or any other artifacts.
#### Adding the `_x_count` meta field to your schema
Since the `_x_count` meta field is not currently part of the GraphQL standard, it has to be
explicitly added to all interfaces and types in your schema. There are two ways to do this.
The preferred way to do this is to use the `EXTENDED_META_FIELD_DEFINITIONS` constant as
a starting point for building your interfaces' and types' field descriptions:
```
from graphql import GraphQLInt, GraphQLField, GraphQLObjectType, GraphQLString
from graphql_compiler import EXTENDED_META_FIELD_DEFINITIONS
fields = EXTENDED_META_FIELD_DEFINITIONS.copy()
fields.update({
'foo': GraphQLField(GraphQLString),
'bar': GraphQLField(GraphQLInt),
# etc.
})
graphql_type = GraphQLObjectType('MyType', fields)
# etc.
```
If you are not able to programmatically define the schema, and instead simply have a pre-made
GraphQL schema object that you are able to mutate, the alternative approach is via the
`insert_meta_fields_into_existing_schema()` helper function defined by the compiler:
```
# assuming that existing_schema is your GraphQL schema object
insert_meta_fields_into_existing_schema(existing_schema)
# existing_schema was mutated in-place and all custom meta-fields were added
```
#### Example Use
```graphql
{
Animal {
name @output(out_name: "name")
out_Animal_ParentOf @fold {
_x_count @output(out_name: "number_of_children")
name @output(out_name: "child_names")
}
}
}
```
This query returns one row for each `Animal` vertex. Each row contains its name, and the number and names
of its children. While the output type of the `child_names` selection is a list of strings,
the output type of the `number_of_children` selection is an integer.
```graphql
{
Animal {
name @output(out_name: "name")
out_Animal_ParentOf @fold {
_x_count @filter(op_name: ">=", value: ["$min_children"])
@output(out_name: "number_of_children")
name @filter(op_name: "has_substring", value: ["$substr"])
@output(out_name: "child_names")
}
}
}
```
Here, we've modified the above query to add two more filtering constraints to the returned rows:
- child `Animal` vertices must contain the value of `$substr` as a substring in their name, and
- `Animal` vertices must have at least `$min_children` children that satisfy the above filter.
Importantly, any filtering on `_x_count` is applied *after* any other filters and type coercions
that are present in the `@fold` in question. This order of operations matters a lot: selecting
`Animal` vertices with 3+ children, then filtering the children based on their names is not the same
as filtering the children first, and then selecting `Animal` vertices that have 3+ children that
matched the earlier filter.
#### Constraints and Rules
- The `_x_count` field is only allowed to appear within a vertex field marked `@fold`.
- Filtering on `_x_count` is always applied *after* any other filters and type coercions present
in that `@fold`.
- Filtering or outputting the value of the `_x_count` field must always be done at the innermost
scope of the `@fold`. It is invalid to expand vertex fields within a `@fold` after filtering
or outputting the value of the `_x_count` meta field.
#### How is filtering on `_x_count` different from `@filter` with `has_edge_degree`?
The `has_edge_degree` filter allows filtering based on the number of edges of a particular type.
There are situations in which filtering with `has_edge_degree` and filtering using `=` on `_x_count`
produce equivalent queries. Here is one such pair of queries:
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @filter(op_name: "has_edge_degree", value: ["$num_animals"]) {
uuid
}
}
}
```
and
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @fold {
_x_count @filter(op_name: "=", value: ["$num_animals"])
}
}
}
```
In both of these queries, we ask for the names of the `Species` vertices that have precisely
`$num_animals` members. However, we have expressed this question in two different ways: once
as a property of the `Species` vertex ("the degree of the `in_Animal_OfSpecies` is `$num_animals`"),
and once as a property of the list of `Animal` vertices produced by the `@fold` ("the number of
elements in the `@fold` is `$num_animals`").
When we add additional filtering within the `Animal` vertices of the `in_Animal_OfSpecies` vertex
field, this distinction becomes very important. Compare the following two queries:
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @filter(op_name: "has_edge_degree", value: ["$num_animals"]) {
out_Animal_LivesIn {
name @filter(op_name: "=", value: ["$location"])
}
}
}
}
```
versus
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @fold {
out_Animal_LivesIn {
_x_count @filter(op_name: "=", value: ["$num_animals"])
name @filter(op_name: "=", value: ["$location"])
}
}
}
}
```
In the first, for the purposes of the `has_edge_degree` filtering, the location where the animals
live is irrelevant: the `has_edge_degree` only makes sure that the `Species` vertex has the
correct number of edges of type `in_Animal_OfSpecies`, and that's it. In contrast, the second query
ensures that only `Species` vertices that have `$num_animals` animals that live in the selected
location are returned -- the location matters since the `@filter` on the `_x_count` field applies
to the number of elements in the `@fold` scope.
## The GraphQL schema
This section assumes that the reader is familiar with the way schemas work in the
[reference implementation of GraphQL](http://graphql.org/learn/schema/).
The GraphQL schema used with the compiler must contain the custom directives and custom `Date`
and `DateTime` scalar types defined by the compiler:
```
directive @recurse(depth: Int!) on FIELD
directive @filter(value: [String!]!, op_name: String!) on FIELD | INLINE_FRAGMENT
directive @tag(tag_name: String!) on FIELD
directive @output(out_name: String!) on FIELD
directive @output_source on FIELD
directive @optional on FIELD
directive @fold on FIELD
scalar DateTime
scalar Date
```
If constructing the schema programmatically, one can simply import the the Python object
representations of the custom directives and the custom types:
```
from graphql_compiler import DIRECTIVES # the list of custom directives
from graphql_compiler import GraphQLDate, GraphQLDateTime # the custom types
```
Since the GraphQL and OrientDB type systems have different rules, there is no one-size-fits-all
solution to writing the GraphQL schema for a given database schema.
However, the following rules of thumb are useful to keep in mind:
- Generally, represent OrientDB abstract classes as GraphQL interfaces. In GraphQL's type system,
GraphQL interfaces cannot inherit from other GraphQL interfaces.
- Generally, represent OrientDB non-abstract classes as GraphQL types,
listing the GraphQL interfaces that they implement. In GraphQL's type system, GraphQL types
cannot inherit from other GraphQL types.
- Inheritance relationships between two OrientDB non-abstract classes,
or between two OrientDB abstract classes, introduce some difficulties in GraphQL.
When modelling your data in OrientDB, it's best to avoid such inheritance if possible.
- If it is impossible to avoid having two non-abstract OrientDB classes `A` and `B` such that
`B` inherits from `A`, you have two options:
- You may choose to represent the `A` OrientDB class as a GraphQL interface,
which the GraphQL type corresponding to `B` can implement.
In this case, the GraphQL schema preserves the inheritance relationship
between `A` and `B`, but sacrifices the representation of any inheritance relationships
`A` may have with any OrientDB superclasses.
- You may choose to represent both `A` and `B` as GraphQL types. The tradeoff in this case is
exactly the opposite from the previous case: the GraphQL schema
sacrifices the inheritance relationship between `A` and `B`, but preserves the
inheritance relationships of `A` with its superclasses.
In this case, it is recommended to create a GraphQL union type `A | B`,
and to use that GraphQL union type for any vertex fields that
in OrientDB would be of type `A`.
- If it is impossible to avoid having two abstract OrientDB classes `A` and `B` such that
`B` inherits from `A`, you similarly have two options:
- You may choose to represent `B` as a GraphQL type that can implement the GraphQL interface
corresponding to `A`. This makes the GraphQL schema preserve the inheritance relationship
between `A` and `B`, but sacrifices the ability for other GraphQL types to inherit from `B`.
- You may choose to represent both `A` and `B` as GraphQL interfaces, sacrificing the schema's
representation of the inheritance between `A` and `B`, but allowing GraphQL types
to inherit from both `A` and `B`. If necessary, you can then create a GraphQL
union type `A | B` and use it for any vertex fields that in OrientDB would be of type `A`.
- It is legal to fully omit classes and fields that are not representable in GraphQL. The compiler
currently does not support OrientDB's `EmbeddedMap` type nor embedded non-primitive typed fields,
so such fields can simply be omitted in the GraphQL representation of their classes.
Alternatively, the entire OrientDB class and all edges that may point to it may be omitted
entirely from the GraphQL schema.
## Execution model
Since the GraphQL compiler can target multiple different query languages, each with its own
behaviors and limitations, the execution model must also be defined as a function of the
compilation target language. While we strive to minimize the differences between
compilation targets, some differences are unavoidable.
The compiler abides by the following principles:
- When the database is queried with a compiled query string, its response must always be in the
form of a list of results.
- The precise format of each such result is defined by each compilation target separately.
- `gremlin`, `MATCH` and `SQL` return data in a tabular format, where each result is
a row of the table, and fields marked for output are columns.
- However, future compilation targets may have a different format. For example, each result
may appear in the nested tree format used by the standard GraphQL specification.
- Each such result must satisfy all directives and types in its corresponding GraphQL query.
- The returned list of results is **not** guaranteed to be complete!
- In other words, there may have been additional result sets that satisfy all directives and
types in the corresponding GraphQL query, but were not returned by the database.
- However, compilation target implementations are encouraged to return complete results
if at all practical. The `MATCH` compilation target is guaranteed to produce complete results.
### Completeness of returned results
To explain the completeness of returned results in more detail, assume the database contains
the following example graph:
```
a ---->_ x
|____ /|
_|_/
/ |____
/ \/
b ----> y
```
Let `a, b, x, y` be the values of the `name` property field of four vertices.
Let the vertices named `a` and `b` be of type `S`, and let `x` and `y` be of type `T`.
Let vertex `a` be connected to both `x` and `y` via directed edges of type `E`.
Similarly, let vertex `b` also be connected to both `x` and `y` via directed edges of type `E`.
Consider the GraphQL query:
```
{
S {
name @output(out_name: "s_name")
out_E {
name @output(out_name: "t_name")
}
}
}
```
Between the data in the database and the query's structure, it is clear that combining any of
`a` or `b` with any of `x` or `y` would produce a valid result. Therefore,
the complete result list, shown here in JSON format, would be:
```
[
{"s_name": "a", "t_name": "x"},
{"s_name": "a", "t_name": "y"},
{"s_name": "b", "t_name": "x"},
{"s_name": "b", "t_name": "y"},
]
```
This is precisely what the `MATCH` compilation target is guaranteed to produce.
The remainder of this section is only applicable to the `gremlin` compilation target. If using
`MATCH`, all of the queries listed in the remainder of this section will produce the same, complete
result list.
Since the `gremlin` compilation target does not guarantee a complete result list,
querying the database using a query string generated by the `gremlin` compilation target
will produce only a partial result list resembling the following:
```
[
{"s_name": "a", "t_name": "x"},
{"s_name": "b", "t_name": "x"},
]
```
Due to limitations in the underlying query language, `gremlin` will by default produce at most one
result for each of the starting locations in the query. The above GraphQL query started at
the type `S`, so each `s_name` in the returned result list is therefore distinct. Furthermore,
there is no guarantee (and no way to know ahead of time) whether `x` or `y` will be returned as
the `t_name` value in each result, as they are both valid results.
Users may apply the `@output_source` directive on the last scope of the query
to alter this behavior:
```graphql
{
S {
name @output(out_name: "s_name")
out_E @output_source {
name @output(out_name: "t_name")
}
}
}
```
Rather than producing at most one result for each `S`, the query will now produce
at most one result for each distinct value that can be found at `out_E`, where the directive
is applied:
```graphql
[
{"s_name": "a", "t_name": "x"},
{"s_name": "a", "t_name": "y"},
]
```
Conceptually, applying the `@output_source` directive makes it as if the query were written in
the opposite order:
```graphql
{
T {
name @output(out_name: "t_name")
in_E {
name @output(out_name: "s_name")
}
}
}
```
## SQL
The following table outlines GraphQL compiler features, and their support (if any) by various
relational database flavors:
| Feature/Dialect | Required Edges | @filter | @output | @recurse | @fold | @optional | @output_source |
|----------------------|----------------|---------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------|----------|-------|-----------|----------------|
| PostgreSQL | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| SQLite | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| Microsoft SQL Server | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| MySQL | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| MariaDB | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
### Configuring SQLAlchemy
Relational databases are supported by compiling to SQLAlchemy core as an intermediate
language, and then relying on SQLAlchemy's compilation of the dialect specific SQL string to query
the target database.
For the SQL backend, GraphQL types are assumed to have a SQL table of the same name, and with the
same properties. For example, a schema type
```
type Animal {
name: String
}
```
is expected to correspond to a SQLAlchemy table object of the same name, case insensitive. For this
schema type this could look like:
```python
from sqlalchemy import MetaData, Table, Column, String
# table for GraphQL type Animal
metadata = MetaData()
animal_table = Table(
'animal', # name of table matches type name from schema
metadata,
Column('name', String(length=12)), # Animal.name GraphQL field has corresponding 'name' column
)
```
If a table of the schema type name does not exist, an exception will be raised at compile time. See
[Configuring the SQL Database to Match the GraphQL Schema](#configuring-the-sql-database-to-match-the-graphql-schema)
for a possible option to resolve such naming discrepancies.
### End-To-End SQL Example
An end-to-end example including relevant GraphQL schema and SQLAlchemy engine preparation follows.
This is intended to show the setup steps for the SQL backend of the GraphQL compiler, and
does not represent best practices for configuring and running SQLAlchemy in a production system.
```python
from graphql import parse
from graphql.utils.build_ast_schema import build_ast_schema
from sqlalchemy import MetaData, Table, Column, String, create_engine
from graphql_compiler.compiler.ir_lowering_sql.metadata import SqlMetadata
from graphql_compiler import graphql_to_sql
# Step 1: Configure a GraphQL schema (note that this can also be done programmatically)
schema_text = '''
schema {
query: RootSchemaQuery
}
# IMPORTANT NOTE: all compiler directives are expected here, but not shown to keep the example brief
directive @filter(op_name: String!, value: [String!]!) on FIELD | INLINE_FRAGMENT
# < more directives here, see the GraphQL schema section of this README for more details. >
directive @output(out_name: String!) on FIELD
type Animal {
name: String
}
'''
schema = build_ast_schema(parse(schema_text))
# Step 2: For all GraphQL types, bind all corresponding SQLAlchemy Tables to a single SQLAlchemy
# metadata instance, using the expected naming detailed above.
# See https://docs.sqlalchemy.org/en/latest/core/metadata.html for more details on this step.
metadata = MetaData()
animal_table = Table(
'animal', # name of table matches type name from schema
metadata,
# Animal.name schema field has corresponding 'name' column in animal table
Column('name', String(length=12)),
)
# Step 3: Prepare a SQLAlchemy engine to query the target relational database.
# See https://docs.sqlalchemy.org/en/latest/core/engines.html for more detail on this step.
engine = create_engine('<connection string>')
# Step 4: Wrap the SQLAlchemy metadata and dialect as a SqlMetadata GraphQL compiler object
sql_metadata = SqlMetadata(engine.dialect, metadata)
# Step 5: Prepare and compile a GraphQL query against the schema
graphql_query = '''
{
Animal {
name @output(out_name: "animal_name")
@filter(op_name: "in_collection", value: ["$names"])
}
}
'''
parameters = {
'names': ['animal name 1', 'animal name 2'],
}
compilation_result = graphql_to_sql(schema, graphql_query, parameters, sql_metadata)
# Step 6: Execute compiled query against a SQLAlchemy engine/connection.
# See https://docs.sqlalchemy.org/en/latest/core/connections.html for more details.
query = compilation_result.query
query_results = [dict(result_proxy) for result_proxy in engine.execute(query)]
```
### Configuring the SQL Database to Match the GraphQL Schema
For simplicity, the SQL backend expects an exact match between SQLAlchemy Tables and GraphQL types,
and between SQLAlchemy Columns and GraphQL fields. What if the table name or column name in the
database doesn't conform to these rules? Eventually the plan is to make this aspect of the
SQL backend more configurable. In the near-term, a possible way to address this is by using
SQL views.
For example, suppose there is a table in the database called `animal_table` and it has a column
called `animal_name`. If the desired schema has type
```
type Animal {
name: String
}
```
Then this could be exposed via a view like:
```sql
CREATE VIEW animal AS
SELECT
animal_name AS name
FROM animal_table
```
At this point, the `animal` view can be used in the SQLAlchemy Table for the purposes of compiling.
## Miscellaneous
### Pretty-Printing GraphQL Queries
To pretty-print GraphQL queries, use the included pretty-printer:
```
python -m graphql_compiler.tool <input_file.graphql >output_file.graphql
```
It's modeled after Python's `json.tool`, reading from stdin and writing to stdout.
### Expanding [`@optional`](#optional) vertex fields
Including an optional statement in GraphQL has no performance issues on its own,
but if you continue expanding vertex fields within an optional scope,
there may be significant performance implications.
Going forward, we will refer to two different kinds of `@optional` directives.
- A *"simple"* optional is a vertex with an `@optional` directive that does not expand
any vertex fields within it.
For example:
```graphql
{
Animal {
name @output(out_name: "name")
in_Animal_ParentOf @optional {
name @output(out_name: "parent_name")
}
}
}
```
OrientDB `MATCH` currently allows the last step in any traversal to be optional.
Therefore, the equivalent `MATCH` traversal for the above `GraphQL` is as follows:
```
SELECT
Animal___1.name as `name`,
Animal__in_Animal_ParentOf___1.name as `parent_name`
FROM (
MATCH {
class: Animal,
as: Animal___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf___1
}
RETURN $matches
)
```
- A *"compound"* optional is a vertex with an `@optional` directive which does expand
vertex fields within it.
For example:
```graphql
{
Animal {
name @output(out_name: "name")
in_Animal_ParentOf @optional {
name @output(out_name: "parent_name")
in_Animal_ParentOf {
name @output(out_name: "grandparent_name")
}
}
}
}
```
Currently, this cannot represented by a simple `MATCH` query.
Specifically, the following is *NOT* a valid `MATCH` statement,
because the optional traversal follows another edge:
```
-- NOT A VALID QUERY
SELECT
Animal___1.name as `name`,
Animal__in_Animal_ParentOf___1.name as `parent_name`
FROM (
MATCH {
class: Animal,
as: Animal___1
}.in('Animal_ParentOf') {
optional: true,
as: Animal__in_Animal_ParentOf___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf__in_Animal_ParentOf___1
}
RETURN $matches
)
```
Instead, we represent a *compound* optional by taking an union (`UNIONALL`) of two distinct
`MATCH` queries. For instance, the `GraphQL` query above can be represented as follows:
```
SELECT EXPAND($final_match)
LET
$match1 = (
SELECT
Animal___1.name AS `name`
FROM (
MATCH {
class: Animal,
as: Animal___1,
where: (
(in_Animal_ParentOf IS null)
OR
(in_Animal_ParentOf.size() = 0)
),
}
)
),
$match2 = (
SELECT
Animal___1.name AS `name`,
Animal__in_Animal_ParentOf___1.name AS `parent_name`
FROM (
MATCH {
class: Animal,
as: Animal___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf__in_Animal_ParentOf___1
}
)
),
$final_match = UNIONALL($match1, $match2)
```
In the first case where the optional edge is not followed,
we have to explicitly filter out all vertices where the edge *could have been followed*.
This is to eliminate duplicates between the two `MATCH` selections.
The previous example is not *exactly* how we implement *compound* optionals
(we also have `SELECT` statements within `$match1` and `$match2`),
but it illustrates the the general idea.
#### Performance Penalty
If we have many *compound* optionals in the given `GraphQL`,
the above procedure results in the union of a large number of `MATCH` queries.
Specifically, for `n` compound optionals, we generate 2<sup>n</sup> different `MATCH` queries.
For each of the 2<sup>n</sup> subsets `S` of the `n` optional edges:
- We remove the `@optional` restriction for each traversal in `S`.
- For each traverse `t` in the complement of `S`, we entirely discard `t`
along with all the vertices and directives within it, and we add a filter
on the previous traverse to ensure that the edge corresponding to `t` does not exist.
Therefore, we get a performance penalty that grows exponentially
with the number of *compound* optional edges.
This is important to keep in mind when writing queries with many optional directives.
If some of those *compound* optionals contain `@optional` vertex fields of their own,
the performance penalty grows since we have to account for all possible subsets of `@optional`
statements that can be satisfied simultaneously.
### Optional `type_equivalence_hints` parameter
This compilation parameter is a workaround for the limitations of the GraphQL and Gremlin
type systems:
- GraphQL does not allow `type` to inherit from another `type`, only to implement an `interface`.
- Gremlin does not have first-class support for inheritance at all.
Assume the following GraphQL schema:
```graphql
type Animal {
name: String
}
type Cat {
name: String
}
type Dog {
name: String
}
union AnimalCatDog = Animal | Cat | Dog
type Foo {
adjacent_animal: AnimalCatDog
}
```
An appropriate `type_equivalence_hints` value here would be `{ Animal: AnimalCatDog }`.
This lets the compiler know that the `AnimalCatDog` union type is implicitly equivalent to
the `Animal` type, as there are no other types that inherit from `Animal` in the database schema.
This allows the compiler to perform accurate type coercions in Gremlin, as well as optimize away
type coercions across edges of union type if the coercion is coercing to the
union's equivalent type.
Setting `type_equivalence_hints = { Animal: AnimalCatDog }` during compilation
would enable the use of a `@fold` on the `adjacent_animal` vertex field of `Foo`:
```graphql
{
Foo {
adjacent_animal @fold {
... on Animal {
name @output(out_name: "name")
}
}
}
}
```
### SchemaGraph
When building a GraphQL schema from the database metadata, we first build a `SchemaGraph` from
the metadata and then, from the `SchemaGraph`, build the GraphQL schema. The `SchemaGraph` is also
a representation of the underlying database schema, but it has three main advantages that make it a
more powerful schema introspection tool:
1. It's able to store and expose a schema's index information. The interface for accessing index
information is provisional though and might change in the near future.
2. Its classes are allowed to inherit from non-abstract classes.
3. It exposes many utility functions, such as `get_subclass_set`, that make it easier to explore
the schema.
See below for a mock example of how to build and use the `SchemaGraph`:
```python
from graphql_compiler.schema_generation.orientdb.schema_graph_builder import (
get_orientdb_schema_graph
)
from graphql_compiler.schema_generation.orientdb.utils import (
ORIENTDB_INDEX_RECORDS_QUERY, ORIENTDB_SCHEMA_RECORDS_QUERY
)
# Get schema metadata from hypothetical Animals database.
client = your_function_that_returns_an_orientdb_client()
schema_records = client.command(ORIENTDB_SCHEMA_RECORDS_QUERY)
schema_data = [record.oRecordData for record in schema_records]
# Get index data.
index_records = client.command(ORIENTDB_INDEX_RECORDS_QUERY)
index_query_data = [record.oRecordData for record in index_records]
# Build SchemaGraph.
schema_graph = get_orientdb_schema_graph(schema_data, index_query_data)
# Get all the subclasses of a class.
print(schema_graph.get_subclass_set('Animal'))
# {'Animal', 'Dog'}
# Get all the outgoing edge classes of a vertex class.
print(schema_graph.get_vertex_schema_element_or_raise('Animal').out_connections)
# {'Animal_Eats', 'Animal_FedAt', 'Animal_LivesIn'}
# Get the vertex classes allowed as the destination vertex of an edge class.
print(schema_graph.get_edge_schema_element_or_raise('Animal_Eats').out_connections)
# {'Fruit', 'Food'}
# Get the superclass of all classes allowed as the destination vertex of an edge class.
print(schema_graph.get_edge_schema_element_or_raise('Animal_Eats').base_out_connection)
# Food
# Get the unique indexes defined on a class.
print(schema_graph.get_unique_indexes_for_class('Animal'))
# [IndexDefinition(name='uuid', 'base_classname'='Animal', fields={'uuid'}, unique=True, ordered=False, ignore_nulls=False)]
```
In the future, we plan to add `SchemaGraph` generation from SQLAlchemy metadata. We also plan to
add a mechanism where one can query a `SchemaGraph` using GraphQL queries.
### Cypher query parameters
RedisGraph [doesn't support query parameters](https://github.com/RedisGraph/RedisGraph/issues/544#issuecomment-507963576), so we perform manual parameter interpolation in the
`graphql_to_redisgraph_cypher` function. However, for Neo4j, we can use Neo4j's client to do
parameter interpolation on its own so that we don't reinvent the wheel.
The function `insert_arguments_into_query` does so based on the query language, which isn't
fine-grained enough here-- for Cypher backends, we only want to insert parameters if the backend
is RedisGraph, but not if it's Neo4j.
Instead, the correct approach for Neo4j Cypher is as follows, given a Neo4j Python client called `neo4j_client`:
```python
compilation_result = compile_graphql_to_cypher(
schema, graphql_query, type_equivalence_hints=type_equivalence_hints)
with neo4j_client.driver.session() as session:
result = session.run(compilation_result.query, parameters)
```
## Amending Parsed Custom Scalar Types
Information about the description, serialization and parsing of custom scalar type
objects is lost when a GraphQL schema is parsed from a string. This causes issues when
working with custom scalar type objects. In order to avoid these issues, one can use the code
snippet below to amend the definitions of the custom scalar types used by the compiler.
```python
from graphql_compiler.schema import CUSTOM_SCALAR_TYPES
from graphql_compiler.schema_generation.utils import amend_custom_scalar_types
amend_custom_scalar_types(your_schema, CUSTOM_SCALAR_TYPES)
```
## FAQ
**Q: Do you really use GraphQL, or do you just use GraphQL-like syntax?**
A: We really use GraphQL. Any query that the compiler will accept is entirely valid GraphQL,
and we actually use the Python port of the GraphQL core library for parsing and type checking.
However, since the database queries produced by compiling GraphQL are subject to the limitations
of the database system they run on, our execution model is somewhat different compared to
the one described in the standard GraphQL specification. See the
[Execution model](#execution-model) section for more details.
**Q: Does this project come with a GraphQL server implementation?**
A: No -- there are many existing frameworks for running a web server. We simply built a tool
that takes GraphQL query strings (and their parameters) and returns a query string you can
use with your database. The compiler does not execute the query string against the database,
nor does it deserialize the results. Therefore, it is agnostic to the choice of
server framework and database client library used.
**Q: Do you plan to support other databases / more GraphQL features in the future?**
A: We'd love to, and we could really use your help! Please consider contributing to this project
by opening issues, opening pull requests, or participating in discussions.
**Q: I think I found a bug, what do I do?**
A: Please check if an issue has already been created for the bug, and open a new one if not.
Make sure to describe the bug in as much detail as possible, including any stack traces or
error messages you may have seen, which database you're using, and what query you compiled.
**Q: I think I found a security vulnerability, what do I do?**
A: Please reach out to us at
[graphql-compiler-maintainer@kensho.com](mailto:graphql-compiler-maintainer@kensho.com)
so we can triage the issue and take appropriate action.
## License
Licensed under the Apache 2.0 License. Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
Copyright 2017-present Kensho Technologies, LLC. The present date is determined by the timestamp
of the most recent commit in the repository.
%package help
Summary: Development documents and examples for graphql-compiler
Provides: python3-graphql-compiler-doc
%description help
# graphql-compiler
[](https://travis-ci.org/kensho-technologies/graphql-compiler)
[](https://coveralls.io/github/kensho-technologies/graphql-compiler?branch=master)
[](https://opensource.org/licenses/Apache-2.0)
[](https://pypi.python.org/pypi/graphql-compiler)
[](https://pypi.python.org/pypi/graphql-compiler)
[](https://pypi.python.org/pypi/graphql-compiler)
[](https://pypi.python.org/pypi/graphql-compiler)
Turn complex GraphQL queries into optimized database queries.
```
pip install graphql-compiler
```
## Quick Overview
Through the GraphQL compiler, users can write powerful queries that uncover
deep relationships in the data while not having to worry about the underlying database query
language. The GraphQL compiler turns read-only queries written in GraphQL syntax to different
query languages.
Furthermore, the GraphQL compiler validates queries through the use of a GraphQL schema
that specifies the underlying schema of the database. We can currently autogenerate a
GraphQL schema by introspecting an OrientDB database, (see [End to End Example](#end-to-end-example)).
In the near future, we plan to add schema autogeneration from SQLAlchemy metadata as well.
For a more detailed overview and getting started guide, please see
[our blog post](https://blog.kensho.com/compiled-graphql-as-a-database-query-language-72e106844282).
## Table of contents
* [Features](#features)
* [End to End Example](#end-to-end-example)
* [Definitions](#definitions)
* [Directives](#directives)
* [@optional](#optional)
* [@output](#output)
* [@fold](#fold)
* [@tag](#tag)
* [@filter](#filter)
* [@recurse](#recurse)
* [@output_source](#output_source)
* [Supported filtering operations](#supported-filtering-operations)
* [Comparison operators](#comparison-operators)
* [name_or_alias](#name_or_alias)
* [between](#between)
* [in_collection](#in_collection)
* [not_in_collection](#not_in_collection)
* [has_substring](#has_substring)
* [contains](#contains)
* [not_contains](#not_contains)
* [intersects](#intersects)
* [has_edge_degree](#has_edge_degree)
* [Type coercions](#type-coercions)
* [Meta fields](#meta-fields)
* [\__typename](#__typename)
* [\_x_count](#_x_count)
* [The GraphQL schema](#the-graphql-schema)
* [Execution model](#execution-model)
* [SQL](#sql)
* [Configuring SQLAlchemy](#configuring-sqlalchemy)
* [End-To-End SQL Example](#end-to-end-sql-example)
* [Configuring the SQL Database to Match the GraphQL Schema](#configuring-the-sql-database-to-match-the-graphql-schema)
* [Miscellaneous](#miscellaneous)
* [Pretty-Printing GraphQL Queries](#pretty-printing-graphql-queries)
* [Expanding `@optional` vertex fields](#expanding-optional-vertex-fields)
* [Optional `type_equivalence_hints` compilation parameter](#optional-type_equivalence_hints-parameter)
* [SchemaGraph](#schemagraph)
* [Cypher query parameters](#cypher-query-parameters)
* [FAQ](#faq)
* [License](#license)
## Features
* **Databases and Query Languages:** We currently support a single database, OrientDB version 2.2.28+, and two query languages that OrientDB supports: the OrientDB dialect of gremlin, and OrientDB's own custom SQL-like query language that we refer to as MATCH, after the name of its graph traversal operator. With OrientDB, MATCH should be the preferred choice for most users, since it tends to run faster than gremlin, and has other desirable properties. See the Execution model section for more details.
Support for relational databases including PostgreSQL, MySQL, SQLite,
and Microsoft SQL Server is a work in progress. A subset of compiler features are available for
these databases. See the [SQL](#sql) section for more details.
* **GraphQL Language Features:** We prioritized and implemented a subset of all functionality supported by the GraphQL language. We hope to add more functionality over time.
## End-to-End Example
Even though this example specifically targets an OrientDB database, it is meant as a generic
end-to-end example of how to use the GraphQL compiler.
```python
from graphql.utils.schema_printer import print_schema
from graphql_compiler import (
get_graphql_schema_from_orientdb_schema_data, graphql_to_match
)
from graphql_compiler.schema_generation.orientdb.utils import ORIENTDB_SCHEMA_RECORDS_QUERY
# Step 1: Get schema metadata from hypothetical Animals database.
client = your_function_that_returns_an_orientdb_client()
schema_records = client.command(ORIENTDB_SCHEMA_RECORDS_QUERY)
schema_data = [record.oRecordData for record in schema_records]
# Step 2: Generate GraphQL schema from metadata.
schema, type_equivalence_hints = get_graphql_schema_from_orientdb_schema_data(schema_data)
print(print_schema(schema))
# schema {
# query: RootSchemaQuery
# }
#
# directive @filter(op_name: String!, value: [String!]!) on FIELD | INLINE_FRAGMENT
#
# directive @tag(tag_name: String!) on FIELD
#
# directive @output(out_name: String!) on FIELD
#
# directive @output_source on FIELD
#
# directive @optional on FIELD
#
# directive @recurse(depth: Int!) on FIELD
#
# directive @fold on FIELD
#
# type Animal {
# name: String
# net_worth: Int
# limbs: Int
# }
#
# type RootSchemaQuery{
# Animal: [Animal]
# }
# Step 3: Write GraphQL query that returns the names of all animals with a certain net worth.
# Note that we prefix net_worth with '$' and surround it with quotes to indicate it's a parameter.
graphql_query = '''
{
Animal {
name @output(out_name: "animal_name")
net_worth @filter(op_name: "=", value: ["$net_worth"])
}
}
'''
parameters = {
'net_worth': '100',
}
# Step 4: Use autogenerated GraphQL schema to compile query into the target database language.
compilation_result = graphql_to_match(schema, graphql_query, parameters, type_equivalence_hints)
print(compilation_result.query)
# SELECT Animal___1.name AS `animal_name`
# FROM ( MATCH { class: Animal, where: ((net_worth = decimal("100"))), as: Animal___1 }
# RETURN $matches)
```
## Definitions
- **Vertex field**: A field corresponding to a vertex in the graph. In the below example, `Animal`
and `out_Entity_Related` are vertex fields. The `Animal` field is the field at which querying
starts, and is therefore the **root vertex field**. In any scope, fields with the prefix `out_`
denote vertex fields connected by an outbound edge, whereas ones with the prefix `in_` denote
vertex fields connected by an inbound edge.
```graphql
{
Animal {
name @output(out_name: "name")
out_Entity_Related {
... on Species {
description @output(out_name: "description")
}
}
}
}
```
- **Property field**: A field corresponding to a property of a vertex in the graph. In the
above example, the `name` and `description` fields are property fields. In any given scope,
**property fields must appear before vertex fields**.
- **Result set**: An assignment of vertices in the graph to scopes (locations) in the query.
As the database processes the query, new result sets may be created (e.g. when traversing edges),
and result sets may be discarded when they do not satisfy filters or type coercions. After all
parts of the query are processed by the database, all remaining result sets are used to form the
query result, by taking their values at all properties marked for output.
- **Scope**: The part of a query between any pair of curly braces. The compiler infers the type
of each scope. For example, in the above query, the scope beginning with `Animal {` is of
type `Animal`, the one beginning with `out_Entity_Related {` is of type `Entity`, and the one
beginning with `... on Species {` is of type `Species`.
- **Type coercion**: An operation that produces a new scope of narrower type than the
scope in which it exists. Any result sets that cannot satisfy the narrower type are filtered out
and not returned. In the above query, `... on Species` is a type coercion which takes
its enclosing scope of type `Entity`, and coerces it into a narrower scope of
type `Species`. This is possible since `Entity` is an interface, and `Species` is a type
that implements the `Entity` interface.
## Directives
### @optional
Without this directive, when a query includes a vertex field, any results matching that query
must be able to produce a value for that vertex field. Applied to a vertex field,
this directive prevents result sets that are unable to produce a value for that field from
being discarded, and allowed to continue processing the remainder of the query.
#### Example Use
```graphql
{
Animal {
name @output(out_name: "name")
out_Animal_ParentOf @optional {
name @output(out_name: "child_name")
}
}
}
```
For each `Animal`:
- if it is a parent of another animal, at least one row containing the
parent and child animal's names, in the `name` and `child_name` columns respectively;
- if it is not a parent of another animal, a row with its name in the `name` column,
and a `null` value in the `child_name` column.
#### Constraints and Rules
- `@optional` can only be applied to vertex fields, except the root vertex field.
- It is allowed to expand vertex fields within an `@optional` scope.
However, doing so is currently associated with a performance penalty in `MATCH`.
For more detail, see: [Expanding `@optional` vertex fields](#expanding-optional-vertex-fields).
- `@recurse`, `@fold`, or `@output_source` may not be used at the same vertex field as `@optional`.
- `@output_source` and `@fold` may not be used anywhere within a scope
marked `@optional`.
If a given result set is unable to produce a value for a vertex field marked `@optional`,
any fields marked `@output` within that vertex field return the `null` value.
When filtering (via `@filter`) or type coercion (via e.g. `... on Animal`) are applied
at or within a vertex field marked `@optional`, the `@optional` is given precedence:
- If a given result set cannot produce a value for the optional vertex field, it is preserved:
the `@optional` directive is applied first, and no filtering or type coercion can happen.
- If a given result set is able to produce a value for the optional vertex field,
the `@optional` does not apply, and that value is then checked against the filtering or type
coercion. These subsequent operations may then cause the result set to be discarded if it does
not match.
For example, suppose we have two `Person` vertices with names `Albert` and `Betty` such that there is a `Person_Knows` edge from `Albert` to `Betty`.
Then the following query:
```graphql
{
Person {
out_Person_Knows @optional {
name @filter(op_name: "=", value: ["$name"])
}
name @output(out_name: "person_name")
}
}
```
with runtime parameter
```python
{
"name": "Charles"
}
```
would output an empty list because the `Person_Knows` edge from `Albert` to `Betty` satisfies the `@optional` directive, but `Betty` doesn't match the filter checking for a node with name `Charles`.
However, if no such `Person_Knows` edge existed from `Albert`, then the output would be
```python
{
name: 'Albert'
}
```
because no such edge can satisfy the `@optional` directive, and no filtering happens.
### @output
Denotes that the value of a property field should be included in the output.
Its `out_name` argument specifies the name of the column in which the
output value should be returned.
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
}
}
```
This query returns the name of each `Animal` in the graph, in a column named `animal_name`.
#### Constraints and Rules
- `@output` can only be applied to property fields.
- The value provided for `out_name` may only consist of upper or lower case letters
(`A-Z`, `a-z`), or underscores (`_`).
- The value provided for `out_name` cannot be prefixed with `___` (three underscores). This
namespace is reserved for compiler internal use.
- For any given query, all `out_name` values must be unique. In other words, output columns must
have unique names.
If the property field marked `@output` exists within a scope marked `@optional`, result sets that
are unable to assign a value to the optional scope return the value `null` as the output
of that property field.
### @fold
Applying `@fold` on a scope "folds" all outputs from within that scope: rather than appearing
on separate rows in the query result, the folded outputs are coalesced into lists starting
at the scope marked `@fold`.
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
out_Animal_ParentOf @fold {
name @output(out_name: "child_names")
}
}
}
```
Each returned row has two columns: `animal_name` with the name of each `Animal` in the graph,
and `child_names` with a list of the names of all children of the `Animal` named `animal_name`.
If a given `Animal` has no children, its `child_names` list is empty.
#### Constraints and Rules
- `@fold` can only be applied to vertex fields, except the root vertex field.
- May not exist at the same vertex field as `@recurse`, `@optional`, or `@output_source`.
- Any scope that is either marked with `@fold` or is nested within a `@fold` marked scope,
may expand at most one vertex field.
- There must be at least one `@output` field within a `@fold` scope.
- All `@output` fields within a `@fold` traversal must be present at the innermost scope.
It is invalid to expand vertex fields within a `@fold` after encountering an `@output` directive.
- `@tag`, `@recurse`, `@optional`, `@output_source` and `@fold` may not be used anywhere
within a scope marked `@fold`.
- Use of type coercions or `@filter` at or within the vertex field marked `@fold` is allowed.
Only data that satisfies the given type coercions and filters is returned by the `@fold`.
- If the compiler is able to prove that the type coercion in the `@fold` scope is actually a no-op,
it may optimize it away. See the
[Optional `type_equivalence_hints` compilation parameter](#optional-type_equivalence_hints-parameter)
section for more details.
#### Example
The following GraphQL is *not allowed* and will produce a `GraphQLCompilationError`.
This query is *invalid* for two separate reasons:
- It expands vertex fields after an `@output` directive (outputting `animal_name`)
- The `in_Animal_ParentOf` scope, which is within a scope marked `@fold`,
expands two vertex fields instead of at most one.
```graphql
{
Animal {
out_Animal_ParentOf @fold {
name @output(out_name: "animal_name")
in_Animal_ParentOf {
out_Animal_OfSpecies {
uuid @output(out_name: "species_id")
}
out_Entity_Related {
... on Animal {
name @output(out_name: "relative_name")
}
}
}
}
}
}
```
The following is a valid use of `@fold`:
```graphql
{
Animal {
out_Animal_ParentOf @fold {
in_Animal_ParentOf {
in_Animal_ParentOf {
out_Entity_Related {
... on Animal {
name @output(out_name: "final_name")
}
}
}
}
}
}
}
```
### @tag
The `@tag` directive enables filtering based on values encountered elsewhere in the same query.
Applied on a property field, it assigns a name to the value of that property field, allowing that
value to then be used as part of a `@filter` directive.
To supply a tagged value to a `@filter` directive, place the tag name (prefixed with a `%` symbol)
in the `@filter`'s `value` array. See [Passing parameters](#passing-parameters)
for more details.
#### Example Use
```graphql
{
Animal {
name @tag(tag_name: "parent_name")
out_Animal_ParentOf {
name @filter(op_name: "<", value: ["%parent_name"])
@output(out_name: "child_name")
}
}
}
```
Each row returned by this query contains, in the `child_name` column, the name of an `Animal`
that is the child of another `Animal`, and has a name that is lexicographically smaller than
the name of its parent.
#### Constraints and Rules
- `@tag` can only be applied to property fields.
- The value provided for `tag_name` may only consist of upper or lower case letters
(`A-Z`, `a-z`), or underscores (`_`).
- For any given query, all `tag_name` values must be unique.
- Cannot be applied to property fields within a scope marked `@fold`.
- Using a `@tag` and a `@filter` that references the tag within the same vertex is allowed,
so long as the two do not appear on the exact same property field.
### @filter
Allows filtering of the data to be returned, based on any of a set of filtering operations.
Conceptually, it is the GraphQL equivalent of the SQL `WHERE` keyword.
See [Supported filtering operations](#supported-filtering-operations)
for details on the various types of filtering that the compiler currently supports.
These operations are currently hardcoded in the compiler; in the future,
we may enable the addition of custom filtering operations via compiler plugins.
Multiple `@filter` directives may be applied to the same field at once. Conceptually,
it is as if the different `@filter` directives were joined by SQL `AND` keywords.
Using a `@tag` and a `@filter` that references the tag within the same vertex is allowed,
so long as the two do not appear on the exact same property field.
#### Passing Parameters
The `@filter` directive accepts two types of parameters: runtime parameters and tagged parameters.
**Runtime parameters** are represented with a `$` prefix (e.g. `$foo`), and denote parameters
whose values will be known at runtime. The compiler will compile the GraphQL query leaving a
spot for the value to fill at runtime. After compilation, the user will have to supply values for
all runtime parameters, and their values will be inserted into the final query before it can be
executed against the database.
Consider the following query:
```graphql
{
Animal {
name @output(out_name: "animal_name")
color @filter(op_name: "=", value: ["$animal_color"])
}
}
```
It returns one row for every `Animal` vertex that has a color equal to `$animal_color`. Each row
contains the animal's name in a column named `animal_name`. The parameter `$animal_color` is
a runtime parameter -- the user must pass in a value (e.g. `{"animal_color": "blue"}`) that
will be inserted into the query before querying the database.
**Tagged parameters** are represented with a `%` prefix (e.g. `%foo`) and denote parameters
whose values are derived from a property field encountered elsewhere in the query.
If the user marks a property field with a `@tag` directive and a suitable name,
that value becomes available to use as a tagged parameter in all subsequent `@filter` directives.
Consider the following query:
```graphql
{
Animal {
name @tag(out_name: "parent_name")
out_Animal_ParentOf {
name @filter(op_name: "has_substring", value: ["%parent_name"])
@output(out_name: "child_name")
}
}
}
```
It returns the names of animals that contain their parent's name as a substring of their own.
The database captures the value of the parent animal's name as the `parent_name` tag, and this
value is then used as the `%parent_name` tagged parameter in the child animal's `@filter`.
We considered and **rejected** the idea of allowing literal values (e.g. `123`)
as `@filter` parameters, for several reasons:
- The GraphQL type of the `@filter` directive's `value` field cannot reasonably encompass
all the different types of arguments that people might supply. Even counting scalar types only,
there's already `ID, Int, Float, Boolean, String, Date, DateTime...` -- way too many to include.
- Literal values would be used when the parameter's value is known to be fixed. We can just as
easily accomplish the same thing by using a runtime parameter with a fixed value. That approach
has the added benefit of potentially reducing the number of different queries that have to be
compiled: two queries with different literal values would have to be compiled twice, whereas
using two different sets of runtime arguments only requires the compilation of one query.
- We were concerned about the potential for accidental misuse of literal values. SQL systems have
supported stored procedures and parameterized queries for decades, and yet ad-hoc SQL query
construction via simple string interpolation is still a serious problem and is the source of
many SQL injection vulnerabilities. We felt that disallowing literal values in the query will
drastically reduce both the use and the risks of unsafe string interpolation,
at an acceptable cost.
#### Constraints and Rules
- The value provided for `op_name` may only consist of upper or lower case letters
(`A-Z`, `a-z`), or underscores (`_`).
- Values provided in the `value` list must start with either `$`
(denoting a runtime parameter) or `%` (denoting a tagged parameter),
followed by exclusively upper or lower case letters (`A-Z`, `a-z`) or underscores (`_`).
- The `@tag` directives corresponding to any tagged parameters in a given `@filter` query
must be applied to fields that appear either at the same vertex as the one with the `@filter`,
or strictly before the field with the `@filter` directive.
- "Can't compare apples and oranges" -- the GraphQL type of the parameters supplied to the `@filter`
must match the GraphQL types the compiler infers based on the field the `@filter` is applied to.
- If the `@tag` corresponding to a tagged parameter originates from within a vertex field
marked `@optional`, the emitted code for the `@filter` checks if the `@optional` field was
assigned a value. If no value was assigned to the `@optional` field, comparisons against the
tagged parameter from within that field return `True`.
- For example, assuming `%from_optional` originates from an `@optional` scope, when no value is
assigned to the `@optional` field:
- using `@filter(op_name: "=", value: ["%from_optional"])` is equivalent to not
having the filter at all;
- using `@filter(op_name: "between", value: ["$lower", "%from_optional"])` is equivalent to
`@filter(op_name: ">=", value: ["$lower"])`.
- Using a `@tag` and a `@filter` that references the tag within the same vertex is allowed,
so long as the two do not appear on the exact same property field.
### @recurse
Applied to a vertex field, specifies that the edge connecting that vertex field to the current
vertex should be visited repeatedly, up to `depth` times. The recursion always starts
at `depth = 0`, i.e. the current vertex -- see the below sections for a more thorough explanation.
#### Example Use
Say the user wants to fetch the names of the children and grandchildren of each `Animal`.
That could be accomplished by running the following two queries and concatenating their results:
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf {
name @output(out_name: "descendant")
}
}
}
```
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf {
out_Animal_ParentOf {
name @output(out_name: "descendant")
}
}
}
}
```
If the user then wanted to also add great-grandchildren to the `descendants` output, that would
require yet another query, and so on. Instead of concatenating the results of multiple queries,
the user can simply use the `@recurse` directive. The following query returns the child and
grandchild descendants:
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf {
out_Animal_ParentOf @recurse(depth: 1) {
name @output(out_name: "descendant")
}
}
}
}
```
Each row returned by this query contains the name of an `Animal` in the `ancestor` column
and the name of its child or grandchild in the `descendant` column.
The `out_Animal_ParentOf` vertex field marked `@recurse` is already enclosed within
another `out_Animal_ParentOf` vertex field, so the recursion starts at the
"child" level (the `out_Animal_ParentOf` not marked with `@recurse`).
Therefore, the `descendant` column contains the names of an `ancestor`'s
children (from `depth = 0` of the recursion) and the names of its grandchildren (from `depth = 1`).
Recursion using this directive is possible since the types of the enclosing scope and the recursion
scope work out: the `@recurse` directive is applied to a vertex field of type `Animal` and
its vertex field is enclosed within a scope of type `Animal`.
Additional cases where recursion is allowed are described in detail below.
The `descendant` column cannot have the name of the `ancestor` animal since the `@recurse`
is already within one `out_Animal_ParentOf` and not at the root `Animal` vertex field.
Similarly, it cannot have descendants that are more than two steps removed
(e.g., great-grandchildren), since the `depth` parameter of `@recurse` is set to `1`.
Now, let's see what happens when we eliminate the outer `out_Animal_ParentOf` vertex field
and simply have the `@recurse` applied on the `out_Animal_ParentOf` in the root vertex field scope:
```graphql
{
Animal {
name @output(out_name: "ancestor")
out_Animal_ParentOf @recurse(depth: 1) {
name @output(out_name: "self_or_descendant")
}
}
}
```
In this case, when the recursion starts at `depth = 0`, the `Animal` within the recursion scope
will be the same `Animal` at the root vertex field, and therefore, in the `depth = 0` step of
the recursion, the value of the `self_or_descendant` field will be equal to the value of
the `ancestor` field.
#### Constraints and Rules
- "The types must work out" -- when applied within a scope of type `A`,
to a vertex field of type `B`, at least one of the following must be true:
- `A` is a GraphQL union;
- `B` is a GraphQL interface, and `A` is a type that implements that interface;
- `A` and `B` are the same type.
- `@recurse` can only be applied to vertex fields other than the root vertex field of a query.
- Cannot be used within a scope marked `@optional` or `@fold`.
- The `depth` parameter of the recursion must always have a value greater than or equal to 1.
Using `depth = 1` produces the current vertex and its neighboring vertices along the
specified edge.
- Type coercions and `@filter` directives within a scope marked `@recurse` do not limit the
recursion depth. Conceptually, recursion to the specified depth happens first,
and then type coercions and `@filter` directives eliminate some of the locations reached
by the recursion.
- As demonstrated by the examples above, the recursion always starts at depth 0,
so the recursion scope always includes the vertex at the scope that encloses
the vertex field marked `@recurse`.
### @output_source
See the [Completeness of returned results](#completeness-of-returned-results) section
for a description of the directive and examples.
#### Constraints and Rules
- May exist at most once in any given GraphQL query.
- Can exist only on a vertex field, and only on the last vertex field used in the query.
- Cannot be used within a scope marked `@optional` or `@fold`.
## Supported filtering operations
### Comparison operators
Supported comparison operators:
- Equal to: `=`
- Not equal to: `!=`
- Greater than: `>`
- Less than: `<`
- Greater than or equal to: `>=`
- Less than or equal to: `<=`
#### Example Use
##### Equal to (`=`):
```graphql
{
Species {
name @filter(op_name: "=", value: ["$species_name"])
uuid @output(out_name: "species_uuid")
}
}
```
This returns one row for every `Species` whose name is equal to the value of the `$species_name`
parameter. Each row contains the `uuid` of the `Species` in a column named `species_uuid`.
##### Greater than or equal to (`>=`):
```
{
Animal {
name @output(out_name: "name")
birthday @output(out_name: "birthday")
@filter(op_name: ">=", value: ["$point_in_time"])
}
}
```
This returns one row for every `Animal` vertex that was born after or on a `$point_in_time`.
Each row contains the animal's name and birthday in columns named `name` and `birthday`, respectively.
#### Constraints and Rules
- All comparison operators must be on a property field.
### name_or_alias
Allows you to filter on vertices which contain the exact string `$wanted_name_or_alias` in their
`name` or `alias` fields.
#### Example Use
```graphql
{
Animal @filter(op_name: "name_or_alias", value: ["$wanted_name_or_alias"]) {
name @output(out_name: "name")
}
}
```
This returns one row for every `Animal` vertex whose name and/or alias is equal to `$wanted_name_or_alias`.
Each row contains the animal's name in a column named `name`.
The value provided for `$wanted_name_or_alias` must be the full name and/or alias of the `Animal`.
Substrings will not be matched.
#### Constraints and Rules
- Must be on a vertex field that has `name` and `alias` properties.
### between
#### Example Use
```graphql
{
Animal {
name @output(out_name: "name")
birthday @filter(op_name: "between", value: ["$lower", "$upper"])
@output(out_name: "birthday")
}
}
```
This returns:
- One row for every `Animal` vertex whose birthday is in between `$lower` and `$upper` dates (inclusive).
Each row contains the animal's name in a column named `name`.
#### Constraints and Rules
- Must be on a property field.
- The lower and upper bounds represent an inclusive interval, which means that the output may
contain values that match them exactly.
### in_collection
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
color @output(out_name: "color")
@filter(op_name: "in_collection", value: ["$colors"])
}
}
```
This returns one row for every `Animal` vertex which has a color contained in a list of colors.
Each row contains the `Animal`'s name and color in columns named `animal_name` and `color`, respectively.
#### Constraints and Rules
- Must be on a property field that is not of list type.
### not_in_collection
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
color @output(out_name: "color")
@filter(op_name: "not_in_collection", value: ["$colors"])
}
}
```
This returns one row for every `Animal` vertex which has a color not contained in a list of colors.
Each row contains the `Animal`'s name and color in columns named `animal_name` and `color`, respectively.
#### Constraints and Rules
- Must be on a property field that is not of list type.
### has_substring
#### Example Use
```graphql
{
Animal {
name @filter(op_name: "has_substring", value: ["$substring"])
@output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose name contains the value supplied
for the `$substring` parameter. Each row contains the matching `Animal`'s name
in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of string type.
### contains
#### Example Use
```graphql
{
Animal {
alias @filter(op_name: "contains", value: ["$wanted"])
name @output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose list of aliases contains the value supplied
for the `$wanted` parameter. Each row contains the matching `Animal`'s name
in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of list type.
### not_contains
#### Example Use
```graphql
{
Animal {
alias @filter(op_name: "not_contains", value: ["$wanted"])
name @output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose list of aliases does not contain the value supplied
for the `$wanted` parameter. Each row contains the matching `Animal`'s name
in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of list type.
### intersects
#### Example Use
```graphql
{
Animal {
alias @filter(op_name: "intersects", value: ["$wanted"])
name @output(out_name: "animal_name")
}
}
```
This returns one row for every `Animal` vertex whose list of aliases has a non-empty intersection
with the list of values supplied for the `$wanted` parameter.
Each row contains the matching `Animal`'s name in a column named `animal_name`.
#### Constraints and Rules
- Must be on a property field of list type.
### has_edge_degree
#### Example Use
```graphql
{
Animal {
name @output(out_name: "animal_name")
out_Animal_ParentOf @filter(op_name: "has_edge_degree", value: ["$child_count"]) @optional {
uuid
}
}
}
```
This returns one row for every `Animal` vertex that has exactly `$child_count` children
(i.e. where the `out_Animal_ParentOf` edge appears exactly `$child_count` times).
Each row contains the matching `Animal`'s name, in a column named `animal_name`.
The `uuid` field within the `out_Animal_ParentOf` vertex field is added simply to satisfy
the GraphQL syntax rule that requires at least one field to exist within any `{}`.
Since this field is not marked with any directive, it has no effect on the query.
*N.B.:* Please note the `@optional` directive on the vertex field being filtered above.
If in your use case you expect to set `$child_count` to 0, you must also mark that
vertex field `@optional`. Recall that absence of `@optional` implies that at least one
such edge must exist. If the `has_edge_degree` filter is used with a parameter set to 0,
that requires the edge to not exist. Therefore, if the `@optional` is not present in this situation,
no valid result sets can be produced, and the resulting query will return no results.
#### Constraints and Rules
- Must be on a vertex field that is not the root vertex of the query.
- Tagged values are not supported as parameters for this filter.
- If the runtime parameter for this operator can be `0`, it is *strongly recommended* to also apply
`@optional` to the vertex field being filtered (see N.B. above for details).
## Type coercions
Type coercions are operations that create a new scope whose type is different than the type of the
enclosing scope of the coercion -- they coerce the enclosing scope into a different type.
Type coercions are represented with GraphQL inline fragments.
#### Example Use
```graphql
{
Species {
name @output(out_name: "species_name")
out_Species_Eats {
... on Food {
name @output(out_name: "food_name")
}
}
}
}
```
Here, the `out_Species_Eats` vertex field is of the `Union__Food__FoodOrSpecies__Species` union type. To proceed
with the query, the user must choose which of the types in the `Union__Food__FoodOrSpecies__Species` union to use.
In this example, `... on Food` indicates that the `Food` type was chosen, and any vertices
at that scope that are not of type `Food` are filtered out and discarded.
```graphql
{
Species {
name @output(out_name: "species_name")
out_Entity_Related {
... on Species {
name @output(out_name: "food_name")
}
}
}
}
```
In this query, the `out_Entity_Related` is of `Entity` type. However, the query only wants to
return results where the related entity is a `Species`, which `... on Species` ensures is the case.
## Meta fields
### \_\_typename
The compiler supports the standard GraphQL meta field `__typename`, which returns the runtime type
of the scope where the field is found. Assuming the GraphQL schema matches the database's schema,
the runtime type will always be a subtype of (or exactly equal to) the static type of the scope
determined by the GraphQL type system. Below, we provide an example query in which
the runtime type is a subtype of the static type, but is not equal to it.
The `__typename` field is treated as a property field of type `String`, and supports
all directives that can be applied to any other property field.
#### Example Use
```graphql
{
Entity {
__typename @output(out_name: "entity_type")
name @output(out_name: "entity_name")
}
}
```
This query returns one row for each `Entity` vertex. The scope in which `__typename` appears is
of static type `Entity`. However, `Animal` is a type of `Entity`, as are `Species`, `Food`,
and others. Vertices of all subtypes of `Entity` will therefore be returned, and the `entity_type`
column that outputs the `__typename` field will show their runtime type: `Animal`, `Species`,
`Food`, etc.
### \_x\_count
The `_x_count` meta field is a non-standard meta field defined by the GraphQL compiler that makes it
possible to interact with the _number_ of elements in a scope marked `@fold`. By applying directives
like `@output` and `@filter` to this meta field, queries can output the number of elements captured
in the `@fold` and filter down results to select only those with the desired fold sizes.
We use the `_x_` prefix to signify that this is an extension meta field introduced by the compiler,
and not part of the canonical set of GraphQL meta fields defined by the GraphQL specification.
We do not use the GraphQL standard double-underscore (`__`) prefix for meta fields,
since all names with that prefix are
[explicitly reserved and prohibited from being used](https://facebook.github.io/graphql/draft/#sec-Reserved-Names)
in directives, fields, or any other artifacts.
#### Adding the `_x_count` meta field to your schema
Since the `_x_count` meta field is not currently part of the GraphQL standard, it has to be
explicitly added to all interfaces and types in your schema. There are two ways to do this.
The preferred way to do this is to use the `EXTENDED_META_FIELD_DEFINITIONS` constant as
a starting point for building your interfaces' and types' field descriptions:
```
from graphql import GraphQLInt, GraphQLField, GraphQLObjectType, GraphQLString
from graphql_compiler import EXTENDED_META_FIELD_DEFINITIONS
fields = EXTENDED_META_FIELD_DEFINITIONS.copy()
fields.update({
'foo': GraphQLField(GraphQLString),
'bar': GraphQLField(GraphQLInt),
# etc.
})
graphql_type = GraphQLObjectType('MyType', fields)
# etc.
```
If you are not able to programmatically define the schema, and instead simply have a pre-made
GraphQL schema object that you are able to mutate, the alternative approach is via the
`insert_meta_fields_into_existing_schema()` helper function defined by the compiler:
```
# assuming that existing_schema is your GraphQL schema object
insert_meta_fields_into_existing_schema(existing_schema)
# existing_schema was mutated in-place and all custom meta-fields were added
```
#### Example Use
```graphql
{
Animal {
name @output(out_name: "name")
out_Animal_ParentOf @fold {
_x_count @output(out_name: "number_of_children")
name @output(out_name: "child_names")
}
}
}
```
This query returns one row for each `Animal` vertex. Each row contains its name, and the number and names
of its children. While the output type of the `child_names` selection is a list of strings,
the output type of the `number_of_children` selection is an integer.
```graphql
{
Animal {
name @output(out_name: "name")
out_Animal_ParentOf @fold {
_x_count @filter(op_name: ">=", value: ["$min_children"])
@output(out_name: "number_of_children")
name @filter(op_name: "has_substring", value: ["$substr"])
@output(out_name: "child_names")
}
}
}
```
Here, we've modified the above query to add two more filtering constraints to the returned rows:
- child `Animal` vertices must contain the value of `$substr` as a substring in their name, and
- `Animal` vertices must have at least `$min_children` children that satisfy the above filter.
Importantly, any filtering on `_x_count` is applied *after* any other filters and type coercions
that are present in the `@fold` in question. This order of operations matters a lot: selecting
`Animal` vertices with 3+ children, then filtering the children based on their names is not the same
as filtering the children first, and then selecting `Animal` vertices that have 3+ children that
matched the earlier filter.
#### Constraints and Rules
- The `_x_count` field is only allowed to appear within a vertex field marked `@fold`.
- Filtering on `_x_count` is always applied *after* any other filters and type coercions present
in that `@fold`.
- Filtering or outputting the value of the `_x_count` field must always be done at the innermost
scope of the `@fold`. It is invalid to expand vertex fields within a `@fold` after filtering
or outputting the value of the `_x_count` meta field.
#### How is filtering on `_x_count` different from `@filter` with `has_edge_degree`?
The `has_edge_degree` filter allows filtering based on the number of edges of a particular type.
There are situations in which filtering with `has_edge_degree` and filtering using `=` on `_x_count`
produce equivalent queries. Here is one such pair of queries:
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @filter(op_name: "has_edge_degree", value: ["$num_animals"]) {
uuid
}
}
}
```
and
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @fold {
_x_count @filter(op_name: "=", value: ["$num_animals"])
}
}
}
```
In both of these queries, we ask for the names of the `Species` vertices that have precisely
`$num_animals` members. However, we have expressed this question in two different ways: once
as a property of the `Species` vertex ("the degree of the `in_Animal_OfSpecies` is `$num_animals`"),
and once as a property of the list of `Animal` vertices produced by the `@fold` ("the number of
elements in the `@fold` is `$num_animals`").
When we add additional filtering within the `Animal` vertices of the `in_Animal_OfSpecies` vertex
field, this distinction becomes very important. Compare the following two queries:
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @filter(op_name: "has_edge_degree", value: ["$num_animals"]) {
out_Animal_LivesIn {
name @filter(op_name: "=", value: ["$location"])
}
}
}
}
```
versus
```graphql
{
Species {
name @output(out_name: "name")
in_Animal_OfSpecies @fold {
out_Animal_LivesIn {
_x_count @filter(op_name: "=", value: ["$num_animals"])
name @filter(op_name: "=", value: ["$location"])
}
}
}
}
```
In the first, for the purposes of the `has_edge_degree` filtering, the location where the animals
live is irrelevant: the `has_edge_degree` only makes sure that the `Species` vertex has the
correct number of edges of type `in_Animal_OfSpecies`, and that's it. In contrast, the second query
ensures that only `Species` vertices that have `$num_animals` animals that live in the selected
location are returned -- the location matters since the `@filter` on the `_x_count` field applies
to the number of elements in the `@fold` scope.
## The GraphQL schema
This section assumes that the reader is familiar with the way schemas work in the
[reference implementation of GraphQL](http://graphql.org/learn/schema/).
The GraphQL schema used with the compiler must contain the custom directives and custom `Date`
and `DateTime` scalar types defined by the compiler:
```
directive @recurse(depth: Int!) on FIELD
directive @filter(value: [String!]!, op_name: String!) on FIELD | INLINE_FRAGMENT
directive @tag(tag_name: String!) on FIELD
directive @output(out_name: String!) on FIELD
directive @output_source on FIELD
directive @optional on FIELD
directive @fold on FIELD
scalar DateTime
scalar Date
```
If constructing the schema programmatically, one can simply import the the Python object
representations of the custom directives and the custom types:
```
from graphql_compiler import DIRECTIVES # the list of custom directives
from graphql_compiler import GraphQLDate, GraphQLDateTime # the custom types
```
Since the GraphQL and OrientDB type systems have different rules, there is no one-size-fits-all
solution to writing the GraphQL schema for a given database schema.
However, the following rules of thumb are useful to keep in mind:
- Generally, represent OrientDB abstract classes as GraphQL interfaces. In GraphQL's type system,
GraphQL interfaces cannot inherit from other GraphQL interfaces.
- Generally, represent OrientDB non-abstract classes as GraphQL types,
listing the GraphQL interfaces that they implement. In GraphQL's type system, GraphQL types
cannot inherit from other GraphQL types.
- Inheritance relationships between two OrientDB non-abstract classes,
or between two OrientDB abstract classes, introduce some difficulties in GraphQL.
When modelling your data in OrientDB, it's best to avoid such inheritance if possible.
- If it is impossible to avoid having two non-abstract OrientDB classes `A` and `B` such that
`B` inherits from `A`, you have two options:
- You may choose to represent the `A` OrientDB class as a GraphQL interface,
which the GraphQL type corresponding to `B` can implement.
In this case, the GraphQL schema preserves the inheritance relationship
between `A` and `B`, but sacrifices the representation of any inheritance relationships
`A` may have with any OrientDB superclasses.
- You may choose to represent both `A` and `B` as GraphQL types. The tradeoff in this case is
exactly the opposite from the previous case: the GraphQL schema
sacrifices the inheritance relationship between `A` and `B`, but preserves the
inheritance relationships of `A` with its superclasses.
In this case, it is recommended to create a GraphQL union type `A | B`,
and to use that GraphQL union type for any vertex fields that
in OrientDB would be of type `A`.
- If it is impossible to avoid having two abstract OrientDB classes `A` and `B` such that
`B` inherits from `A`, you similarly have two options:
- You may choose to represent `B` as a GraphQL type that can implement the GraphQL interface
corresponding to `A`. This makes the GraphQL schema preserve the inheritance relationship
between `A` and `B`, but sacrifices the ability for other GraphQL types to inherit from `B`.
- You may choose to represent both `A` and `B` as GraphQL interfaces, sacrificing the schema's
representation of the inheritance between `A` and `B`, but allowing GraphQL types
to inherit from both `A` and `B`. If necessary, you can then create a GraphQL
union type `A | B` and use it for any vertex fields that in OrientDB would be of type `A`.
- It is legal to fully omit classes and fields that are not representable in GraphQL. The compiler
currently does not support OrientDB's `EmbeddedMap` type nor embedded non-primitive typed fields,
so such fields can simply be omitted in the GraphQL representation of their classes.
Alternatively, the entire OrientDB class and all edges that may point to it may be omitted
entirely from the GraphQL schema.
## Execution model
Since the GraphQL compiler can target multiple different query languages, each with its own
behaviors and limitations, the execution model must also be defined as a function of the
compilation target language. While we strive to minimize the differences between
compilation targets, some differences are unavoidable.
The compiler abides by the following principles:
- When the database is queried with a compiled query string, its response must always be in the
form of a list of results.
- The precise format of each such result is defined by each compilation target separately.
- `gremlin`, `MATCH` and `SQL` return data in a tabular format, where each result is
a row of the table, and fields marked for output are columns.
- However, future compilation targets may have a different format. For example, each result
may appear in the nested tree format used by the standard GraphQL specification.
- Each such result must satisfy all directives and types in its corresponding GraphQL query.
- The returned list of results is **not** guaranteed to be complete!
- In other words, there may have been additional result sets that satisfy all directives and
types in the corresponding GraphQL query, but were not returned by the database.
- However, compilation target implementations are encouraged to return complete results
if at all practical. The `MATCH` compilation target is guaranteed to produce complete results.
### Completeness of returned results
To explain the completeness of returned results in more detail, assume the database contains
the following example graph:
```
a ---->_ x
|____ /|
_|_/
/ |____
/ \/
b ----> y
```
Let `a, b, x, y` be the values of the `name` property field of four vertices.
Let the vertices named `a` and `b` be of type `S`, and let `x` and `y` be of type `T`.
Let vertex `a` be connected to both `x` and `y` via directed edges of type `E`.
Similarly, let vertex `b` also be connected to both `x` and `y` via directed edges of type `E`.
Consider the GraphQL query:
```
{
S {
name @output(out_name: "s_name")
out_E {
name @output(out_name: "t_name")
}
}
}
```
Between the data in the database and the query's structure, it is clear that combining any of
`a` or `b` with any of `x` or `y` would produce a valid result. Therefore,
the complete result list, shown here in JSON format, would be:
```
[
{"s_name": "a", "t_name": "x"},
{"s_name": "a", "t_name": "y"},
{"s_name": "b", "t_name": "x"},
{"s_name": "b", "t_name": "y"},
]
```
This is precisely what the `MATCH` compilation target is guaranteed to produce.
The remainder of this section is only applicable to the `gremlin` compilation target. If using
`MATCH`, all of the queries listed in the remainder of this section will produce the same, complete
result list.
Since the `gremlin` compilation target does not guarantee a complete result list,
querying the database using a query string generated by the `gremlin` compilation target
will produce only a partial result list resembling the following:
```
[
{"s_name": "a", "t_name": "x"},
{"s_name": "b", "t_name": "x"},
]
```
Due to limitations in the underlying query language, `gremlin` will by default produce at most one
result for each of the starting locations in the query. The above GraphQL query started at
the type `S`, so each `s_name` in the returned result list is therefore distinct. Furthermore,
there is no guarantee (and no way to know ahead of time) whether `x` or `y` will be returned as
the `t_name` value in each result, as they are both valid results.
Users may apply the `@output_source` directive on the last scope of the query
to alter this behavior:
```graphql
{
S {
name @output(out_name: "s_name")
out_E @output_source {
name @output(out_name: "t_name")
}
}
}
```
Rather than producing at most one result for each `S`, the query will now produce
at most one result for each distinct value that can be found at `out_E`, where the directive
is applied:
```graphql
[
{"s_name": "a", "t_name": "x"},
{"s_name": "a", "t_name": "y"},
]
```
Conceptually, applying the `@output_source` directive makes it as if the query were written in
the opposite order:
```graphql
{
T {
name @output(out_name: "t_name")
in_E {
name @output(out_name: "s_name")
}
}
}
```
## SQL
The following table outlines GraphQL compiler features, and their support (if any) by various
relational database flavors:
| Feature/Dialect | Required Edges | @filter | @output | @recurse | @fold | @optional | @output_source |
|----------------------|----------------|---------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------|----------|-------|-----------|----------------|
| PostgreSQL | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| SQLite | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| Microsoft SQL Server | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| MySQL | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
| MariaDB | No | Limited, [intersects](#intersects), [has_edge_degree](#has_edge_degree), and [name_or_alias](#name_or_alias) filter unsupported | Limited, [\__typename](#__typename) output metafield unsupported | No | No | No | No |
### Configuring SQLAlchemy
Relational databases are supported by compiling to SQLAlchemy core as an intermediate
language, and then relying on SQLAlchemy's compilation of the dialect specific SQL string to query
the target database.
For the SQL backend, GraphQL types are assumed to have a SQL table of the same name, and with the
same properties. For example, a schema type
```
type Animal {
name: String
}
```
is expected to correspond to a SQLAlchemy table object of the same name, case insensitive. For this
schema type this could look like:
```python
from sqlalchemy import MetaData, Table, Column, String
# table for GraphQL type Animal
metadata = MetaData()
animal_table = Table(
'animal', # name of table matches type name from schema
metadata,
Column('name', String(length=12)), # Animal.name GraphQL field has corresponding 'name' column
)
```
If a table of the schema type name does not exist, an exception will be raised at compile time. See
[Configuring the SQL Database to Match the GraphQL Schema](#configuring-the-sql-database-to-match-the-graphql-schema)
for a possible option to resolve such naming discrepancies.
### End-To-End SQL Example
An end-to-end example including relevant GraphQL schema and SQLAlchemy engine preparation follows.
This is intended to show the setup steps for the SQL backend of the GraphQL compiler, and
does not represent best practices for configuring and running SQLAlchemy in a production system.
```python
from graphql import parse
from graphql.utils.build_ast_schema import build_ast_schema
from sqlalchemy import MetaData, Table, Column, String, create_engine
from graphql_compiler.compiler.ir_lowering_sql.metadata import SqlMetadata
from graphql_compiler import graphql_to_sql
# Step 1: Configure a GraphQL schema (note that this can also be done programmatically)
schema_text = '''
schema {
query: RootSchemaQuery
}
# IMPORTANT NOTE: all compiler directives are expected here, but not shown to keep the example brief
directive @filter(op_name: String!, value: [String!]!) on FIELD | INLINE_FRAGMENT
# < more directives here, see the GraphQL schema section of this README for more details. >
directive @output(out_name: String!) on FIELD
type Animal {
name: String
}
'''
schema = build_ast_schema(parse(schema_text))
# Step 2: For all GraphQL types, bind all corresponding SQLAlchemy Tables to a single SQLAlchemy
# metadata instance, using the expected naming detailed above.
# See https://docs.sqlalchemy.org/en/latest/core/metadata.html for more details on this step.
metadata = MetaData()
animal_table = Table(
'animal', # name of table matches type name from schema
metadata,
# Animal.name schema field has corresponding 'name' column in animal table
Column('name', String(length=12)),
)
# Step 3: Prepare a SQLAlchemy engine to query the target relational database.
# See https://docs.sqlalchemy.org/en/latest/core/engines.html for more detail on this step.
engine = create_engine('<connection string>')
# Step 4: Wrap the SQLAlchemy metadata and dialect as a SqlMetadata GraphQL compiler object
sql_metadata = SqlMetadata(engine.dialect, metadata)
# Step 5: Prepare and compile a GraphQL query against the schema
graphql_query = '''
{
Animal {
name @output(out_name: "animal_name")
@filter(op_name: "in_collection", value: ["$names"])
}
}
'''
parameters = {
'names': ['animal name 1', 'animal name 2'],
}
compilation_result = graphql_to_sql(schema, graphql_query, parameters, sql_metadata)
# Step 6: Execute compiled query against a SQLAlchemy engine/connection.
# See https://docs.sqlalchemy.org/en/latest/core/connections.html for more details.
query = compilation_result.query
query_results = [dict(result_proxy) for result_proxy in engine.execute(query)]
```
### Configuring the SQL Database to Match the GraphQL Schema
For simplicity, the SQL backend expects an exact match between SQLAlchemy Tables and GraphQL types,
and between SQLAlchemy Columns and GraphQL fields. What if the table name or column name in the
database doesn't conform to these rules? Eventually the plan is to make this aspect of the
SQL backend more configurable. In the near-term, a possible way to address this is by using
SQL views.
For example, suppose there is a table in the database called `animal_table` and it has a column
called `animal_name`. If the desired schema has type
```
type Animal {
name: String
}
```
Then this could be exposed via a view like:
```sql
CREATE VIEW animal AS
SELECT
animal_name AS name
FROM animal_table
```
At this point, the `animal` view can be used in the SQLAlchemy Table for the purposes of compiling.
## Miscellaneous
### Pretty-Printing GraphQL Queries
To pretty-print GraphQL queries, use the included pretty-printer:
```
python -m graphql_compiler.tool <input_file.graphql >output_file.graphql
```
It's modeled after Python's `json.tool`, reading from stdin and writing to stdout.
### Expanding [`@optional`](#optional) vertex fields
Including an optional statement in GraphQL has no performance issues on its own,
but if you continue expanding vertex fields within an optional scope,
there may be significant performance implications.
Going forward, we will refer to two different kinds of `@optional` directives.
- A *"simple"* optional is a vertex with an `@optional` directive that does not expand
any vertex fields within it.
For example:
```graphql
{
Animal {
name @output(out_name: "name")
in_Animal_ParentOf @optional {
name @output(out_name: "parent_name")
}
}
}
```
OrientDB `MATCH` currently allows the last step in any traversal to be optional.
Therefore, the equivalent `MATCH` traversal for the above `GraphQL` is as follows:
```
SELECT
Animal___1.name as `name`,
Animal__in_Animal_ParentOf___1.name as `parent_name`
FROM (
MATCH {
class: Animal,
as: Animal___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf___1
}
RETURN $matches
)
```
- A *"compound"* optional is a vertex with an `@optional` directive which does expand
vertex fields within it.
For example:
```graphql
{
Animal {
name @output(out_name: "name")
in_Animal_ParentOf @optional {
name @output(out_name: "parent_name")
in_Animal_ParentOf {
name @output(out_name: "grandparent_name")
}
}
}
}
```
Currently, this cannot represented by a simple `MATCH` query.
Specifically, the following is *NOT* a valid `MATCH` statement,
because the optional traversal follows another edge:
```
-- NOT A VALID QUERY
SELECT
Animal___1.name as `name`,
Animal__in_Animal_ParentOf___1.name as `parent_name`
FROM (
MATCH {
class: Animal,
as: Animal___1
}.in('Animal_ParentOf') {
optional: true,
as: Animal__in_Animal_ParentOf___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf__in_Animal_ParentOf___1
}
RETURN $matches
)
```
Instead, we represent a *compound* optional by taking an union (`UNIONALL`) of two distinct
`MATCH` queries. For instance, the `GraphQL` query above can be represented as follows:
```
SELECT EXPAND($final_match)
LET
$match1 = (
SELECT
Animal___1.name AS `name`
FROM (
MATCH {
class: Animal,
as: Animal___1,
where: (
(in_Animal_ParentOf IS null)
OR
(in_Animal_ParentOf.size() = 0)
),
}
)
),
$match2 = (
SELECT
Animal___1.name AS `name`,
Animal__in_Animal_ParentOf___1.name AS `parent_name`
FROM (
MATCH {
class: Animal,
as: Animal___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf___1
}.in('Animal_ParentOf') {
as: Animal__in_Animal_ParentOf__in_Animal_ParentOf___1
}
)
),
$final_match = UNIONALL($match1, $match2)
```
In the first case where the optional edge is not followed,
we have to explicitly filter out all vertices where the edge *could have been followed*.
This is to eliminate duplicates between the two `MATCH` selections.
The previous example is not *exactly* how we implement *compound* optionals
(we also have `SELECT` statements within `$match1` and `$match2`),
but it illustrates the the general idea.
#### Performance Penalty
If we have many *compound* optionals in the given `GraphQL`,
the above procedure results in the union of a large number of `MATCH` queries.
Specifically, for `n` compound optionals, we generate 2<sup>n</sup> different `MATCH` queries.
For each of the 2<sup>n</sup> subsets `S` of the `n` optional edges:
- We remove the `@optional` restriction for each traversal in `S`.
- For each traverse `t` in the complement of `S`, we entirely discard `t`
along with all the vertices and directives within it, and we add a filter
on the previous traverse to ensure that the edge corresponding to `t` does not exist.
Therefore, we get a performance penalty that grows exponentially
with the number of *compound* optional edges.
This is important to keep in mind when writing queries with many optional directives.
If some of those *compound* optionals contain `@optional` vertex fields of their own,
the performance penalty grows since we have to account for all possible subsets of `@optional`
statements that can be satisfied simultaneously.
### Optional `type_equivalence_hints` parameter
This compilation parameter is a workaround for the limitations of the GraphQL and Gremlin
type systems:
- GraphQL does not allow `type` to inherit from another `type`, only to implement an `interface`.
- Gremlin does not have first-class support for inheritance at all.
Assume the following GraphQL schema:
```graphql
type Animal {
name: String
}
type Cat {
name: String
}
type Dog {
name: String
}
union AnimalCatDog = Animal | Cat | Dog
type Foo {
adjacent_animal: AnimalCatDog
}
```
An appropriate `type_equivalence_hints` value here would be `{ Animal: AnimalCatDog }`.
This lets the compiler know that the `AnimalCatDog` union type is implicitly equivalent to
the `Animal` type, as there are no other types that inherit from `Animal` in the database schema.
This allows the compiler to perform accurate type coercions in Gremlin, as well as optimize away
type coercions across edges of union type if the coercion is coercing to the
union's equivalent type.
Setting `type_equivalence_hints = { Animal: AnimalCatDog }` during compilation
would enable the use of a `@fold` on the `adjacent_animal` vertex field of `Foo`:
```graphql
{
Foo {
adjacent_animal @fold {
... on Animal {
name @output(out_name: "name")
}
}
}
}
```
### SchemaGraph
When building a GraphQL schema from the database metadata, we first build a `SchemaGraph` from
the metadata and then, from the `SchemaGraph`, build the GraphQL schema. The `SchemaGraph` is also
a representation of the underlying database schema, but it has three main advantages that make it a
more powerful schema introspection tool:
1. It's able to store and expose a schema's index information. The interface for accessing index
information is provisional though and might change in the near future.
2. Its classes are allowed to inherit from non-abstract classes.
3. It exposes many utility functions, such as `get_subclass_set`, that make it easier to explore
the schema.
See below for a mock example of how to build and use the `SchemaGraph`:
```python
from graphql_compiler.schema_generation.orientdb.schema_graph_builder import (
get_orientdb_schema_graph
)
from graphql_compiler.schema_generation.orientdb.utils import (
ORIENTDB_INDEX_RECORDS_QUERY, ORIENTDB_SCHEMA_RECORDS_QUERY
)
# Get schema metadata from hypothetical Animals database.
client = your_function_that_returns_an_orientdb_client()
schema_records = client.command(ORIENTDB_SCHEMA_RECORDS_QUERY)
schema_data = [record.oRecordData for record in schema_records]
# Get index data.
index_records = client.command(ORIENTDB_INDEX_RECORDS_QUERY)
index_query_data = [record.oRecordData for record in index_records]
# Build SchemaGraph.
schema_graph = get_orientdb_schema_graph(schema_data, index_query_data)
# Get all the subclasses of a class.
print(schema_graph.get_subclass_set('Animal'))
# {'Animal', 'Dog'}
# Get all the outgoing edge classes of a vertex class.
print(schema_graph.get_vertex_schema_element_or_raise('Animal').out_connections)
# {'Animal_Eats', 'Animal_FedAt', 'Animal_LivesIn'}
# Get the vertex classes allowed as the destination vertex of an edge class.
print(schema_graph.get_edge_schema_element_or_raise('Animal_Eats').out_connections)
# {'Fruit', 'Food'}
# Get the superclass of all classes allowed as the destination vertex of an edge class.
print(schema_graph.get_edge_schema_element_or_raise('Animal_Eats').base_out_connection)
# Food
# Get the unique indexes defined on a class.
print(schema_graph.get_unique_indexes_for_class('Animal'))
# [IndexDefinition(name='uuid', 'base_classname'='Animal', fields={'uuid'}, unique=True, ordered=False, ignore_nulls=False)]
```
In the future, we plan to add `SchemaGraph` generation from SQLAlchemy metadata. We also plan to
add a mechanism where one can query a `SchemaGraph` using GraphQL queries.
### Cypher query parameters
RedisGraph [doesn't support query parameters](https://github.com/RedisGraph/RedisGraph/issues/544#issuecomment-507963576), so we perform manual parameter interpolation in the
`graphql_to_redisgraph_cypher` function. However, for Neo4j, we can use Neo4j's client to do
parameter interpolation on its own so that we don't reinvent the wheel.
The function `insert_arguments_into_query` does so based on the query language, which isn't
fine-grained enough here-- for Cypher backends, we only want to insert parameters if the backend
is RedisGraph, but not if it's Neo4j.
Instead, the correct approach for Neo4j Cypher is as follows, given a Neo4j Python client called `neo4j_client`:
```python
compilation_result = compile_graphql_to_cypher(
schema, graphql_query, type_equivalence_hints=type_equivalence_hints)
with neo4j_client.driver.session() as session:
result = session.run(compilation_result.query, parameters)
```
## Amending Parsed Custom Scalar Types
Information about the description, serialization and parsing of custom scalar type
objects is lost when a GraphQL schema is parsed from a string. This causes issues when
working with custom scalar type objects. In order to avoid these issues, one can use the code
snippet below to amend the definitions of the custom scalar types used by the compiler.
```python
from graphql_compiler.schema import CUSTOM_SCALAR_TYPES
from graphql_compiler.schema_generation.utils import amend_custom_scalar_types
amend_custom_scalar_types(your_schema, CUSTOM_SCALAR_TYPES)
```
## FAQ
**Q: Do you really use GraphQL, or do you just use GraphQL-like syntax?**
A: We really use GraphQL. Any query that the compiler will accept is entirely valid GraphQL,
and we actually use the Python port of the GraphQL core library for parsing and type checking.
However, since the database queries produced by compiling GraphQL are subject to the limitations
of the database system they run on, our execution model is somewhat different compared to
the one described in the standard GraphQL specification. See the
[Execution model](#execution-model) section for more details.
**Q: Does this project come with a GraphQL server implementation?**
A: No -- there are many existing frameworks for running a web server. We simply built a tool
that takes GraphQL query strings (and their parameters) and returns a query string you can
use with your database. The compiler does not execute the query string against the database,
nor does it deserialize the results. Therefore, it is agnostic to the choice of
server framework and database client library used.
**Q: Do you plan to support other databases / more GraphQL features in the future?**
A: We'd love to, and we could really use your help! Please consider contributing to this project
by opening issues, opening pull requests, or participating in discussions.
**Q: I think I found a bug, what do I do?**
A: Please check if an issue has already been created for the bug, and open a new one if not.
Make sure to describe the bug in as much detail as possible, including any stack traces or
error messages you may have seen, which database you're using, and what query you compiled.
**Q: I think I found a security vulnerability, what do I do?**
A: Please reach out to us at
[graphql-compiler-maintainer@kensho.com](mailto:graphql-compiler-maintainer@kensho.com)
so we can triage the issue and take appropriate action.
## License
Licensed under the Apache 2.0 License. Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
Copyright 2017-present Kensho Technologies, LLC. The present date is determined by the timestamp
of the most recent commit in the repository.
%prep
%autosetup -n graphql-compiler-1.11.0
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-graphql-compiler -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Wed May 31 2023 Python_Bot <Python_Bot@openeuler.org> - 1.11.0-1
- Package Spec generated
|