khive-query 0.4.0

GQL and SPARQL parsers with SQL compiler for knowledge graph queries.
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
//! Integration tests for the SQL compiler through the public API.
//!
//! Tests cover fixed-length, variable-length, synthetic edge, and WHERE clause
//! compilation paths. Formerly inline in `compilers/sql.rs`; moved here per
//! QUERY-AUD-002.

use khive_query::ast::{QueryValue, ReturnItem};
use khive_query::{
    compile, parse, parse_auto, CompileOptions, CompiledQuery, QueryError, QueryLanguage,
};

fn opts() -> CompileOptions {
    CompileOptions::default()
}

fn scoped(namespace: &str) -> CompileOptions {
    CompileOptions {
        scopes: vec![namespace.to_string()],
        max_limit: 500,
    }
}

// --- Fixed-length compilation ---

#[test]
fn edge_property_relation_allowed() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[e]->(b) WHERE e.relation = 'extends' RETURN a",
    )
    .unwrap();
    let result = compile(&q, &opts());
    assert!(
        result.is_ok(),
        "relation should be allowed: {:?}",
        result.err()
    );
}

#[test]
fn edge_property_weight_allowed() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[e]->(b) WHERE e.weight > 0.5 RETURN a",
    )
    .unwrap();
    let result = compile(&q, &opts());
    assert!(
        result.is_ok(),
        "weight should be allowed: {:?}",
        result.err()
    );
}

#[test]
fn compile_unknown_kind_passes_through() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a:gizmo)-[:extends]->(b) RETURN a",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    let has_gizmo = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Text(s) if s == "gizmo"));
    assert!(
        has_gizmo,
        "pack-agnostic: unknown kind must pass through into SQL params"
    );
}

#[test]
fn compile_kind_passes_through_unchanged() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a:paper)-[:introduced_by]->(b:concept) RETURN a LIMIT 1",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    let has_paper = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Text(s) if s == "paper"));
    assert!(
        has_paper,
        "kind 'paper' must pass through unchanged into SQL params"
    );
}

#[test]
fn compile_rejects_namespace_in_where() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a:concept)-[:extends]->(b) WHERE a.namespace = 'other' RETURN a",
    )
    .unwrap();
    let err = compile(&q, &opts()).unwrap_err();
    assert!(err.to_string().contains("namespace"), "msg: {err}");
}

#[test]
fn compile_rejects_unknown_relation_in_where() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[e:extends]->(b) WHERE e.relation = 'related_to' RETURN a",
    )
    .unwrap();
    let err = compile(&q, &opts()).unwrap_err();
    assert!(err.to_string().contains("related_to"), "msg: {err}");
}

#[test]
fn compile_kind_in_where_passes_through_unchanged() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends]->(b) WHERE a.kind = 'paper' RETURN a",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    let has_paper = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Text(s) if s == "paper"));
    assert!(
        has_paper,
        "kind 'paper' must pass through unchanged into SQL params"
    );
}

#[test]
fn return_property_projection_compiles() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a:concept)-[e:extends]->(b:concept) RETURN a.name, b.name LIMIT 5",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains(".name AS a_name"),
        "sql: {}",
        compiled.sql
    );
    assert!(
        compiled.sql.contains(".name AS b_name"),
        "sql: {}",
        compiled.sql
    );
    assert!(
        !compiled.sql.contains("a_kind"),
        "should not emit full node columns"
    );
}

#[test]
fn return_unknown_node_property_rejected() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a:concept)-[:extends]->(b) RETURN a.domain LIMIT 5",
    )
    .unwrap();
    let err = compile(&q, &opts()).unwrap_err();
    assert!(
        matches!(err, QueryError::Compile(ref msg) if msg.contains("unknown node property 'domain'")),
        "got {err:?}"
    );
}

#[test]
fn return_unknown_edge_property_rejected() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[e:extends]->(b) RETURN e.label LIMIT 5",
    )
    .unwrap();
    let err = compile(&q, &opts()).unwrap_err();
    assert!(
        matches!(err, QueryError::Compile(ref msg) if msg.contains("unknown edge property 'label'")),
        "got {err:?}"
    );
}

#[test]
fn return_valid_edge_property_compiles() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[e:extends]->(b) RETURN e.relation, e.weight LIMIT 5",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains(".relation AS e_relation"),
        "sql: {}",
        compiled.sql
    );
    assert!(
        compiled.sql.contains(".weight AS e_weight"),
        "sql: {}",
        compiled.sql
    );
}

