interstellar 0.2.0

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

This document provides comprehensive documentation for the GQL (Graph Query Language) implementation in Interstellar.

## Table of Contents

1. [Overview](#overview)
2. [Architecture](#architecture)
3. [Quick Start](#quick-start)
4. [Query Syntax Reference](#query-syntax-reference)
5. [Pattern Matching](#pattern-matching)
6. [Expression Types](#expression-types)
7. [Operators](#operators)
8. [Built-in Functions](#built-in-functions)
9. [Aggregation](#aggregation)
10. [Advanced Features](#advanced-features)
11. [Mutation Operations](#mutation-operations)
12. [Error Handling](#error-handling)
13. [Limitations](#limitations)

---

## Overview

GQL is a declarative query language for property graphs, offering a SQL-like syntax for pattern matching, data retrieval, and mutations. The Interstellar GQL implementation provides:

- **Pattern Matching**: Find subgraphs using intuitive ASCII-art syntax
- **Filtering**: WHERE clause with comparison, logical, and string operators
- **Projection**: RETURN clause for selecting and transforming results
- **Aggregation**: COUNT, SUM, AVG, MIN, MAX, COLLECT functions
- **Sorting & Pagination**: ORDER BY, LIMIT, OFFSET
- **Mutations**: CREATE, SET, REMOVE, DELETE, DETACH DELETE, MERGE
- **Advanced Features**: UNION, OPTIONAL MATCH, EXISTS, CASE expressions, WITH PATH, WITH clause
- **Query Parameters**: Parameterized queries with `$paramName` syntax
- **LET Clause**: Bind intermediate computed values to variables
- **List Comprehensions**: Transform and filter lists with `[x IN list | expr]` syntax
- **Map Literals**: Create map values with `{key: value}` syntax
- **String Concatenation**: `||` operator for string operations
- **Inline WHERE**: Filter patterns directly within node/edge definitions
- **Regular Expressions**: Pattern matching with `=~` operator
- **REDUCE Function**: Fold/accumulate over lists
- **List Predicates**: ALL, ANY, NONE, SINGLE quantifier expressions
- **HAVING Clause**: Filter aggregated results post-GROUP BY

---

## Architecture

### Pipeline

The GQL implementation follows a pipeline architecture:

```
GQL Query Text → Parser (pest) → AST → Compiler/Executor → Results
```

| Stage | Description |
|-------|-------------|
| **Parser** | Converts GQL text into a typed AST using pest PEG grammar |
| **AST** | Typed representation of query structure |
| **Compiler** | Transforms read-only AST into traversal operations |
| **Mutation Executor** | Executes mutation statements directly on storage |

### Module Structure

```
src/gql/
├── mod.rs        # Public API exports
├── grammar.pest  # PEG grammar definition (344 lines)
├── ast.rs        # AST type definitions
├── parser.rs     # Parser implementation
├── compiler.rs   # Query compiler for read operations
├── mutation.rs   # Mutation execution engine
└── error.rs      # Error types (ParseError, CompileError, MutationError)
```

### Read vs Write Operations

| Operation Type | Access | Entry Point |
|---------------|--------|-------------|
| Read queries | `GraphSnapshot` (immutable) | `snapshot.gql(query)` or `compile(&query, &snapshot)` |
| Mutations | `GraphStorageMut` (mutable) | `execute_mutation(&stmt, &mut storage)` |

---

## Quick Start

### Read Queries

The simplest way to execute a GQL query:

```rust
use interstellar::prelude::*;

// Create a graph with data
let graph = Graph::new();
graph.add_vertex("Person", props! {
    "name" => "Alice",
    "age" => 30i64
});

let snapshot = graph.snapshot();

// Execute GQL query
let results = snapshot.gql("MATCH (n:Person) RETURN n").unwrap();
assert_eq!(results.len(), 1);
```

### Mutations

For mutations (CREATE, SET, DELETE, etc.), use `execute_mutation` with mutable storage:

```rust
use interstellar::gql::{parse_statement, execute_mutation};
use interstellar::prelude::*;

let graph = Graph::new();
let mut storage = graph.as_storage_mut();

// CREATE a new vertex
let stmt = parse_statement("CREATE (n:Person {name: 'Alice', age: 30})").unwrap();
execute_mutation(&stmt, &mut storage).unwrap();

drop(storage);  // Release mutable borrow

assert_eq!(graph.snapshot().vertex_count(), 1);

// UPDATE with SET
let mut storage = graph.as_storage_mut();
let stmt = parse_statement("MATCH (n:Person {name: 'Alice'}) SET n.age = 31").unwrap();
execute_mutation(&stmt, &mut storage).unwrap();

// DELETE
let stmt = parse_statement("MATCH (n:Person {name: 'Alice'}) DELETE n").unwrap();
execute_mutation(&stmt, &mut storage).unwrap();
```

---

## Query Syntax Reference

### Complete Query Structure

```
[MATCH pattern [, pattern ...]]
[OPTIONAL MATCH pattern [, pattern ...]]
[WITH PATH [AS alias]]
[UNWIND expression AS variable]
[WHERE expression]
[LET variable = expression]...
[WITH [DISTINCT] expression [AS alias] [, ...]
  [WHERE expression]
  [ORDER BY expression [ASC|DESC] [, ...]]
  [LIMIT n [OFFSET|SKIP m]]]...
RETURN [DISTINCT] expression [AS alias] [, ...]
[GROUP BY expression [, ...]]
[HAVING expression]
[ORDER BY expression [ASC|DESC] [, ...]]
[LIMIT n [OFFSET|SKIP m]]
[UNION [ALL] query]
```

### MATCH Clause

The `MATCH` clause specifies patterns to find in the graph.

```sql
-- Match all Person vertices
MATCH (n:Person) RETURN n

-- Match with property constraint
MATCH (n:Person {name: 'Alice'}) RETURN n

-- Match connected vertices
MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN a, b

-- Multiple patterns (comma-separated)
MATCH (a:Person), (b:Team) RETURN a, b
```

### OPTIONAL MATCH Clause

`OPTIONAL MATCH` matches patterns if possible, producing `null` values if no match is found (similar to SQL LEFT JOIN).

```sql
-- Find all players, with their championship teams (if any)
MATCH (p:Player)
OPTIONAL MATCH (p)-[:won_championship_with]->(t:Team)
RETURN p.name, t.name

-- Players without championships will have null for t.name
```

### WITH PATH Clause

Enables path tracking for retrieving the traversal path using the `path()` function.

```sql
MATCH (p1:Player)-[:played_for]->(t:Team)<-[:played_for]-(p2:Player)
WITH PATH
RETURN path(), p2.name
```

### UNWIND Clause

Expands a list into individual rows.

```sql
-- Expand a literal list
UNWIND [1, 2, 3] AS num
RETURN num * 2
-- Returns: 2, 4, 6

-- Expand collected values
MATCH (p:Player)
UNWIND collect(p.name) AS name
RETURN name
```

### WHERE Clause

Filters results using boolean expressions.

```sql
-- Comparison operators
MATCH (p:Person) WHERE p.age > 25 RETURN p

-- Combined conditions
MATCH (p:Person)
WHERE p.age >= 25 AND p.age <= 35
RETURN p

-- String matching
MATCH (p:Person)
WHERE p.name STARTS WITH 'A'
RETURN p

-- Null checks
MATCH (p:Person)
WHERE p.email IS NOT NULL
RETURN p

-- List membership
MATCH (p:Person)
WHERE p.status IN ['active', 'pending']
RETURN p

-- EXISTS subquery
MATCH (p:Player)
WHERE EXISTS { (p)-[:won_championship_with]->() }
RETURN p.name
```

### RETURN Clause

Specifies what data to return.

```sql
-- Return entire vertex
MATCH (n:Person) RETURN n

-- Return specific properties
MATCH (n:Person) RETURN n.name, n.age

-- With aliases
MATCH (n:Person) RETURN n.name AS personName, n.age AS years

-- Return distinct values
MATCH (n:Person) RETURN DISTINCT n.city

-- Return literals
MATCH (n:Person) RETURN n.name, 'constant' AS label

-- Return computed expressions
MATCH (n:Person) RETURN n.name, n.age * 12 AS ageInMonths
```

### GROUP BY Clause

Groups results for aggregation.

```sql
-- Count players by position
MATCH (p:Player)
RETURN p.position, count(*)
GROUP BY p.position

-- Average age by team
MATCH (p:Player)-[:plays_for]->(t:Team)
RETURN t.name, avg(p.age)
GROUP BY t.name
```

### HAVING Clause

The `HAVING` clause filters results after aggregation, similar to SQL's HAVING. Use it to filter on aggregate values.

```sql
-- Filter groups by aggregate value
MATCH (p:Player)-[:plays_for]->(t:Team)
RETURN t.name, COUNT(*) AS playerCount
GROUP BY t.name
HAVING playerCount > 10

-- Filter by average
MATCH (p:Player)-[:plays_for]->(t:Team)
RETURN t.name, AVG(p.points) AS avgPoints
GROUP BY t.name
HAVING avgPoints > 15

-- Multiple conditions in HAVING
MATCH (p:Player)-[:plays_for]->(t:Team)
RETURN t.name, COUNT(*) AS count, AVG(p.points) AS avg
GROUP BY t.name
HAVING count >= 5 AND avg > 10
```

**HAVING vs WHERE:**

| Clause | When Applied | Use For |
|--------|--------------|---------|
| `WHERE` | Before aggregation | Filter individual rows |
| `HAVING` | After aggregation | Filter aggregated groups |

```sql
-- Combined WHERE and HAVING
MATCH (p:Player)-[:plays_for]->(t:Team)
WHERE p.active = true              -- Filter before grouping
RETURN t.name, COUNT(*) AS count
GROUP BY t.name
HAVING count > 5                   -- Filter after grouping
```

### ORDER BY Clause

Sorts results.

```sql
-- Ascending (default)
MATCH (p:Person) RETURN p ORDER BY p.age

-- Descending
MATCH (p:Person) RETURN p ORDER BY p.age DESC

-- Multiple sort keys
MATCH (p:Person)
RETURN p
ORDER BY p.age DESC, p.name ASC
```

### LIMIT and OFFSET Clauses

Pagination support. `SKIP` is supported as an alias for `OFFSET`.

```sql
-- First 10 results
MATCH (p:Person) RETURN p LIMIT 10

-- Skip 20, take 10 (using OFFSET)
MATCH (p:Person) RETURN p LIMIT 10 OFFSET 20

-- Skip 20, take 10 (using SKIP alias)
MATCH (p:Person) RETURN p LIMIT 10 SKIP 20
```

### UNION Clause

Combines results from multiple queries.

```sql
-- UNION (deduplicates results)
MATCH (p:Player)-[:played_for]->(t:Team) RETURN t.name
UNION
MATCH (p:Player)-[:won_championship_with]->(t:Team) RETURN t.name

-- UNION ALL (keeps duplicates)
MATCH (p:Player)-[:played_for]->(t:Team) RETURN t.name
UNION ALL
MATCH (p:Player)-[:won_championship_with]->(t:Team) RETURN t.name
```

### WITH Clause

The `WITH` clause allows intermediate result projection and filtering within a query. It enables query chaining by passing computed values between query parts.

**Basic Syntax:**

```sql
MATCH (pattern)
WITH expression [AS alias] [, ...]
[WHERE expression]
[ORDER BY expression [ASC|DESC]]
[LIMIT n [OFFSET|SKIP m]]
RETURN ...
```

**Basic Projection:**

```sql
-- Pass selected properties to next stage
MATCH (p:Player)-[:plays_for]->(t:Team)
WITH p.name AS playerName, t.name AS teamName
RETURN playerName, teamName
```

**Aggregation in WITH:**

```sql
-- Count friends and filter by count
MATCH (p:Person)-[:KNOWS]->(friend)
WITH p, COUNT(friend) AS friendCount
WHERE friendCount > 5
RETURN p.name, friendCount

-- Calculate statistics before further processing
MATCH (p:Player)
WITH p.position AS position, AVG(p.points) AS avgPoints, COUNT(*) AS count
WHERE count > 3
RETURN position, avgPoints
ORDER BY avgPoints DESC
```

**WHERE After WITH:**

```sql
-- Filter on computed values
MATCH (p:Player)-[:plays_for]->(t:Team)
WITH t, COUNT(p) AS playerCount
WHERE playerCount >= 10
RETURN t.name, playerCount
```

**WITH DISTINCT:**

```sql
-- Remove duplicate rows
MATCH (p:Player)-[:played_for]->(t:Team)
WITH DISTINCT t.conference AS conference
RETURN conference
```

**ORDER BY and LIMIT in WITH:**

```sql
-- Get top 5 scorers, then find their teams
MATCH (p:Player)
WITH p
ORDER BY p.points DESC
LIMIT 5
RETURN p.name, p.points
```

**Chaining Multiple WITH Clauses:**

```sql
MATCH (p:Player)-[:plays_for]->(t:Team)
WITH t, COUNT(p) AS playerCount
WITH t.name AS teamName, playerCount
WHERE playerCount > 10
RETURN teamName, playerCount
```

**Complete Example:**

```sql
-- Find teams with high-scoring players and get their average
MATCH (p:Player)-[:plays_for]->(t:Team)
WITH t, AVG(p.points) AS avgPoints, MAX(p.points) AS topScore
WHERE avgPoints > 15
RETURN t.name AS team, avgPoints, topScore
ORDER BY avgPoints DESC
LIMIT 10
```

---

## Pattern Matching

Patterns describe the graph structure to match using an intuitive ASCII-art syntax.

### Node Patterns

Node patterns are enclosed in parentheses and can include variable bindings, labels, and property constraints.

| Syntax | Description |
|--------|-------------|
| `(n)` | Any vertex, bound to variable `n` |
| `(n:Person)` | Vertex with label `Person` |
| `(n:Person:Employee)` | Vertex with multiple labels |
| `(n {name: 'Alice'})` | Vertex with property constraint |
| `(n:Person {name: 'Alice'})` | Label and property constraint |
| `(:Person)` | Anonymous (unbound) vertex with label |
| `()` | Any vertex (anonymous) |

**Examples:**

```sql
-- Match any vertex
MATCH (n) RETURN n

-- Match by label
MATCH (p:Person) RETURN p

-- Match by multiple labels
MATCH (e:Person:Employee) RETURN e

-- Match by property value
MATCH (p:Person {name: 'Alice', age: 30}) RETURN p
```

### Edge Patterns

Edge patterns specify relationship types and directions.

| Syntax | Description |
|--------|-------------|
| `-[:KNOWS]->` | Outgoing edge with label `KNOWS` |
| `<-[:KNOWS]-` | Incoming edge with label `KNOWS` |
| `-[:KNOWS]-` | Bidirectional (either direction) |
| `-[e:KNOWS]->` | Edge bound to variable `e` |
| `-[]->` | Any outgoing edge |
| `-[e]->` | Any outgoing edge, bound to `e` |

**Edge Direction Summary:**

| Arrow | Direction | Traversal Step |
|-------|-----------|----------------|
| `-->` | Outgoing | `out()` |
| `<--` | Incoming | `in_()` |
| `--` | Both | `both()` |

**Examples:**

```sql
-- Outgoing relationship
MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN a, b

-- Incoming relationship
MATCH (a:Person)<-[:WORKS_FOR]-(b:Person) RETURN a, b

-- Either direction
MATCH (a:Person)-[:KNOWS]-(b:Person) RETURN a, b

-- Bind edge to variable
MATCH (a)-[r:KNOWS]->(b) RETURN a, r, b

-- Multiple relationship types (match any)
MATCH (a)-[:KNOWS|:WORKS_WITH]->(b) RETURN a, b
```

### Variable-Length Paths

Variable-length paths match paths of varying lengths using quantifiers.

| Syntax | Min | Max | Description |
|--------|-----|-----|-------------|
| `*` | 0 | 10 (default) | Any number of hops |
| `*3` | 3 | 3 | Exactly 3 hops |
| `*2..5` | 2 | 5 | Between 2 and 5 hops |
| `*..5` | 0 | 5 | Up to 5 hops |
| `*2..` | 2 | 10 (default) | At least 2 hops |

**Examples:**

```sql
-- Any number of KNOWS hops
MATCH (a:Person)-[:KNOWS*]->(b:Person)
RETURN a.name, b.name

-- Exactly 2 hops
MATCH (a:Person)-[:KNOWS*2]->(b:Person)
RETURN a.name, b.name

-- Between 1 and 3 hops
MATCH (a:Person)-[:KNOWS*1..3]->(b:Person)
RETURN a.name, b.name

-- Friends of friends (2 hops)
MATCH (me:Person {name: 'Alice'})-[:KNOWS*2]->(fof:Person)
WHERE NOT (me)-[:KNOWS]->(fof)
RETURN fof.name
```

### EXISTS Patterns

The `EXISTS` expression checks if a subpattern matches from the current context.

```sql
-- Players who have won championships
MATCH (p:Player)
WHERE EXISTS { (p)-[:won_championship_with]->(:Team) }
RETURN p.name

-- Players who have NOT won championships  
MATCH (p:Player)
WHERE NOT EXISTS { (p)-[:won_championship_with]->() }
RETURN p.name

-- Complex existence check
MATCH (p:Player)
WHERE EXISTS { (p)-[:played_for]->(:Team {name: 'Lakers'}) }
RETURN p.name
```

---

## Expression Types

Expressions are used in WHERE, RETURN, ORDER BY, and other clauses.

### Literals

| Type | Examples | Description |
|------|----------|-------------|
| String | `'hello'`, `'Alice'` | Single-quoted strings. Use `''` to escape quotes. |
| Integer | `42`, `-7`, `0` | 64-bit signed integers |
| Float | `3.14`, `-0.5` | 64-bit floating point |
| Boolean | `true`, `false` | Case-insensitive |
| Null | `null` | Represents missing/unknown value |
| List | `[1, 2, 3]`, `['a', 'b']` | Ordered collection |

### Variable References

```sql
-- Reference a bound variable
MATCH (n:Person) RETURN n

-- Variables can be nodes or edges
MATCH (a)-[r:KNOWS]->(b) RETURN a, r, b
```

### Property Access

```sql
-- Access vertex property
MATCH (n:Person) RETURN n.name

-- Access edge property
MATCH (a)-[r:KNOWS]->(b) RETURN r.since

-- Nested in expressions
MATCH (n:Person) WHERE n.age > 21 RETURN n
```

### CASE Expressions

Conditional logic with WHEN/THEN/ELSE branches.

```sql
-- Simple categorization
MATCH (p:Player)
RETURN p.name,
  CASE
    WHEN p.age > 35 THEN 'Veteran'
    WHEN p.age > 28 THEN 'Prime'
    ELSE 'Young'
  END AS category

-- Multiple conditions
MATCH (s:Student)
RETURN s.name,
  CASE
    WHEN s.score >= 90 THEN 'A'
    WHEN s.score >= 80 THEN 'B'
    WHEN s.score >= 70 THEN 'C'
    ELSE 'F'
  END AS grade

-- CASE without ELSE returns null
MATCH (p:Person)
RETURN CASE WHEN p.age > 65 THEN 'Senior' END
```

---

## Operators

### Operator Precedence (highest to lowest)

| Precedence | Operators | Description |
|------------|-----------|-------------|
| 1 | `()` | Parentheses |
| 2 | `-` (unary) | Negation |
| 3 | `^` | Exponentiation |
| 4 | `*`, `/`, `%` | Multiplication, Division, Modulo |
| 5 | `+`, `-` | Addition, Subtraction |
| 6 | `\|\|` | String Concatenation |
| 7 | `=`, `<>`, `<`, `<=`, `>`, `>=` | Comparison |
| 7 | `=~` | Regular expression match |
| 7 | `CONTAINS`, `STARTS WITH`, `ENDS WITH` | String comparison |
| 7 | `IS NULL`, `IS NOT NULL` | Null checks |
| 7 | `IN`, `NOT IN` | List membership |
| 8 | `NOT` | Logical negation |
| 9 | `AND` | Logical conjunction |
| 10 | `OR` | Logical disjunction |

### Comparison Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `=` | Equality | `n.age = 30` |
| `<>` or `!=` | Inequality | `n.status <> 'inactive'` |
| `<` | Less than | `n.age < 30` |
| `<=` | Less than or equal | `n.age <= 30` |
| `>` | Greater than | `n.age > 30` |
| `>=` | Greater than or equal | `n.age >= 30` |

### Logical Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `AND` | Logical AND | `n.age > 20 AND n.age < 40` |
| `OR` | Logical OR | `n.city = 'NYC' OR n.city = 'LA'` |
| `NOT` | Logical NOT | `NOT n.inactive` |

### Arithmetic Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `+` | Addition | `n.salary + 1000` |
| `-` | Subtraction | `n.age - 5` |
| `*` | Multiplication | `n.price * n.quantity` |
| `/` | Division | `n.total / n.count` |
| `%` | Modulo | `n.value % 10` |
| `^` | Exponentiation | `n.base ^ 2` |

### String Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `\|\|` | String concatenation | `p.firstName \|\| ' ' \|\| p.lastName` |
| `CONTAINS` | Substring match | `n.name CONTAINS 'son'` |
| `STARTS WITH` | Prefix match | `n.name STARTS WITH 'A'` |
| `ENDS WITH` | Suffix match | `n.email ENDS WITH '.com'` |

### Null Check Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `IS NULL` | Check for null | `n.email IS NULL` |
| `IS NOT NULL` | Check for non-null | `n.email IS NOT NULL` |

### List Membership Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `IN` | Value in list | `n.status IN ['active', 'pending']` |
| `NOT IN` | Value not in list | `n.status NOT IN ['deleted', 'banned']` |

### Regular Expression Operators

The `=~` operator performs regular expression pattern matching against strings.

| Operator | Description | Example |
|----------|-------------|---------|
| `=~` | Regex match | `n.email =~ '.*@gmail\\.com$'` |

**Basic Usage:**

```sql
-- Match emails ending with @gmail.com
MATCH (p:Person)
WHERE p.email =~ '.*@gmail\\.com$'
RETURN p.name, p.email

-- Match names starting with 'J'
MATCH (p:Person)
WHERE p.name =~ '^J.*'
RETURN p.name

-- Match phone numbers with pattern
MATCH (c:Contact)
WHERE c.phone =~ '^\\d{3}-\\d{3}-\\d{4}$'
RETURN c.name, c.phone
```

**Case-Insensitive Matching:**

Use the `(?i)` flag at the start of the pattern for case-insensitive matching:

```sql
-- Case-insensitive match
MATCH (p:Person)
WHERE p.name =~ '(?i)^john.*'
RETURN p.name

-- Match 'Smith', 'SMITH', 'smith', etc.
MATCH (p:Person)
WHERE p.lastName =~ '(?i)smith'
RETURN p.name
```

**Common Regex Patterns:**

| Pattern | Description | Example |
|---------|-------------|---------|
| `.*` | Any characters | `'.*test.*'` matches 'testing' |
| `^` | Start of string | `'^Hello'` matches 'Hello World' |
| `$` | End of string | `'world$'` matches 'Hello world' |
| `\\d` | Any digit | `'\\d+'` matches '123' |
| `\\w` | Word character | `'\\w+'` matches 'hello' |
| `[abc]` | Character class | `'[aeiou]'` matches vowels |
| `(?i)` | Case insensitive | `'(?i)hello'` matches 'HELLO' |

**Note:** Backslashes must be escaped in GQL string literals (`\\d` instead of `\d`).

---

## Built-in Functions

### String Functions

| Function | Description | Example |
|----------|-------------|---------|
| `TOUPPER(s)` / `UPPER(s)` | Convert to uppercase | `TOUPPER(n.name)` → `'ALICE'` |
| `TOLOWER(s)` / `LOWER(s)` | Convert to lowercase | `TOLOWER(n.name)` → `'alice'` |
| `SIZE(s)` / `LENGTH(s)` | String/list length | `SIZE(n.name)` → `5` |
| `TRIM(s)` | Remove leading/trailing whitespace | `TRIM('  hello  ')` → `'hello'` |
| `LTRIM(s)` | Remove leading whitespace | `LTRIM('  hello')` → `'hello'` |
| `RTRIM(s)` | Remove trailing whitespace | `RTRIM('hello  ')` → `'hello'` |
| `SUBSTRING(s, start[, len])` | Extract substring | `SUBSTRING('hello', 1, 3)` → `'ell'` |
| `REPLACE(s, search, repl)` | Replace occurrences | `REPLACE('hello', 'l', 'L')` → `'heLLo'` |

**Examples:**

```sql
MATCH (p:Person)
RETURN TOUPPER(p.name) AS upperName

MATCH (p:Person)
WHERE SIZE(p.name) > 5
RETURN p.name

MATCH (p:Person)
RETURN SUBSTRING(p.email, 0, SUBSTRING(p.email, '@') - 1) AS username
```

### Numeric Functions

| Function | Description | Example |
|----------|-------------|---------|
| `ABS(n)` | Absolute value | `ABS(-5)` → `5` |
| `CEIL(n)` / `CEILING(n)` | Round up | `CEIL(4.2)` → `5.0` |
| `FLOOR(n)` | Round down | `FLOOR(4.8)` → `4.0` |
| `ROUND(n)` | Round to nearest | `ROUND(4.5)` → `5.0` |
| `SIGN(n)` | Sign of number (-1, 0, 1) | `SIGN(-5)` → `-1` |
| `SQRT(n)` | Square root | `SQRT(16)` → `4.0` |
| `POW(base, exp)` / `POWER(base, exp)` | Exponentiation | `POW(2, 3)` → `8.0` |
| `LOG(n)` / `LN(n)` | Natural logarithm | `LOG(e)` → `1.0` |
| `LOG10(n)` | Base-10 logarithm | `LOG10(100)` → `2.0` |
| `EXP(n)` | e^n | `EXP(1)` → `2.718...` |

**Examples:**

```sql
MATCH (p:Product)
RETURN p.name, ABS(p.profit) AS absoluteProfit

MATCH (c:Circle)
RETURN SQRT(c.area / 3.14159) AS radius
```

### Trigonometric Functions

All trigonometric functions work with radians.

| Function | Description |
|----------|-------------|
| `SIN(n)` | Sine |
| `COS(n)` | Cosine |
| `TAN(n)` | Tangent |
| `ASIN(n)` | Inverse sine (input: -1 to 1) |
| `ACOS(n)` | Inverse cosine (input: -1 to 1) |
| `ATAN(n)` | Inverse tangent |
| `ATAN2(y, x)` | Two-argument arctangent |

### Angle Conversion Functions

| Function | Description | Example |
|----------|-------------|---------|
| `DEGREES(radians)` | Radians to degrees | `DEGREES(3.14159)` → `180.0` |
| `RADIANS(degrees)` | Degrees to radians | `RADIANS(180)` → `3.14159` |

### Mathematical Constants

| Function | Description | Value |
|----------|-------------|-------|
| `PI()` | Pi constant | `3.141592653589793` |
| `E()` | Euler's number | `2.718281828459045` |

### Type Conversion Functions

| Function | Description | Example |
|----------|-------------|---------|
| `TOSTRING(v)` | Convert to string | `TOSTRING(42)` → `'42'` |
| `TOINTEGER(v)` / `TOINT(v)` | Convert to integer | `TOINTEGER('42')` → `42` |
| `TOFLOAT(v)` | Convert to float | `TOFLOAT('3.14')` → `3.14` |
| `TOBOOLEAN(v)` / `TOBOOL(v)` | Convert to boolean | `TOBOOLEAN('true')` → `true` |

### Introspection Functions

| Function | Description | Example |
|----------|-------------|---------|
| `ID(n)` | Get element ID | `ID(n)` → vertex/edge ID |
| `LABELS(n)` | Get vertex labels | `LABELS(n)` → `['Person']` |
| `TYPE(r)` | Get edge type | `TYPE(r)` → `'KNOWS'` |
| `PROPERTIES(n)` | Get all properties as map | `PROPERTIES(n)` → `{name: 'Alice', age: 30}` |

**Examples:**

```sql
MATCH (n:Person)
RETURN ID(n) AS id, LABELS(n) AS labels

MATCH (a)-[r]->(b)
RETURN TYPE(r) AS relationType
```

### Special Functions

| Function | Description | Example |
|----------|-------------|---------|
| `COALESCE(v1, v2, ...)` | First non-null value | `COALESCE(n.nickname, n.name)` |
| `PATH()` | Get traversal path (requires WITH PATH) | See below |
| `MATH(expr, args...)` | Evaluate mathexpr expression | See below |

### COALESCE Function

Returns the first non-null argument:

```sql
MATCH (p:Person)
RETURN COALESCE(p.nickname, p.name) AS displayName

-- With multiple fallbacks
MATCH (p:Person)
RETURN COALESCE(p.email, p.phone, 'No contact') AS contact
```

### PATH Function

Retrieves the full traversal path. Requires `WITH PATH` clause:

```sql
MATCH (p1:Player)-[:played_for]->(t:Team)<-[:played_for]-(p2:Player)
WITH PATH
RETURN path(), p2.name

-- Path returns list: [vertex, edge, vertex, edge, vertex, ...]
```

### MATH Function (mathexpr Integration)

Evaluates complex mathematical expressions using the mathexpr library:

```sql
-- Basic math expression with literal arguments
MATCH (n:Number)
RETURN MATH('sqrt(a^2 + b^2)', 3, 4) AS hypotenuse
-- Returns: 5.0

-- Using property values as arguments
MATCH (n:Point)
RETURN MATH('sqrt(a^2 + b^2)', n.x, n.y) AS distance

-- Complex expressions
MATCH (n:Data)
RETURN MATH('sin(x) * cos(y) + exp(-z)', n.x, n.y, n.z) AS result
```

The MATH function supports:
- Variables: `a`, `b`, `c`, `d`, `e`, `f` (positional arguments)
- Constants: `pi`, `e`, `tau`
- Operators: `+`, `-`, `*`, `/`, `%`, `^`
- Functions: `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `sinh`, `cosh`, `tanh`, `sqrt`, `cbrt`, `abs`, `floor`, `ceil`, `round`, `exp`, `ln`, `log`, `log2`, `log10`, `min`, `max`, `clamp`

### REDUCE Function

The `REDUCE` function folds/accumulates over a list, similar to reduce/fold operations in functional programming.

**Syntax:**

```
REDUCE(accumulator = initialValue, variable IN list | expression)
```

**Parameters:**

| Parameter | Description |
|-----------|-------------|
| `accumulator` | Variable name for the accumulated value |
| `initialValue` | Starting value for the accumulator |
| `variable` | Variable bound to each list element |
| `list` | The list to iterate over |
| `expression` | Expression that computes the new accumulator value |

**Examples:**

```sql
-- Sum a list of numbers
RETURN REDUCE(total = 0, x IN [1, 2, 3, 4, 5] | total + x) AS sum
-- Returns: 15

-- Product of list elements
RETURN REDUCE(product = 1, n IN [2, 3, 4] | product * n) AS result
-- Returns: 24

-- Concatenate strings
RETURN REDUCE(str = '', s IN ['a', 'b', 'c'] | str || s) AS combined
-- Returns: 'abc'

-- With separator
RETURN REDUCE(str = '', s IN ['hello', 'world'] | 
  CASE WHEN str = '' THEN s ELSE str || ', ' || s END
) AS joined
-- Returns: 'hello, world'
```

**Using with Query Results:**

```sql
-- Sum prices from collected items
MATCH (p:Person)-[:PURCHASED]->(item:Product)
LET items = COLLECT(item.price)
RETURN p.name, REDUCE(total = 0, price IN items | total + price) AS totalSpent

-- Calculate path length
MATCH (a:Person)-[r:KNOWS*1..5]->(b:Person)
RETURN REDUCE(len = 0, rel IN r | len + 1) AS pathLength
```

**Complex Accumulation:**

```sql
-- Build a running maximum
RETURN REDUCE(maxVal = 0, x IN [3, 1, 4, 1, 5, 9] | 
  CASE WHEN x > maxVal THEN x ELSE maxVal END
) AS maxValue
-- Returns: 9

-- Count matching elements
RETURN REDUCE(count = 0, x IN [1, 2, 3, 4, 5] | 
  CASE WHEN x > 2 THEN count + 1 ELSE count END
) AS countGreaterThan2
-- Returns: 3
```

### List Predicate Functions

List predicates test conditions across list elements. They return boolean values.

| Function | Description | Returns `true` when |
|----------|-------------|---------------------|
| `ALL(x IN list WHERE cond)` | All elements match | Every element satisfies condition |
| `ANY(x IN list WHERE cond)` | At least one matches | At least one element satisfies |
| `NONE(x IN list WHERE cond)` | No elements match | No element satisfies condition |
| `SINGLE(x IN list WHERE cond)` | Exactly one matches | Exactly one element satisfies |

**ALL - Every Element Must Match:**

```sql
-- Check if all numbers are positive
RETURN ALL(x IN [1, 2, 3] WHERE x > 0) AS allPositive
-- Returns: true

RETURN ALL(x IN [1, -2, 3] WHERE x > 0) AS allPositive
-- Returns: false

-- Check if all friends are adults
MATCH (p:Person)-[:KNOWS]->(f:Person)
LET friendAges = COLLECT(f.age)
WHERE ALL(age IN friendAges WHERE age >= 18)
RETURN p.name
```

**ANY - At Least One Must Match:**

```sql
-- Check if any number is negative
RETURN ANY(x IN [1, -2, 3] WHERE x < 0) AS hasNegative
-- Returns: true

-- Check if player has any championship
MATCH (p:Player)
LET rings = COLLECT { MATCH (p)-[:won_championship_with]->() RETURN 1 }
WHERE ANY(x IN rings WHERE x = 1)
RETURN p.name AS champions
```

**NONE - No Element Must Match:**

```sql
-- Check if no numbers are negative
RETURN NONE(x IN [1, 2, 3] WHERE x < 0) AS noNegatives
-- Returns: true

-- Find players with no losses
MATCH (p:Player)
LET results = [10, 5, 8, 12]  -- example scores
WHERE NONE(score IN results WHERE score < 5)
RETURN p.name
```

**SINGLE - Exactly One Must Match:**

```sql
-- Check if exactly one element equals 5
RETURN SINGLE(x IN [1, 5, 3] WHERE x = 5) AS exactlyOne
-- Returns: true

RETURN SINGLE(x IN [5, 5, 3] WHERE x = 5) AS exactlyOne
-- Returns: false (two matches)

-- Find teams with exactly one star player
MATCH (t:Team)<-[:plays_for]-(p:Player)
LET scores = COLLECT(p.points)
WHERE SINGLE(pts IN scores WHERE pts > 25)
RETURN t.name AS teamWithOneStar
```

**Edge Cases:**

```sql
-- Empty list behavior
RETURN ALL(x IN [] WHERE x > 0)    -- true (vacuously true)
RETURN ANY(x IN [] WHERE x > 0)    -- false (no elements match)
RETURN NONE(x IN [] WHERE x > 0)   -- true (no elements fail)
RETURN SINGLE(x IN [] WHERE x > 0) -- false (no elements match)
```

---

## Aggregation

Aggregate functions compute values across multiple matched patterns.

### Aggregate Functions

| Function | Description | Example |
|----------|-------------|---------|
| `COUNT(*)` | Count all results | `COUNT(*)` |
| `COUNT(expr)` | Count non-null values | `COUNT(n.email)` |
| `COUNT(DISTINCT expr)` | Count unique values | `COUNT(DISTINCT n.city)` |
| `SUM(expr)` | Sum numeric values | `SUM(n.salary)` |
| `AVG(expr)` | Average of numeric values | `AVG(n.age)` |
| `MIN(expr)` | Minimum value | `MIN(n.price)` |
| `MAX(expr)` | Maximum value | `MAX(n.score)` |
| `COLLECT(expr)` | Collect values into list | `COLLECT(n.name)` |

### Basic Aggregation Examples

```sql
-- Count all vertices
MATCH (n:Person) RETURN COUNT(*)

-- Count non-null property values
MATCH (n:Person) RETURN COUNT(n.email)

-- Count distinct values
MATCH (n:Person) RETURN COUNT(DISTINCT n.city)

-- Sum, average, min, max
MATCH (e:Employee)
RETURN SUM(e.salary), AVG(e.salary), MIN(e.salary), MAX(e.salary)

-- Collect into list
MATCH (p:Person)-[:LIVES_IN]->(c:City {name: 'NYC'})
RETURN COLLECT(p.name) AS nycResidents
```

### GROUP BY Aggregation

When using aggregate functions with non-aggregated expressions, use GROUP BY:

```sql
-- Count players by position
MATCH (p:Player)
RETURN p.position, COUNT(*) AS count
GROUP BY p.position

-- Average salary by department
MATCH (e:Employee)-[:WORKS_IN]->(d:Department)
RETURN d.name AS department, AVG(e.salary) AS avgSalary
GROUP BY d.name

-- Multiple group keys
MATCH (p:Player)-[:plays_for]->(t:Team)
RETURN t.name, p.position, COUNT(*) AS count
GROUP BY t.name, p.position
ORDER BY t.name, count DESC
```

### Aggregation with Filtering

```sql
-- Filter before aggregation (WHERE)
MATCH (p:Player)
WHERE p.active = true
RETURN p.position, AVG(p.salary) AS avgSalary
GROUP BY p.position

-- Complex aggregation query
MATCH (p:Player)-[:played_for]->(t:Team)
WHERE p.draft_year >= 2010
RETURN t.name,
       COUNT(*) AS totalPlayers,
       AVG(p.career_points) AS avgPoints,
       MAX(p.career_points) AS topScorer
GROUP BY t.name
ORDER BY avgPoints DESC
LIMIT 10
```

### COLLECT Function

Collects values into a list:

```sql
-- Collect all names
MATCH (p:Person)
RETURN COLLECT(p.name) AS allNames

-- Collect with grouping
MATCH (p:Player)-[:plays_for]->(t:Team)
RETURN t.name, COLLECT(p.name) AS players
GROUP BY t.name

-- Collect distinct values
MATCH (p:Player)-[:played_for]->(t:Team)
RETURN p.name, COLLECT(DISTINCT t.name) AS teams
GROUP BY p.name
```

---

## Advanced Features

This section covers advanced GQL features for complex analytical queries.

### Query Parameters

Parameterized queries allow safe value injection and query reuse using `$paramName` syntax.

**Syntax:**

```sql
-- Parameter in property filter
MATCH (n:Person {id: $personId}) RETURN n

-- Parameter in WHERE clause
MATCH (n:Person) WHERE n.age > $minAge RETURN n

-- Parameter in expression
MATCH (n) RETURN n.value * $multiplier AS scaled

-- Multiple parameters
MATCH (a:Person {id: $fromId})-[:KNOWS]->(b:Person {id: $toId})
RETURN a, b
```

**Rust Usage:**

```rust
use interstellar::gql::{execute_with_params, Parameters};
use interstellar::Value;

let mut params = Parameters::new();
params.insert("personId".to_string(), Value::Int(123));
params.insert("minAge".to_string(), Value::Int(18));

let results = execute_with_params(
    &graph,
    "MATCH (p:Person {id: $personId})-[:FRIEND]->(f) 
     WHERE f.age >= $minAge 
     RETURN f.name",
    &params,
)?;
```

**Supported parameter types:** String, Int, Float, Bool, List, Map, Null

### Inline WHERE in Patterns

Filter nodes and edges directly within pattern syntax during pattern matching.

**Syntax:**

```sql
-- Node with inline WHERE
MATCH (n:Person WHERE n.age > 21) RETURN n

-- Edge with inline WHERE
MATCH (a)-[r:KNOWS WHERE r.since > 2020]->(b) RETURN a, b

-- Combined filters
MATCH (a:Person WHERE a.status = 'active')-[r:FOLLOWS WHERE r.weight > 0.5]->(b)
RETURN a, b
```

**Semantics:**

- Inline WHERE is evaluated during pattern matching, not after
- Can only reference properties of the current element (not other pattern variables)
- Combines with label filters (both must match)

**Equivalent queries:**

```sql
-- These are semantically equivalent:
MATCH (n:Person WHERE n.age > 21) RETURN n
MATCH (n:Person) WHERE n.age > 21 RETURN n

-- But inline WHERE is useful for edge filtering in complex patterns
MATCH (a)-[r:KNOWS WHERE r.weight > 0.5]->(b)-[s:WORKS_AT]->(c)
RETURN a, b, c
```

### LET Clause

The LET clause binds the result of an expression to a variable for use in subsequent clauses.

**Syntax:**

```sql
-- Basic LET
MATCH (p:Person)-[:FRIEND]->(f)
LET friendCount = COUNT(f)
RETURN p.name, friendCount

-- LET with COLLECT
MATCH (p:Person)-[:PURCHASED]->(item)
LET purchases = COLLECT(item)
LET totalSpent = SUM(item.price)
RETURN p.name, purchases, totalSpent

-- LET with CASE expression
MATCH (p:Person)
LET ageCategory = CASE 
    WHEN p.age < 18 THEN 'minor'
    WHEN p.age < 65 THEN 'adult'
    ELSE 'senior'
END
RETURN p.name, ageCategory

-- Multiple LET clauses (later LETs can reference earlier ones)
MATCH (person)-[:WORKS_AT]->(company)
LET colleagues = COLLECT(person)
LET companySize = SIZE(colleagues)
LET avgSalary = AVG(person.salary)
RETURN company.name, companySize, avgSalary
```

**Clause ordering:**

```
MATCH -> OPTIONAL MATCH -> WHERE -> LET -> RETURN -> GROUP BY -> ORDER BY -> LIMIT
```

### List Comprehensions

Transform and filter lists using a concise syntax similar to Python list comprehensions.

**Syntax:**

```sql
-- Basic transformation: [variable IN list | expression]
[x IN list | x.name]

-- With filter: [variable IN list WHERE condition | expression]
[x IN list WHERE x.active | x.name]
```

**Examples:**

```sql
-- Get names from list of people
LET names = [p IN people | p.name]
-- Input: [{name: 'Alice'}, {name: 'Bob'}]
-- Output: ['Alice', 'Bob']

-- Filter and transform
LET adultNames = [p IN people WHERE p.age >= 18 | p.name]
-- Input: [{name: 'Alice', age: 25}, {name: 'Bob', age: 15}]
-- Output: ['Alice']

-- Build formatted strings
LET labels = [t IN types | t.category || '/' || t.name]
-- Input: [{category: 'A', name: 'foo'}, {category: 'B', name: 'bar'}]
-- Output: ['A/foo', 'B/bar']

-- Complex expressions
[p IN people | CASE WHEN p.age > 18 THEN 'adult' ELSE 'minor' END]
```

**Semantics:**

- The variable is scoped to the comprehension only
- If input is NULL or not a list, returns NULL
- Empty list input returns empty list

### String Concatenation Operator

The `||` operator concatenates strings, following SQL/GQL standard.

**Syntax:**

```sql
-- Basic concatenation
'Hello' || ' ' || 'World'
-- Result: 'Hello World'

-- With properties
p.firstName || ' ' || p.lastName

-- In expressions
RETURN n.type || '/' || n.subtype AS fullType

-- With COALESCE for null handling
COALESCE(p.nickname, p.firstName) || ' ' || p.lastName
```

**Semantics:**

- If either operand is NULL, result is NULL
- Non-string operands are automatically converted to strings:
  - Int/Float: Decimal representation
  - Bool: `"true"` / `"false"`
  - List: `"[elem1, elem2, ...]"`
  - Map: `"{key1: val1, key2: val2}"`

### Map Literals

Create map/object values in expressions, particularly useful with COLLECT and RETURN.

**Syntax:**

```sql
-- Map literal
{name: 'Alice', age: 30}

-- Map with property references
{personName: p.name, personAge: p.age}

-- In COLLECT
LET data = COLLECT({parent: parent, type: event.type})

-- In RETURN
RETURN {
    name: p.name,
    stats: {
        friends: friendCount,
        posts: postCount
    }
} AS profile

-- Nested maps supported
{outer: {inner: value}}
```

**Keys:** Must be identifiers (unquoted) or string literals

### CALL Procedures (Graph Algorithms)

Interstellar exposes graph algorithms as CALL procedures. These work with both the graph-bound and snapshot-only entry points.

See the [Algorithms Guide](../guides/algorithms.md) for detailed usage, algorithm selection, and the Rust API.

| Procedure | Arguments | YIELD columns | Description |
|-----------|-----------|---------------|-------------|
| `interstellar.shortestPath(src, tgt)` | 2 vertices | `path`, `distance` | Unweighted BFS shortest path |
| `interstellar.dijkstra(src, tgt, prop)` | 2 vertices + weight property | `path`, `distance` | Dijkstra weighted shortest path |
| `interstellar.bfs(src)` | 1 vertex | `node`, `depth` | BFS traversal (all reachable vertices) |
| `interstellar.dfs(src [, maxDepth])` | 1 vertex + optional depth | `node`, `depth` | DFS traversal with optional depth limit |
| `interstellar.astar(src, tgt, w, h)` | 2 vertices + weight + heuristic properties | `path`, `distance` | A\* pathfinding |
| `interstellar.bidirectionalBfs(src, tgt)` | 2 vertices | `path`, `distance` | Bidirectional BFS shortest path |
| `interstellar.iddfs(src, tgt, maxDepth)` | 2 vertices + max depth | `path`, `distance` | Iterative deepening DFS |

#### Examples

```sql
-- Unweighted shortest path
MATCH (a), (b) WHERE id(a) = 1 AND id(b) = 4
CALL interstellar.shortestPath(a, b)
YIELD path AS p, distance AS d
RETURN p, d
```

```sql
-- Dijkstra weighted shortest path
MATCH (a), (b) WHERE id(a) = 1 AND id(b) = 4
CALL interstellar.dijkstra(a, b, 'weight')
YIELD path AS p, distance AS d
RETURN p, d
```

```sql
-- BFS traversal
MATCH (a) WHERE id(a) = 1
CALL interstellar.bfs(a)
YIELD node AS v, depth AS d
RETURN v, d
```

```sql
-- DFS traversal with depth limit
MATCH (a) WHERE id(a) = 1
CALL interstellar.dfs(a, 3)
YIELD node AS v, depth AS d
RETURN v, d
```

```sql
-- A* with heuristic property
MATCH (a), (b) WHERE id(a) = 1 AND id(b) = 4
CALL interstellar.astar(a, b, 'weight', 'estimatedDist')
YIELD path AS p, distance AS d
RETURN p, d
```

```sql
-- Bidirectional BFS
MATCH (a), (b) WHERE id(a) = 1 AND id(b) = 4
CALL interstellar.bidirectionalBfs(a, b)
YIELD path AS p, distance AS d
RETURN p, d
```

```sql
-- IDDFS with max depth
MATCH (a), (b) WHERE id(a) = 1 AND id(b) = 4
CALL interstellar.iddfs(a, b, 10)
YIELD path AS p, distance AS d
RETURN p, d
```

All pathfinding procedures return empty results (no rows) when no path exists between source and target.

### CALL Procedures (Full-Text Search)

Gated on the `full-text` feature and only dispatched through the graph-bound entry point ([`Graph::gql`](https://docs.rs/interstellar/latest/interstellar/storage/struct.Graph.html#method.gql) / [`Graph::gql_with_params`](https://docs.rs/interstellar/latest/interstellar/storage/struct.Graph.html#method.gql_with_params)). The snapshot-only [`gql::compile`](https://docs.rs/interstellar/latest/interstellar/gql/fn.compile.html) path returns `ProcedureArgumentError` with an actionable message — it has no `Graph` handle to dispatch against.

Interstellar exposes its Tantivy-backed FTS engine as eight procedures, one per `(query-kind × element-kind)` combination. Compound queries (`And` / `Or` / `Not`) are intentionally **not** exposed through GQL — use Gremlin's [`TextQ.*` DSL](gremlin.md#textq-full-text-query-dsl) or the Rust API for those.

| Procedure | Backing `TextQuery` | Scope |
|-----------|---------------------|-------|
| `interstellar.searchTextV(prop, query, k)` | `Match(query)` | vertices |
| `interstellar.searchTextAllV(prop, query, k)` | `MatchAll(query)` | vertices |
| `interstellar.searchTextPhraseV(prop, query, k)` | `Phrase { text: query, slop: 0 }` | vertices |
| `interstellar.searchTextPrefixV(prop, query, k)` | `Prefix(query)` | vertices |
| `interstellar.searchTextE(prop, query, k)` | edge-side `Match(query)` | edges |
| `interstellar.searchTextAllE(prop, query, k)` | edge-side `MatchAll(query)` | edges |
| `interstellar.searchTextPhraseE(prop, query, k)` | edge-side `Phrase { .. }` | edges |
| `interstellar.searchTextPrefixE(prop, query, k)` | edge-side `Prefix(query)` | edges |

Arguments are typed `(property STRING, query STRING, k INT)`. Hits are returned in descending BM25 score order, capped at `k`.

#### YIELD aliases

| Alias | Type / shape |
|-------|--------------|
| `elem` | `Value::Map` — fully materialized property record |
| `elemId` | `Value::Vertex(VertexId)` / `Value::Edge(EdgeId)` — bare reference |
| `score` | `Value::Float` — BM25 score (descending) |

`elem` materialization is **lazy**: if your `YIELD` clause does not name `elem`, the dispatcher skips the per-row property lookup — id-only queries pay zero materialization cost.

#### Anchoring with MATCH

GQL requires every query to begin with a `MATCH` clause, and `CALL` fires once per outer row. To call a procedure exactly once, anchor against a single known row:

```sql
-- Anchor on one vertex by id.
MATCH (anchor) WHERE id(anchor) = 0
CALL interstellar.searchTextV('body', 'raft', 5)
YIELD elemId, score
RETURN elemId, score
```

```sql
-- Materialize the full element record.
MATCH (anchor) WHERE id(anchor) = 0
CALL interstellar.searchTextPhraseV('body', 'quick brown fox', 5)
YIELD elem
RETURN elem
```

```sql
-- Edge-side prefix search.
MATCH (anchor) WHERE id(anchor) = 0
CALL interstellar.searchTextPrefixE('note', 'consen', 10)
YIELD elemId, score
RETURN elemId, score
```

Without the anchor, a bare `MATCH ()` unfolds per vertex and re-runs the procedure once per row — usually not what you want.

### Complete Advanced Query Example

Combining multiple advanced features:

```sql
MATCH (person:Person WHERE person.id = $personId)
      -[r1:PARTICIPATED_IN WHERE r1.role = 'child']->(birthEvent:Birth)
      <-[r2:PARTICIPATED_IN WHERE r2.role = 'parent']-(parent:Person),
      (parent)-[:PARTICIPATED_IN]->(otherBirth:Birth)
      <-[r3:PARTICIPATED_IN WHERE r3.role = 'child']-(sibling:Person)
WHERE sibling <> person
LET siblingInfo = COLLECT({
    sibling: sibling,
    parent: parent,
    sharedEvent: birthEvent
})
RETURN sibling.name,
       SIZE(siblingInfo) AS connectionCount,
       [s IN siblingInfo | s.parent.name] AS sharedParents
GROUP BY sibling
```

---

## Mutation Operations

Mutations modify the graph and require mutable storage access.

### Mutation Statement Structure

```
[MATCH pattern [WHERE expression]]
<mutation_clause>+
[RETURN expression [AS alias] [, ...]]
```

Or for MERGE:

```
MERGE pattern
[ON CREATE SET assignments]
[ON MATCH SET assignments]
[RETURN ...]
```

### CREATE Clause

Creates new vertices and edges.

```sql
-- Create a single vertex
CREATE (n:Person {name: 'Alice', age: 30})

-- Create multiple vertices
CREATE (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'})

-- Create with RETURN to get the created element
CREATE (n:Person {name: 'Alice'}) RETURN n

-- Create a vertex with edge (requires existing endpoint or creates inline)
CREATE (a:Person {name: 'Alice'})-[:KNOWS]->(b:Person {name: 'Bob'})
```

**Rust Usage:**

```rust
use interstellar::gql::{parse_statement, execute_mutation};
use interstellar::prelude::*;

let graph = Graph::new();
let mut storage = graph.as_storage_mut();

let stmt = parse_statement("CREATE (n:Person {name: 'Alice', age: 30})").unwrap();
execute_mutation(&stmt, &mut storage).unwrap();

drop(storage);
assert_eq!(graph.snapshot().vertex_count(), 1);
```

### SET Clause

Updates properties on matched elements.

```sql
-- Update single property
MATCH (n:Person {name: 'Alice'})
SET n.age = 31

-- Update multiple properties
MATCH (n:Person {name: 'Alice'})
SET n.age = 31, n.status = 'active'

-- Update with expression
MATCH (n:Person {name: 'Alice'})
SET n.age = n.age + 1

-- Update and return
MATCH (n:Person {name: 'Alice'})
SET n.lastUpdated = 1234567890
RETURN n
```

### REMOVE Clause

Removes properties from elements (sets them to null/removes the key).

```sql
-- Remove single property
MATCH (n:Person {name: 'Alice'})
REMOVE n.temporaryField

-- Remove multiple properties
MATCH (n:Person)
REMOVE n.tempA, n.tempB
```

### DELETE Clause

Deletes matched elements. Fails if deleting a vertex that has connected edges.

```sql
-- Delete matched vertices (must have no edges)
MATCH (n:Person {status: 'inactive'})
DELETE n

-- Delete edges
MATCH (a:Person)-[r:KNOWS]->(b:Person)
WHERE r.since < 2020
DELETE r

-- Delete multiple elements
MATCH (a:Person {name: 'Alice'})-[r:KNOWS]->(b:Person)
DELETE r, b
```

### DETACH DELETE Clause

Deletes vertices along with all their connected edges automatically.

```sql
-- Delete vertex and its edges
MATCH (n:Person {name: 'Alice'})
DETACH DELETE n

-- Delete multiple vertices with edges
MATCH (n:Person)
WHERE n.status = 'deleted'
DETACH DELETE n
```

### MERGE Clause

MERGE is an "upsert" operation: matches existing patterns or creates them if not found.

```sql
-- Simple merge (create if not exists)
MERGE (n:Person {name: 'Alice'})

-- Merge with ON CREATE (set properties only when creating)
MERGE (n:Person {name: 'Alice'})
ON CREATE SET n.created = 1234567890

-- Merge with ON MATCH (set properties only when matching existing)
MERGE (n:Person {name: 'Alice'})
ON MATCH SET n.lastSeen = 1234567890

-- Merge with both actions
MERGE (n:Person {name: 'Alice'})
ON CREATE SET n.created = 1234567890, n.visits = 1
ON MATCH SET n.lastSeen = 1234567890, n.visits = n.visits + 1
RETURN n
```

### Complete Mutation Examples

```rust
use interstellar::gql::{parse_statement, execute_mutation};
use interstellar::prelude::*;

let graph = Graph::new();
let mut storage = graph.as_storage_mut();

// Create initial data
let stmt = parse_statement(r#"
    CREATE (alice:Person {name: 'Alice', age: 30}),
           (bob:Person {name: 'Bob', age: 25}),
           (alice)-[:KNOWS {since: 2020}]->(bob)
"#).unwrap();
execute_mutation(&stmt, &mut storage).unwrap();

// Update a property
let stmt = parse_statement(r#"
    MATCH (n:Person {name: 'Alice'})
    SET n.age = 31
"#).unwrap();
execute_mutation(&stmt, &mut storage).unwrap();

// Delete a relationship
let stmt = parse_statement(r#"
    MATCH (a:Person {name: 'Alice'})-[r:KNOWS]->(b:Person)
    DELETE r
"#).unwrap();
execute_mutation(&stmt, &mut storage).unwrap();

// Merge (upsert) a person
let stmt = parse_statement(r#"
    MERGE (n:Person {name: 'Charlie'})
    ON CREATE SET n.created = 1234567890
    ON MATCH SET n.lastSeen = 1234567890
"#).unwrap();
execute_mutation(&stmt, &mut storage).unwrap();
```

---

## Error Handling

The GQL module defines three error types for different stages of query processing.

### ParseError

Errors during query parsing (syntax errors).

| Variant | Description |
|---------|-------------|
| `SyntaxAt { span, message }` | Syntax error at specific position |
| `Syntax(String)` | General syntax error |
| `Empty` | Empty query string |
| `MissingClause { clause, span }` | Required clause missing |
| `InvalidLiteral { value, span, reason }` | Invalid literal value |
| `UnexpectedToken { span, found, expected }` | Unexpected token encountered |
| `UnexpectedEof { span, expected }` | Unexpected end of input |
| `InvalidRange { range, span, reason }` | Invalid path quantifier range |

**Example:**

```rust
use interstellar::gql::{parse, ParseError};

match parse("MATCH (n:Person) RETURN") {
    Ok(_) => println!("Parsed successfully"),
    Err(ParseError::SyntaxAt { span, message }) => {
        eprintln!("Syntax error at position {}: {}", span.start, message);
    }
    Err(e) => eprintln!("Parse error: {}", e),
}
```

### CompileError

Errors during compilation (semantic errors).

| Variant | Description |
|---------|-------------|
| `UndefinedVariable { name }` | Reference to undefined variable |
| `DuplicateVariable { name }` | Variable bound multiple times |
| `EmptyPattern` | MATCH clause has no patterns |
| `PatternMustStartWithNode` | Pattern starts with edge instead of node |
| `UnsupportedExpression { expr }` | Expression not supported in context |
| `AggregateInWhere { func }` | Aggregate function used in WHERE |
| `InvalidPropertyAccess { variable }` | Property access on non-element |
| `UnsupportedAggregation { func }` | Unknown aggregate function |
| `TypeMismatch { message }` | Type error in expression |
| `ExpressionNotInGroupBy { expr }` | Non-aggregated expression missing from GROUP BY |
| `UnsupportedFeature(String)` | Feature not implemented |

**Example:**

```rust
use interstellar::gql::{parse, compile, CompileError};
use interstellar::Graph;

let graph = Graph::in_memory();
let snapshot = graph.snapshot();

let query = parse("MATCH (n:Person) RETURN x").unwrap();
match compile(&query, &snapshot) {
    Ok(_) => println!("Success"),
    Err(CompileError::UndefinedVariable { name }) => {
        eprintln!("Variable '{}' is not defined in MATCH", name);
    }
    Err(e) => eprintln!("Compile error: {}", e),
}
```

### MutationError

Errors during mutation execution.

| Variant | Description |
|---------|-------------|
| `Compile(CompileError)` | Underlying compilation error |
| `Storage(StorageError)` | Storage operation failed |
| `UnboundVariable(String)` | Variable not bound during execution |
| `VertexHasEdges(VertexId)` | DELETE on vertex with edges (use DETACH DELETE) |
| `InvalidElementType { operation, expected, actual }` | Wrong element type for operation |
| `MissingLabel` | CREATE vertex without label |
| `IncompleteEdge` | Edge missing source or target |

**Example:**

```rust
use interstellar::gql::{parse_statement, execute_mutation, MutationError};
use interstellar::prelude::*;

let graph = Graph::new();
let mut storage = graph.as_storage_mut();

// Create vertex with an edge
parse_statement("CREATE (a:Person)-[:KNOWS]->(b:Person)").map(|s| execute_mutation(&s, &mut storage));

// Try to DELETE (not DETACH DELETE) - will fail
let stmt = parse_statement("MATCH (n:Person) DELETE n").unwrap();
match execute_mutation(&stmt, &mut storage) {
    Ok(_) => println!("Deleted"),
    Err(MutationError::VertexHasEdges(vid)) => {
        eprintln!("Cannot delete vertex {:?}: has edges. Use DETACH DELETE.", vid);
    }
    Err(e) => eprintln!("Mutation error: {}", e),
}
```

### GqlError (Top-level)

Wraps both parse and compile errors for convenience:

```rust
use interstellar::gql::GqlError;

let graph = interstellar::Graph::in_memory();
let snapshot = graph.snapshot();

match snapshot.gql("MATCH (n:Person) RETURN x") {
    Ok(results) => println!("Found {} results", results.len()),
    Err(GqlError::Parse(e)) => eprintln!("Syntax error: {}", e),
    Err(GqlError::Compile(e)) => eprintln!("Compilation error: {}", e),
}
```

---

## Limitations

The current GQL implementation has the following limitations:

### Not Supported

| Feature | Status | Notes |
|---------|--------|-------|
| Subqueries | Not supported | No nested `CALL` or `MATCH` within expressions |
| `FOREACH` | Not supported | No iterative mutations |
| `LOAD CSV` | Not supported | No external data import |
| Multiple graphs | Not supported | Single graph queries only |
| Returning paths directly | Partial | Use `WITH PATH` + `path()` function |
| `CALL` procedures | Partial | Built-in algorithm and FTS procedures only — see [CALL Procedures (Graph Algorithms)](#call-procedures-graph-algorithms) and [CALL Procedures (Full-Text Search)](#call-procedures-full-text-search). No user-defined procedures. |
| Pattern comprehensions | Not supported | `[(p)-[:KNOWS]->(f) | f.name]` syntax |

### Partial Support

| Feature | Limitation |
|---------|------------|
| `UNWIND` | Supported but may have limitations in complex nested contexts |
| Anonymous endpoint patterns | `MATCH ()-[r]->()` may require explicit labels on endpoints |
| Multi-pattern MATCH | Only first pattern fully used; subsequent patterns joined via comma |
| Variable-length paths | Default max of 10 hops; custom max supported via `*n..m` syntax |

### Known Behaviors

1. **Keywords are case-insensitive**: `MATCH`, `match`, `Match` are all valid
2. **Identifiers are case-sensitive**: `n.Name` and `n.name` are different properties
3. **String literals use single quotes**: `'Alice'` not `"Alice"`
4. **NULL propagation**: Operations involving NULL typically return NULL
5. **Empty MATCH results**: If MATCH finds nothing, mutations don't execute

### Error on Mutation Without Match

```sql
-- This returns empty results (no error)
MATCH (n:NonExistent) SET n.prop = 1

-- To ensure data exists, check count or use MERGE
```

---

## API Reference

### Public Functions

```rust
// Parse a single query (returns Query)
pub fn parse(input: &str) -> Result<Query, ParseError>;

// Parse a statement (query, UNION, or mutation)
pub fn parse_statement(input: &str) -> Result<Statement, ParseError>;

// Compile and execute a query
pub fn compile<'g>(query: &Query, snapshot: &'g GraphSnapshot<'g>) -> Result<Vec<Value>, CompileError>;

// Compile and execute a statement
pub fn compile_statement<'g>(stmt: &Statement, snapshot: &'g GraphSnapshot<'g>) -> Result<Vec<Value>, CompileError>;

// Compile and execute a query with parameters
pub fn compile_with_params<'g>(
    query: &str,
    params: &Parameters,
    snapshot: &'g GraphSnapshot<'g>,
) -> Result<Vec<Value>, GqlError>;

// Execute a query with parameters (convenience function)
pub fn execute_with_params<G: Graph>(
    graph: &G,
    query: &str,
    params: &Parameters,
) -> Result<Vec<Value>, GqlError>;

// Execute a mutation
pub fn execute_mutation<S: GraphStorage + GraphStorageMut>(
    stmt: &Statement,
    storage: &mut S,
) -> Result<Vec<Value>, MutationError>;

// Execute a mutation query directly
pub fn execute_mutation_query<S: GraphStorage + GraphStorageMut>(
    query: &MutationQuery,
    storage: &mut S,
) -> Result<Vec<Value>, MutationError>;
```

### Types

```rust
/// Parameters passed to query execution
pub type Parameters = HashMap<String, Value>;
```

### Convenience Method

```rust
// On GraphSnapshot
impl GraphSnapshot {
    pub fn gql(&self, query: &str) -> Result<Vec<Value>, GqlError>;
}
```

### Re-exports

The `interstellar::gql` module re-exports:

- All AST types from `ast.rs`
- `compile`, `compile_statement` from `compiler.rs`
- `ParseError`, `CompileError`, `GqlError`, `Span` from `error.rs`
- `execute_mutation`, `execute_mutation_query`, `MutationContext`, `MutationError`, `Element` from `mutation.rs`
- `parse`, `parse_statement` from `parser.rs`