#[test]
fn entity_type_compiles_as_direct_column_not_json_extract() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:document {entity_type: 'paper'})-[:extends]->(m) RETURN n",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains(".entity_type = ?"),
        "entity_type must compile to a direct column comparison; sql: {}",
        compiled.sql
    );
    assert!(
        !compiled.sql.contains("json_extract"),
        "entity_type must NOT use json_extract; sql: {}",
        compiled.sql
    );
    let has_paper_param = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Text(s) if s == "paper"));
    assert!(
        has_paper_param,
        "entity_type value 'paper' must appear as a bound parameter"
    );
}

// --- Variable-length compilation ---

#[test]
fn variable_length_uses_cte() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a {name: 'LoRA'})-[:extends*1..3]->(b) RETURN b LIMIT 20",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled.sql.contains("WITH RECURSIVE"));
    assert!(compiled.sql.contains("traverse"));
}

#[test]
fn depth_cap_at_ten_rejects_above_max() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends*1..50]->(b) RETURN b",
    )
    .unwrap();
    let err = compile(&q, &opts()).unwrap_err();
    assert!(
        matches!(err, QueryError::InvalidInput(_)),
        "expected InvalidInput for depth > 10, got {err:?}"
    );
}

#[test]
fn depth_within_cap_compiles() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends*1..10]->(b) RETURN b",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled.sql.contains("WITH RECURSIVE"));
    let depth_val = compiled.params.iter().find_map(|p| {
        if let QueryValue::Integer(n) = p {
            Some(*n)
        } else {
            None
        }
    });
    assert_eq!(depth_val, Some(10), "depth param should be 10");
}

#[test]
fn variable_length_return_start_only_joins_end_entity() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a:concept)-[:extends*1..3]->(b) RETURN a LIMIT 10",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains("JOIN primary_nodes r"),
        "primary_nodes r must always be joined; sql: {}",
        compiled.sql
    );
}

#[test]
fn variable_length_trailing_pattern_unsupported() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends*1..3]->(b)-[:implements]->(c) RETURN b",
    )
    .unwrap();
    let err = compile(&q, &opts()).unwrap_err();
    assert!(
        matches!(err, QueryError::Unsupported(_)),
        "expected Unsupported, got {err:?}"
    );
}

#[test]
fn variable_length_mixed_chain_unsupported() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends]->(b)-[:implements*1..2]->(c) RETURN c",
    )
    .unwrap();
    let err = compile(&q, &opts()).unwrap_err();
    assert!(matches!(err, QueryError::Unsupported(_)), "got {err:?}");
}

// --- SPARQL ---

#[test]
fn sparql_star_rejected_as_unsupported() {
    let err = parse(
        QueryLanguage::Sparql,
        "SELECT ?a ?b WHERE { ?a :extends* ?b . }",
    )
    .unwrap_err();
    assert!(matches!(err, QueryError::Unsupported(_)), "got {err:?}");
}

#[test]
fn sparql_subject_object_direction_compiles_outbound() {
    let q = parse(
        QueryLanguage::Sparql,
        "SELECT ?a ?b WHERE { ?a :extends ?b . }",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled
            .sql
            .contains("JOIN graph_edges e0 ON e0.source_id = n0.id"),
        "SPARQL subject must bind graph_edges.source_id; sql: {}",
        compiled.sql
    );
    assert!(
        compiled.sql.contains("ON n1.id = e0.target_id"),
        "SPARQL object must bind graph_edges.target_id; sql: {}",
        compiled.sql
    );
}

// --- WHERE OR support ---

#[test]
fn where_or_compiles_to_sql_or() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a:concept)-[e:extends]->(b) WHERE a.name = 'LoRA' OR a.name = 'QLoRA' RETURN a",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains(" OR "),
        "WHERE OR must produce SQL OR; sql: {}",
        compiled.sql
    );
    let has_lora = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Text(s) if s == "LoRA"));
    let has_qlora = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Text(s) if s == "QLoRA"));
    assert!(has_lora && has_qlora, "both OR values must be bound params");
}

#[test]
fn where_and_or_precedence() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a:concept)-[e:extends]->(b) WHERE a.name = 'X' AND a.kind = 'concept' OR b.kind = 'project' RETURN a",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains(" OR "),
        "expected OR in sql; sql: {}",
        compiled.sql
    );
}

// --- Synthetic edge compilation (ADR-041) ---

#[test]
fn synthetic_edge_joins_event_observations() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (ev)-[:observed_as_selected]->(m:memory) RETURN ev, m",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains("event_observations"),
        "sql: {}",
        compiled.sql
    );
    assert!(
        !compiled.sql.contains("graph_edges"),
        "sql: {}",
        compiled.sql
    );
    let has_role_param = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Text(s) if s == "selected"));
    assert!(has_role_param, "role 'selected' must be a bound parameter");
}

#[test]
fn synthetic_edge_event_source_binds_events_table() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (ev)-[:observed_as_selected]->(m:memory) RETURN ev, m",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains("FROM events "),
        "sql: {}",
        compiled.sql
    );
}

#[test]
fn synthetic_edge_event_node_projects_event_columns() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (ev)-[:observed_as_selected]->(m) RETURN ev",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled.sql.contains("ev_verb"), "sql: {}", compiled.sql);
    assert!(compiled.sql.contains("ev_outcome"), "sql: {}", compiled.sql);
    assert!(
        !compiled.sql.contains("ev_name,") && !compiled.sql.contains("ev_name "),
        "sql: {}",
        compiled.sql
    );
}

#[test]
fn synthetic_edge_namespace_filter_on_events_table() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (ev)-[:observed_as_selected]->(m) RETURN m",
    )
    .unwrap();
    let compiled = compile(&q, &scoped("test-ns")).unwrap();
    let ns_count = compiled
        .params
        .iter()
        .filter(|p| matches!(p, QueryValue::Text(s) if s == "test-ns"))
        .count();
    assert!(
        ns_count >= 2,
        "namespace must be filtered on both events and target; params: {:?}",
        compiled.params
    );
}

#[test]
fn synthetic_edge_candidate_role() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (ev)-[:observed_as_candidate]->(m) RETURN ev, m",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains("event_observations"),
        "sql: {}",
        compiled.sql
    );
    let has_candidate = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Text(s) if s == "candidate"));
    assert!(has_candidate, "role 'candidate' must be bound");
}

#[test]
fn synthetic_edge_multi_role() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (ev)-[:observed_as_candidate|observed_as_selected]->(m) RETURN m",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled.sql.contains("event_observations"),
        "sql: {}",
        compiled.sql
    );
    assert!(
        compiled.sql.contains("IN"),
        "multi-role must use IN; sql: {}",
        compiled.sql
    );
}

#[test]
fn mixed_synthetic_and_canonical_rejected() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (ev)-[:observed_as_selected|extends]->(m) RETURN m",
    )
    .unwrap();
    let err = compile(&q, &opts()).unwrap_err();
    assert!(matches!(err, QueryError::Compile(_)), "got {err:?}");
}

#[test]
fn synthetic_edge_inbound_rejected() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (m)<-[:observed_as_selected]-(ev) RETURN m",
    )
    .unwrap();
    let err = compile(&q, &opts()).unwrap_err();
    assert!(matches!(err, QueryError::Compile(_)), "got {err:?}");
}

// --- Variable-length OR ---

#[test]
fn variable_length_or_across_endpoints_rejected() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends*1..3]->(b) WHERE a.name = 'X' OR b.name = 'Y' RETURN a",
    )
    .unwrap();
    let result = compile(&q, &opts());
    assert!(
        matches!(result, Err(QueryError::Unsupported(_))),
        "got {result:?}"
    );
}

#[test]
fn variable_length_or_single_endpoint_still_works() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends*1..3]->(b) WHERE a.name = 'X' OR a.name = 'Y' RETURN a",
    )
    .unwrap();
    let result = compile(&q, &opts());
    assert!(
        result.is_ok(),
        "single-endpoint OR must compile; got {result:?}"
    );
}

#[test]
fn variable_length_and_across_endpoints_still_works() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends*1..3]->(b) WHERE a.name = 'X' AND b.name = 'Y' RETURN a",
    )
    .unwrap();
    let result = compile(&q, &opts());
    assert!(
        result.is_ok(),
        "AND across endpoints must compile; got {result:?}"
    );
}

#[test]
fn test_variable_length_or_compiles_to_or() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends*1..3]->(b) WHERE a.name = 'LoRA' OR a.name = 'QLoRA' RETURN b",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled.sql.contains(" OR "), "sql: {}", compiled.sql);
}

#[test]
fn test_single_endpoint_or_at_depth_1() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[r:extends]->(b) WHERE r.weight > 0.5 OR r.relation = 'extends' RETURN a",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled.sql.contains(" OR "), "sql: {}", compiled.sql);
}

#[test]
fn test_and_still_works() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (a)-[:extends*1..3]->(b) WHERE a.name = 'LoRA' AND a.kind = 'concept' RETURN b",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(!compiled.sql.contains(" OR "), "sql: {}", compiled.sql);
}

// --- parse_auto ---

#[test]
fn parse_auto_gql() {
    let q = parse_auto("MATCH (a:concept)-[:extends]->(b) RETURN b LIMIT 5").unwrap();
    assert_eq!(q.return_items, vec![ReturnItem::Variable("b".into())]);
}

#[test]
fn parse_auto_sparql() {
    let q = parse_auto("SELECT ?a ?b WHERE { ?a :extends ?b . }").unwrap();
    assert_eq!(
        q.return_items,
        vec![
            ReturnItem::Variable("a".into()),
            ReturnItem::Variable("b".into()),
        ]
    );
}

// --- Issue #755: inline property-map integer literals ---

#[test]
fn gql_inline_property_map_accepts_integer_literal() {
    // Previously a parse error: "expected string literal".
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:pull_request {number: 54}) RETURN n",
    );
    assert!(q.is_ok(), "integer literal must parse: {:?}", q.err());
}

#[test]
fn gql_inline_property_map_accepts_negative_integer_literal() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:pull_request {offset: -54}) RETURN n",
    );
    assert!(
        q.is_ok(),
        "negative integer literal must parse: {:?}",
        q.err()
    );
}

#[test]
fn gql_inline_property_map_integer_compiles_to_numeric_param() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:pull_request {number: 54}) RETURN n",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();

    let has_numeric_param = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Integer(54)));
    assert!(
        has_numeric_param,
        "integer literal must bind as QueryValue::Integer, not Float or text \
         (Float loses precision past 2^53 -- issue #832); params: {:?}",
        compiled.params
    );

    let number_predicate = compiled
        .sql
        .lines()
        .find(|l| l.contains("'$.number'"))
        .unwrap_or(&compiled.sql);
    assert!(
        !number_predicate.contains("COLLATE NOCASE"),
        "numeric comparison must not use text COLLATE NOCASE; sql: {}",
        compiled.sql
    );
}

#[test]
fn gql_inline_property_map_integer_matches_json_number_not_json_string() {
    // Regression for the root cause: json_extract() returns a JSON number as a
    // SQLite numeric storage class. Binding it as QueryValue::Text produced a
    // predicate that could never match (TEXT vs INTEGER/REAL never compare
    // equal in SQLite), which is exactly the silent-mismatch bug in #755.
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:pull_request {number: 54}) RETURN n",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled
            .params
            .iter()
            .any(|p| matches!(p, QueryValue::Integer(_) | QueryValue::Float(_))),
        "must bind a numeric parameter so it compares equal to json_extract's \
         numeric result; params: {:?}",
        compiled.params
    );
}

#[test]
fn gql_inline_property_map_quoted_number_still_binds_as_text() {
    // Decided behavior (documented in PR body for #755): a quoted numeric
    // string in an inline property map is a deliberate string literal and
    // keeps matching JSON strings only — it must NOT be coerced to a number.
    // This is what previously produced the "silently matches nothing" trap
    // against a JSON-number-typed property; the fix is that the *unquoted*
    // form (above) now works, not that the quoted form starts matching numbers.
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:pull_request {number: '54'}) RETURN n",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    let has_text_param = compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Text(s) if s == "54"));
    assert!(
        has_text_param,
        "quoted numeric literal must still bind as TEXT; params: {:?}",
        compiled.params
    );
}

#[test]
fn gql_inline_property_map_accepts_float_and_bool_literals() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:document {score: 4.5, archived: true}) RETURN n",
    );
    assert!(q.is_ok(), "float/bool literals must parse: {:?}", q.err());
    let compiled = compile(&q.unwrap(), &opts()).unwrap();
    assert!(compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Float(n) if *n == 4.5)));
    assert!(compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Integer(1))));
}

#[test]
fn gql_inline_property_map_entity_type_must_be_string() {
    let err = parse(
        QueryLanguage::Gql,
        "MATCH (n:document {entity_type: 54}) RETURN n",
    )
    .unwrap_err();
    assert!(matches!(err, QueryError::Parse { .. }));
}

#[test]
fn variable_length_inline_property_map_integer_compiles_to_numeric_param() {
    // Same fix, exercised through the variable-length (recursive CTE) compile path.
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:pull_request {number: 54})-[:extends*1..2]->(b) RETURN b",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Integer(54))));
}

#[test]
fn variable_length_inline_property_map_large_integer_binds_exact_i64() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:pull_request {number: 9007199254740993})-[:extends*1..2]->(b) RETURN b",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Integer(9007199254740993))));
}

// --- Issue #832: integer literal precision (2^53+1, i64 bounds, overflow) ---

#[test]
fn gql_inline_property_map_large_integer_binds_exact_i64_not_lossy_float() {
    // 2^53 + 1 = 9007199254740993 is the smallest positive integer that
    // cannot be represented exactly as f64 -- it rounds to 9007199254740992.0.
    // A JSON-number property with this value must be matched by an exact i64
    // parameter, not a lossy float.
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:artifact {number: 9007199254740993}) RETURN n",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled
            .params
            .iter()
            .any(|p| matches!(p, QueryValue::Integer(9007199254740993))),
        "large integer literal must bind as the exact i64, not a rounded f64; params: {:?}",
        compiled.params
    );
}

#[test]
fn gql_inline_property_map_i64_max_binds_exact() {
    let q = parse(
        QueryLanguage::Gql,
        &format!("MATCH (n:artifact {{number: {}}}) RETURN n", i64::MAX),
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Integer(n) if *n == i64::MAX)));
}

#[test]
fn gql_inline_property_map_i64_min_binds_exact() {
    let q = parse(
        QueryLanguage::Gql,
        &format!("MATCH (n:artifact {{number: {}}}) RETURN n", i64::MIN),
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Integer(n) if *n == i64::MIN)));
}

#[test]
fn gql_where_equality_large_integer_binds_exact_i64_not_lossy_float() {
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:artifact) WHERE n.number = 9007199254740993 RETURN n",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(
        compiled
            .params
            .iter()
            .any(|p| matches!(p, QueryValue::Integer(9007199254740993))),
        "WHERE equality with a large integer literal must bind exact i64; params: {:?}",
        compiled.params
    );
}

#[test]
fn gql_where_equality_i64_bounds_bind_exact() {
    for bound in [i64::MIN, i64::MAX] {
        let q = parse(
            QueryLanguage::Gql,
            &format!("MATCH (n:artifact) WHERE n.number = {bound} RETURN n"),
        )
        .unwrap();
        let compiled = compile(&q, &opts()).unwrap();
        assert!(
            compiled
                .params
                .iter()
                .any(|p| matches!(p, QueryValue::Integer(n) if *n == bound)),
            "bound {bound} must bind exact; params: {:?}",
            compiled.params
        );
    }
}

#[test]
fn variable_length_where_i64_bounds_bind_exact() {
    // Exercises the variable-length WHERE compiler branch (compile_var_len_condition,
    // sql.rs:919), not the start-node inline property map path already covered above.
    for bound in [i64::MIN, i64::MAX] {
        let q = parse(
            QueryLanguage::Gql,
            &format!("MATCH (a)-[:extends*1..3]->(b) WHERE b.number = {bound} RETURN b"),
        )
        .unwrap();
        let compiled = compile(&q, &opts()).unwrap();
        assert!(
            compiled
                .params
                .iter()
                .any(|p| matches!(p, QueryValue::Integer(n) if *n == bound)),
            "variable-length WHERE bound {bound} must bind exact i64; params: {:?}",
            compiled.params
        );
    }
}

#[test]
fn variable_length_end_node_inline_property_map_i64_bounds_bind_exact() {
    // Exercises the end-node inline-map CTE path (end.properties compiled via
    // compile_property_equality), not the start-node inline map already covered above.
    for bound in [i64::MIN, i64::MAX] {
        let q = parse(
            QueryLanguage::Gql,
            &format!("MATCH (a)-[:extends*1..3]->(b:artifact {{number: {bound}}}) RETURN b"),
        )
        .unwrap();
        let compiled = compile(&q, &opts()).unwrap();
        assert!(
            compiled
                .params
                .iter()
                .any(|p| matches!(p, QueryValue::Integer(n) if *n == bound)),
            "end-node inline-map bound {bound} must bind exact i64; params: {:?}",
            compiled.params
        );
    }
}

#[test]
fn gql_inline_property_map_integer_overflow_rejected_at_parse_time() {
    // i64::MAX + 1 -- one digit sequence beyond the supported integer range.
    let overflow = "9223372036854775808";
    let err = parse(
        QueryLanguage::Gql,
        &format!("MATCH (n:artifact {{number: {overflow}}}) RETURN n"),
    )
    .unwrap_err();
    assert!(
        matches!(err, QueryError::Parse { .. }),
        "out-of-range integer literal must be rejected at parse time, not silently \
         truncated or coerced to float; got: {err:?}"
    );
}

#[test]
fn gql_where_equality_integer_overflow_rejected_at_parse_time() {
    let overflow = "9223372036854775808";
    let err = parse(
        QueryLanguage::Gql,
        &format!("MATCH (n:artifact) WHERE n.number = {overflow} RETURN n"),
    )
    .unwrap_err();
    assert!(matches!(err, QueryError::Parse { .. }));
}

#[test]
fn gql_inline_property_map_float_overflow_rejected() {
    // A decimal literal (has a '.') whose magnitude overflows f64 to infinity.
    let huge = format!("{}.0", "9".repeat(400));
    let err = parse(
        QueryLanguage::Gql,
        &format!("MATCH (n:document {{score: {huge}}}) RETURN n"),
    )
    .unwrap_err();
    assert!(
        matches!(err, QueryError::Parse { .. }),
        "non-finite float literal must be rejected, not silently bound as Infinity; got: {err:?}"
    );
}

// --- Numeric literal grammar (docs/design.md): digits required on both
// sides of the dot. `1.`, `-.5`, and `.5` must all be rejected, not
// delegated to f64::parse's looser rules. ---

#[test]
fn gql_inline_property_map_trailing_dot_float_rejected() {
    let err = parse(
        QueryLanguage::Gql,
        "MATCH (n:document {score: 1.}) RETURN n",
    )
    .unwrap_err();
    assert!(
        matches!(err, QueryError::Parse { .. }),
        "'1.' has no digits after the dot and must be rejected; got: {err:?}"
    );
}

#[test]
fn gql_inline_property_map_negative_leading_dot_float_rejected() {
    let err = parse(
        QueryLanguage::Gql,
        "MATCH (n:document {score: -.5}) RETURN n",
    )
    .unwrap_err();
    assert!(
        matches!(err, QueryError::Parse { .. }),
        "'-.5' has no digits before the dot and must be rejected; got: {err:?}"
    );
}

#[test]
fn gql_inline_property_map_leading_dot_float_rejected() {
    let err = parse(
        QueryLanguage::Gql,
        "MATCH (n:document {score: .5}) RETURN n",
    )
    .unwrap_err();
    assert!(
        matches!(err, QueryError::Parse { .. }),
        "'.5' has no digits before the dot and must be rejected; got: {err:?}"
    );
}

#[test]
fn gql_inline_property_map_well_formed_float_still_parses() {
    // Digits on both sides of the dot must keep working (regression guard
    // against over-tightening the grammar check).
    let q = parse(
        QueryLanguage::Gql,
        "MATCH (n:document {score: 1.5}) RETURN n",
    )
    .unwrap();
    let compiled = compile(&q, &opts()).unwrap();
    assert!(compiled
        .params
        .iter()
        .any(|p| matches!(p, QueryValue::Float(n) if *n == 1.5)));
}

// --- Issue #849: substrate node labels (entity/note) must be satisfiable ---
//
// Stored `kind` values are always granular (concept/document/task/...); the
// substrate words entity/note/edge/event name a *table*, not a stored `kind`.
// Compiling a bare substrate label straight into `kind = ?` (as fixed/`event`
// filters did) makes the predicate unsatisfiable by construction. The fix
// filters the union's `substrate_kind` discriminator column instead. These
// tests exercise the compiled SQL shape (fixed-length + variable-length +
// SPARQL) and, for the fixed-length case, execute the compiled SQL against a
// minimal in-memory fixture matching `khive-db`'s substrate schema to prove
// the query is actually satisfiable end-to-end, not just shaped correctly.

mod substrate_labels {
    use super::*;
    use rusqlite::Connection;

    /// Minimal fixture matching `crates/khive-db/sql/schema.sql`'s substrate
    /// tables. All four must exist (even empty) because the compiler always
    /// binds a plain node pattern through the `entities UNION notes UNION
    /// events UNION graph_edges` primary-substrate source.
    fn fixture_db() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE entities (
                id TEXT PRIMARY KEY, namespace TEXT NOT NULL, kind TEXT NOT NULL,
                name TEXT NOT NULL, description TEXT, properties TEXT,
                tags TEXT NOT NULL DEFAULT '[]', created_at INTEGER NOT NULL,
                updated_at INTEGER NOT NULL, deleted_at INTEGER,
                entity_type TEXT, merged_into TEXT, merge_event_id TEXT
            );
            CREATE TABLE notes (
                id TEXT PRIMARY KEY, namespace TEXT NOT NULL, kind TEXT NOT NULL,
                status TEXT NOT NULL DEFAULT 'active', name TEXT,
                content TEXT NOT NULL DEFAULT '', salience REAL, decay_factor REAL,
                expires_at INTEGER, properties TEXT, created_at INTEGER NOT NULL,
                updated_at INTEGER NOT NULL, deleted_at INTEGER
            );
            CREATE TABLE events (
                id TEXT PRIMARY KEY, namespace TEXT NOT NULL, verb TEXT NOT NULL,
                substrate TEXT NOT NULL, actor TEXT NOT NULL, outcome TEXT NOT NULL,
                data TEXT, duration_us INTEGER NOT NULL DEFAULT 0, target_id TEXT,
                created_at INTEGER NOT NULL, kind TEXT NOT NULL DEFAULT 'audit',
                payload TEXT NOT NULL DEFAULT '{}',
                payload_schema_version INTEGER NOT NULL DEFAULT 1,
                profile_state_version INTEGER, session_id TEXT,
                aggregate_kind TEXT, aggregate_id TEXT
            );
            CREATE TABLE graph_edges (
                namespace TEXT NOT NULL, id TEXT NOT NULL, source_id TEXT NOT NULL,
                target_id TEXT NOT NULL, relation TEXT NOT NULL,
                weight REAL NOT NULL DEFAULT 1.0, created_at INTEGER NOT NULL,
                updated_at INTEGER NOT NULL, deleted_at INTEGER, metadata TEXT,
                target_backend TEXT, PRIMARY KEY (namespace, id)
            );
            INSERT INTO entities
                (id, namespace, kind, name, description, properties, tags,
                 created_at, updated_at, deleted_at, entity_type)
            VALUES
                ('e-fixture-1', 'local', 'concept', 'X', NULL, '{}', '[]',
                 0, 0, NULL, NULL);
            INSERT INTO notes
                (id, namespace, kind, status, name, content, salience,
                 decay_factor, expires_at, properties, created_at, updated_at,
                 deleted_at)
            VALUES
                ('n-fixture-1', 'local', 'observation', 'active', 'X', 'body',
                 NULL, NULL, NULL, '{}', 0, 0, NULL);",
        )
        .unwrap();
        conn
    }

    fn run(conn: &Connection, compiled: &CompiledQuery) -> Vec<String> {
        let db_params: Vec<Box<dyn rusqlite::ToSql>> = compiled
            .params
            .iter()
            .map(|p| -> Box<dyn rusqlite::ToSql> {
                match p {
                    QueryValue::Null => Box::new(Option::<i64>::None),
                    QueryValue::Integer(n) => Box::new(*n),
                    QueryValue::Float(n) => Box::new(*n),
                    QueryValue::Text(s) => Box::new(s.clone()),
                    QueryValue::Blob(b) => Box::new(b.clone()),
                }
            })
            .collect();
        let param_refs: Vec<&dyn rusqlite::ToSql> = db_params.iter().map(|b| b.as_ref()).collect();
        let mut stmt = conn.prepare(&compiled.sql).unwrap();
        stmt.query_map(param_refs.as_slice(), |row| row.get::<_, String>(0))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap()
    }

    /// `fixture_db()` plus a second entity and a `graph_edges` row connecting
    /// it to `e-fixture-1`. SPARQL requires at least one variable-to-variable
    /// relation triple to parse (`no edge patterns found` otherwise), so any
    /// SPARQL regression test needs a connected graph, unlike the single-node
    /// GQL substrate-label tests below.
    fn fixture_db_with_edge() -> Connection {
        let conn = fixture_db();
        conn.execute_batch(
            "INSERT INTO entities
                (id, namespace, kind, name, description, properties, tags,
                 created_at, updated_at, deleted_at, entity_type)
            VALUES
                ('e-fixture-2', 'local', 'document', 'Y', NULL, '{}', '[]',
                 0, 0, NULL, NULL);
            INSERT INTO graph_edges
                (namespace, id, source_id, target_id, relation, weight,
                 created_at, updated_at, deleted_at, metadata, target_backend)
            VALUES
                ('local', 'edge-fixture-1', 'e-fixture-1', 'e-fixture-2',
                 'extends', 1.0, 0, 0, NULL, NULL, NULL);",
        )
        .unwrap();
        conn
    }

    #[test]
    fn entity_substrate_label_compiles_without_unsatisfiable_kind_filter() {
        let q = parse(
            QueryLanguage::Gql,
            "MATCH (e:entity) WHERE e.name = 'X' RETURN e.id",
        )
        .unwrap();
        let compiled = compile(&q, &opts()).unwrap();
        assert!(
            compiled.sql.contains("substrate_kind = ?"),
            "substrate label 'entity' must filter substrate_kind, not kind; sql: {}",
            compiled.sql
        );
        assert!(
            !compiled.sql.contains("n0.kind = ?"),
            "substrate label 'entity' must not also emit an unsatisfiable kind filter; sql: {}",
            compiled.sql
        );

        let conn = fixture_db();
        let rows = run(&conn, &compiled);
        assert_eq!(
            rows,
            vec!["e-fixture-1".to_string()],
            "MATCH (e:entity) WHERE e.name = 'X' must return the existing entity row; sql: {}",
            compiled.sql
        );
    }

    #[test]
    fn note_substrate_label_compiles_without_unsatisfiable_kind_filter() {
        let q = parse(
            QueryLanguage::Gql,
            "MATCH (n:note) WHERE n.name = 'X' RETURN n.id",
        )
        .unwrap();
        let compiled = compile(&q, &opts()).unwrap();
        assert!(
            compiled.sql.contains("substrate_kind = ?"),
            "substrate label 'note' must filter substrate_kind, not kind; sql: {}",
            compiled.sql
        );

        let conn = fixture_db();
        let rows = run(&conn, &compiled);
        assert_eq!(
            rows,
            vec!["n-fixture-1".to_string()],
            "MATCH (n:note) WHERE n.name = 'X' must return the existing note row; sql: {}",
            compiled.sql
        );
    }

    #[test]
    fn granular_label_still_filters_kind_column() {
        let q = parse(QueryLanguage::Gql, "MATCH (e:concept) RETURN e.id").unwrap();
        let compiled = compile(&q, &opts()).unwrap();
        assert!(
            compiled.sql.contains("n0.kind = ?"),
            "granular label 'concept' must still emit kind = ?; sql: {}",
            compiled.sql
        );
        let has_concept_param = compiled
            .params
            .iter()
            .any(|p| matches!(p, QueryValue::Text(s) if s == "concept"));
        assert!(has_concept_param, "params: {:?}", compiled.params);

        let conn = fixture_db();
        let rows = run(&conn, &compiled);
        assert_eq!(
            rows,
            vec!["e-fixture-1".to_string()],
            "MATCH (e:concept) must still return the concept-kind entity row; sql: {}",
            compiled.sql
        );
    }

    #[test]
    fn sparql_entity_substrate_label_compiles_and_returns_row() {
        let q = parse(
            QueryLanguage::Sparql,
            "SELECT ?e WHERE { ?e a :entity . ?e :name \"X\" . ?e :extends ?c . }",
        )
        .unwrap();
        let compiled = compile(&q, &opts()).unwrap();
        assert!(
            compiled.sql.contains("substrate_kind = ?"),
            "SPARQL 'a :entity' must filter substrate_kind, not kind (frontend parity); sql: {}",
            compiled.sql
        );

        let conn = fixture_db_with_edge();
        let db_params: Vec<Box<dyn rusqlite::ToSql>> = compiled
            .params
            .iter()
            .map(|p| -> Box<dyn rusqlite::ToSql> {
                match p {
                    QueryValue::Null => Box::new(Option::<i64>::None),
                    QueryValue::Integer(n) => Box::new(*n),
                    QueryValue::Float(n) => Box::new(*n),
                    QueryValue::Text(s) => Box::new(s.clone()),
                    QueryValue::Blob(b) => Box::new(b.clone()),
                }
            })
            .collect();
        let param_refs: Vec<&dyn rusqlite::ToSql> = db_params.iter().map(|b| b.as_ref()).collect();
        let mut stmt = conn.prepare(&compiled.sql).unwrap();
        let ids: Vec<String> = stmt
            .query_map(param_refs.as_slice(), |row| row.get::<_, String>("e_id"))
            .unwrap()
            .collect::<Result<_, _>>()
            .unwrap();
        assert_eq!(
            ids,
            vec!["e-fixture-1".to_string()],
            "SPARQL entity-substrate query must return the existing entity row; sql: {}",
            compiled.sql
        );
    }

    #[test]
    fn variable_length_entity_substrate_label_filters_substrate_kind() {
        let q = parse(
            QueryLanguage::Gql,
            "MATCH (a:entity)-[:extends*1..2]->(b) RETURN b LIMIT 5",
        )
        .unwrap();
        let compiled = compile(&q, &opts()).unwrap();
        assert!(
            compiled.sql.contains("s.substrate_kind = ?"),
            "variable-length seed with substrate label 'entity' must filter \
             s.substrate_kind, not s.kind; sql: {}",
            compiled.sql
        );
    }
}