ursa-cli 0.7.0

The ursa command-line tool: SQL over Parquet, CSV, JSON and Arrow files, local or in object storage.
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
//! The `ursa` binary, run as a user runs it.

use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};

/// The workspace root, where the docs' data files live.
fn workspace() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .to_path_buf()
}

fn karate_edges() -> String {
    workspace()
        .join("python/ursa/datasets/data/karate_edges.csv")
        .display()
        .to_string()
}

fn ursa(args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_ursa"))
        .args(args)
        .current_dir(workspace())
        .output()
        .expect("ursa runs")
}

fn ursa_with_stdin(args: &[&str], stdin: &str) -> Output {
    let mut child = Command::new(env!("CARGO_BIN_EXE_ursa"))
        .args(args)
        .current_dir(workspace())
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("ursa runs");
    child
        .stdin
        .take()
        .unwrap()
        .write_all(stdin.as_bytes())
        .unwrap();
    child.wait_with_output().unwrap()
}

/// stdout of a run that must succeed.
fn ok(output: Output) -> String {
    assert!(
        output.status.success(),
        "ursa failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8(output.stdout).unwrap()
}

/// stderr of a run that must fail.
fn err(output: Output) -> String {
    assert!(
        !output.status.success(),
        "ursa should have failed; stdout: {}",
        String::from_utf8_lossy(&output.stdout)
    );
    String::from_utf8(output.stderr).unwrap()
}

/// Getting Started, "Query a file", run from the workspace root.
#[test]
fn query_a_file_matches_getting_started() {
    let out = ok(ursa(&[
        "-c",
        "SELECT * FROM 'python/ursa/datasets/data/karate_edges.csv' LIMIT 3",
    ]));
    assert_eq!(
        out,
        "\
+-----+-----+
| src | dst |
+-----+-----+
| 0   | 1   |
| 0   | 2   |
| 0   | 3   |
+-----+-----+
"
    );
}

#[test]
fn output_formats() {
    let sql = format!("SELECT * FROM '{}' LIMIT 2", karate_edges());
    assert_eq!(
        ok(ursa(&["--format", "csv", "-c", &sql])),
        "src,dst\n0,1\n0,2\n"
    );
    assert_eq!(
        ok(ursa(&["--format", "tsv", "-c", &sql])),
        "src\tdst\n0\t1\n0\t2\n"
    );
    assert_eq!(
        ok(ursa(&["--format", "json", "-c", &sql])),
        "[{\"src\":0,\"dst\":1},{\"src\":0,\"dst\":2}]\n"
    );
    assert_eq!(
        ok(ursa(&["--format", "ndjson", "-c", &sql])),
        "{\"src\":0,\"dst\":1}\n{\"src\":0,\"dst\":2}\n"
    );
    // An Arrow IPC stream starts with the continuation marker.
    let arrow = ursa(&["--format", "arrow", "-c", &sql]);
    assert!(arrow.status.success());
    assert_eq!(&arrow.stdout[..4], &[0xff, 0xff, 0xff, 0xff]);
}

#[test]
fn empty_results_keep_their_header() {
    assert_eq!(
        ok(ursa(&["-c", "SELECT 1 AS x WHERE false"])),
        "+---+\n| x |\n+---+\n+---+\n"
    );
    assert_eq!(
        ok(ursa(&[
            "--format",
            "csv",
            "-c",
            "SELECT 1 AS x WHERE false"
        ])),
        "x\n"
    );
    assert_eq!(
        ok(ursa(&[
            "--format",
            "json",
            "-c",
            "SELECT 1 AS x WHERE false"
        ])),
        "[]\n"
    );
}

#[test]
fn several_statements_print_each_result() {
    let sql = format!(
        "CREATE VIEW ties AS SELECT * FROM '{}';
         SELECT count(*) AS edges FROM ties;
         SELECT max(dst) AS top FROM ties;",
        karate_edges()
    );
    assert_eq!(
        ok(ursa(&["--format", "csv", "-c", &sql])),
        "edges\n78\ntop\n33\n"
    );
}

#[test]
fn show_ursa_settings() {
    assert_eq!(
        ok(ursa(&[
            "--format",
            "csv",
            "-c",
            "SHOW ursa.index_storage_limit; SET ursa.index_storage_limit = '1GiB'; \
             SHOW ursa.index_storage_limit",
        ])),
        "name,value\nursa.index_storage_limit,4GiB\nname,value\nursa.index_storage_limit,1GiB\n"
    );
    let all = ok(ursa(&["--format", "csv", "-c", "SHOW ALL"]));
    assert!(all.contains("\nursa.index_storage_limit,4GiB\n"), "{all}");
}

#[test]
fn commands_and_files_run_in_order() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("q.sql");
    std::fs::write(&file, "SELECT 2 AS b;\n").unwrap();
    let file = file.display().to_string();
    let out = ok(ursa(&[
        "--format",
        "csv",
        "-c",
        "SELECT 1 AS a",
        "--file",
        &file,
        "-c",
        "SELECT 3 AS c",
    ]));
    assert_eq!(out, "a\n1\nb\n2\nc\n3\n");
}

/// `-f` runs a file, as in DuckDB and psql.
#[test]
fn short_f_runs_a_file() {
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("q.sql");
    std::fs::write(&file, "SELECT 2 AS b;\n").unwrap();
    let file = file.display().to_string();
    assert_eq!(ok(ursa(&["--format", "csv", "-f", &file])), "b\n2\n");
}

/// `ursa -f json` reads like the old spelling of `--format json`; say so.
#[test]
fn short_f_with_a_format_name_points_to_format() {
    let message = err(ursa(&["-f", "json", "-c", "SELECT 1"]));
    assert!(
        message.contains("cannot read 'json'")
            && message.contains("to choose the output format, use --format json"),
        "{message}"
    );
}

/// `ursa --format csv … | head`: once the reader is gone, ursa stops
/// quietly with status 0, in every format (#317).
#[cfg(unix)]
#[test]
fn a_closed_pipe_ends_quietly_in_every_format() {
    use std::io::{BufRead, BufReader};
    let sql = "SELECT value, value * 2 AS twice FROM generate_series(1, 300000)";
    for format in ["csv", "tsv", "table", "json", "ndjson"] {
        let mut child = Command::new(env!("CARGO_BIN_EXE_ursa"))
            .args(["--format", format, "-c", sql])
            .current_dir(workspace())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("ursa runs");
        let mut first = String::new();
        BufReader::new(child.stdout.take().unwrap())
            .read_line(&mut first)
            .unwrap();
        // The reader is dropped here: the pipe closes with output pending.
        let out = child.wait_with_output().unwrap();
        assert!(!first.is_empty(), "{format}: no first line");
        assert!(
            out.status.success(),
            "{format}: exit {:?}, stderr: {}",
            out.status.code(),
            String::from_utf8_lossy(&out.stderr)
        );
        assert_eq!(String::from_utf8_lossy(&out.stderr), "", "{format}");
    }
}

#[test]
fn sql_from_stdin() {
    let sql = format!("SELECT count(*) AS n FROM '{}';", karate_edges());
    let out = ursa_with_stdin(&["--format", "csv"], &sql);
    assert_eq!(ok(out), "n\n78\n");
}

#[test]
fn copy_to_parquet_and_read_it_back() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("edges.parquet").display().to_string();
    let copy = format!(
        "COPY (SELECT * FROM '{}' WHERE src = 0) TO '{target}'",
        karate_edges()
    );
    assert_eq!(ok(ursa(&["--format", "csv", "-c", &copy])), "count\n16\n");
    let read = format!("SELECT count(*) AS n, max(dst) AS top FROM '{target}'");
    assert_eq!(
        ok(ursa(&["--format", "csv", "-c", &read])),
        "n,top\n16,31\n"
    );
}

#[test]
fn gzip_csv() {
    use flate2::write::GzEncoder;
    use flate2::Compression;

    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("edges.csv.gz");
    let mut gz = GzEncoder::new(
        std::fs::File::create(&path).unwrap(),
        Compression::default(),
    );
    gz.write_all(b"src,dst\n0,1\n1,2\n2,0\n").unwrap();
    gz.finish().unwrap();
    let sql = format!(
        "SELECT sum(dst) AS s, count(*) AS n FROM '{}'",
        path.display()
    );
    assert_eq!(ok(ursa(&["--format", "csv", "-c", &sql])), "s,n\n3,3\n");
}

#[test]
fn json_lines_by_extension() {
    use flate2::write::GzEncoder;
    use flate2::Compression;

    let dir = tempfile::tempdir().unwrap();
    let lines = "{\"src\": 0, \"dst\": 1}\n{\"src\": 1, \"dst\": 2}\n";
    std::fs::create_dir(dir.path().join("parts")).unwrap();
    for name in [
        "edges.json",
        "edges.jsonl",
        "edges.ndjson",
        "parts/a.jsonl",
        "parts/b.jsonl",
    ] {
        std::fs::write(dir.path().join(name), lines).unwrap();
    }
    let mut gz = GzEncoder::new(
        std::fs::File::create(dir.path().join("edges.jsonl.gz")).unwrap(),
        Compression::default(),
    );
    gz.write_all(lines.as_bytes()).unwrap();
    gz.finish().unwrap();
    let root = dir.path().display();
    for location in [
        "edges.json",
        "edges.jsonl",
        "edges.ndjson",
        "edges.jsonl.gz",
        "parts/*.jsonl",
        "parts/",
    ] {
        let sql = format!("SELECT count(*) AS n, max(dst) AS top FROM '{root}/{location}'");
        let n = if location.starts_with("parts") { 4 } else { 2 };
        assert_eq!(
            ok(ursa(&["--format", "csv", "-c", &sql])),
            format!("n,top\n{n},2\n"),
            "{location}"
        );
    }
    // COPY writes .jsonl as it writes .json.
    let copy = format!("COPY (SELECT 7 AS x) TO '{root}/out.jsonl'");
    assert_eq!(ok(ursa(&["--format", "csv", "-c", &copy])), "count\n1\n");
    let read = format!("SELECT x FROM '{root}/out.jsonl'");
    assert_eq!(ok(ursa(&["--format", "csv", "-c", &read])), "x\n7\n");
}

#[test]
fn read_functions() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("edges.txt"), "0|1\n1|2\n2|0\n").unwrap();
    std::fs::write(dir.path().join("a.csv"), "src,dst\n0,1\n").unwrap();
    std::fs::write(dir.path().join("b.csv"), "src,dst\n1,2\n2,3\n").unwrap();
    std::fs::write(
        dir.path().join("array.json"),
        "[{\"src\": 0, \"dst\": 5}, {\"src\": 1, \"dst\": 6}]",
    )
    .unwrap();
    let root = dir.path().display();
    let csv = |sql: String| ok(ursa(&["--format", "csv", "-c", &sql]));
    assert_eq!(
        csv(format!(
            "SELECT sum(column_2) AS s FROM read_csv('{root}/edges.txt', header => false, \
             delim => '|')"
        )),
        "s\n3\n"
    );
    // DuckDB's `name = value` too.
    assert_eq!(
        csv(format!(
            "SELECT count(*) AS n FROM read_csv('{root}/edges.txt', header = false, sep = '|')"
        )),
        "n\n3\n"
    );
    assert_eq!(
        csv(format!(
            "SELECT count(*) AS n FROM read_csv(['{root}/a.csv', '{root}/b.csv'])"
        )),
        "n\n3\n"
    );
    assert_eq!(
        csv(format!(
            "SELECT count(*) AS n FROM read_csv('{root}/*.csv')"
        )),
        "n\n3\n"
    );
    assert_eq!(
        csv(format!(
            "SELECT sum(dst) AS s FROM read_json('{root}/array.json', format => 'array')"
        )),
        "s\n11\n"
    );
    // In a subquery, a CTE and a view.
    assert_eq!(
        csv(format!(
            "CREATE VIEW e AS SELECT * FROM read_csv('{root}/a.csv'); \
             WITH b AS (SELECT * FROM read_csv('{root}/b.csv')) \
             SELECT (SELECT count(*) FROM e) + (SELECT count(*) FROM b) AS n"
        )),
        "n\n3\n"
    );
    assert_eq!(
        err(ursa(&[
            "-c",
            &format!("SELECT * FROM read_cvs('{root}/a.csv')")
        ])),
        "Error: there is no table function 'read_cvs'; did you mean 'read_csv'?\n"
    );
    assert_eq!(
        err(ursa(&[
            "-c",
            &format!("SELECT * FROM read_csv('{root}/a.csv', qoute => '\"')")
        ])),
        "Error: read_csv() has no option 'qoute'; did you mean 'quote'? (it takes header, \
         delim, sep, delimiter, quote, compression)\n"
    );
}

#[test]
fn local_glob_and_directory() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("a.csv"), "src,dst\n0,1\n").unwrap();
    std::fs::write(dir.path().join("b.csv"), "src,dst\n1,2\n2,3\n").unwrap();
    let root = dir.path().display();
    let glob = format!("SELECT count(*) AS n FROM '{root}/*.csv'");
    assert_eq!(ok(ursa(&["--format", "csv", "-c", &glob])), "n\n3\n");
    let directory = format!("SELECT count(*) AS n FROM '{root}/'");
    assert_eq!(ok(ursa(&["--format", "csv", "-c", &directory])), "n\n3\n");
}

#[test]
fn errors_are_for_people() {
    let e = err(ursa(&["-c", "SELECT * FROM 'no_such_file.csv'"]));
    assert_eq!(e, "Error: no file found at 'no_such_file.csv'\n");

    let e = err(ursa(&["-c", "SELEC 1"]));
    assert!(e.starts_with("Error: syntax error: "), "{e}");
    assert!(!e.contains("ParserError"), "{e}");

    let e = err(ursa(&["-c", "SELECT 'a'::int"]));
    assert!(!e.contains("Optimizer rule"), "{e}");

    // A syntax error anywhere runs nothing.
    let out = ursa(&["-c", "SELECT 1 AS a; SELEC 2"]);
    assert!(!out.status.success());
    assert!(out.stdout.is_empty());
}

/// Getting Started, "Define a graph", in one invocation. Getting Started omits
/// the `ORDER BY`; it is here because row order is not guaranteed.
#[test]
fn define_a_graph_matches_getting_started() {
    let data = "python/ursa/datasets/data";
    let sql = format!(
        "CREATE VIEW members AS SELECT * FROM '{data}/karate_nodes.csv';
         CREATE VIEW ties    AS SELECT * FROM '{data}/karate_edges.csv';

         CREATE PROPERTY GRAPH karate
           VERTEX TABLES (members KEY (id))
           EDGE TABLES (
             ties SOURCE KEY (src) REFERENCES members (id)
                  DESTINATION KEY (dst) REFERENCES members (id)
           );

         CREATE PROPERTY GRAPH karate_edges_only
           EDGE TABLES (ties SOURCE KEY (src) DESTINATION KEY (dst));

         SELECT * FROM karate.nodes ORDER BY id LIMIT 3;"
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+----+--------+
| id | club   |
+----+--------+
| 0  | Mr. Hi |
| 1  | Mr. Hi |
| 2  | Mr. Hi |
+----+--------+
"
    );
}

#[test]
fn graphs_last_for_the_invocation() {
    let define = format!(
        "CREATE VIEW ties AS SELECT * FROM '{}';
         CREATE PROPERTY GRAPH g EDGE TABLES (ties SOURCE KEY (src) DESTINATION KEY (dst))",
        karate_edges()
    );
    let out = ok(ursa(&[
        "--format",
        "csv",
        "-c",
        &define,
        "-c",
        "SELECT count(*) AS nodes FROM g.nodes",
        "-c",
        "SELECT count(*) AS edges FROM g.edges; DROP PROPERTY GRAPH g",
    ]));
    assert_eq!(out, "nodes\n34\nedges\n78\n");

    let e = err(ursa(&["-c", "SELECT * FROM g.nodes"]));
    assert!(e.contains("g.nodes"), "{e}");
    let e = err(ursa(&[
        "-c",
        "CREATE PROPERTY GRAPH g EDGE TABLES (ties SOURCE KEY (src, x) DESTINATION KEY (dst))",
    ]));
    assert!(
        e.starts_with("Error: multi-column keys are not supported yet at Line: ")
            && e.ends_with("; KEY, SOURCE KEY, DESTINATION KEY and REFERENCES take one column\n"),
        "{e}"
    );
}

#[test]
fn only_ursa_files_are_databases() {
    let e = err(ursa(&["query.sql", "-c", "SELECT 1"]));
    assert!(e.contains("'query.sql' is not a database file"), "{e}");
    let e = err(ursa(&["--readonly", "-c", "SELECT 1"]));
    assert!(e.contains("--readonly"), "{e}");
}

/// With stdin not a terminal and empty, there is nothing to run (the shell
/// starts only on a terminal; see tests/shell_pty.rs).
#[test]
fn no_sql_on_a_pipe_does_nothing() {
    let out = ursa_with_stdin(&[], "");
    assert!(out.status.success());
    assert_eq!(String::from_utf8(out.stdout).unwrap(), "");
    assert_eq!(String::from_utf8(out.stderr).unwrap(), "");
}

/// `-init` runs first, before `-c`; dot-commands in it work, an error in it
/// is printed and the rest runs.
#[test]
fn init_runs_before_the_sql() {
    let dir = tempfile::tempdir().unwrap();
    let init = dir.path().join("setup.sql");
    std::fs::write(
        &init,
        ".mode csv\nCREATE VIEW v AS SELECT 42 AS answer;\nSELECT nope;\n",
    )
    .unwrap();
    let init = init.display().to_string();
    for flag in ["-init", "--init"] {
        let out = ursa(&[flag, &init, "-c", "SELECT * FROM v"]);
        assert!(out.status.success());
        assert_eq!(String::from_utf8(out.stdout).unwrap(), "answer\n42\n");
        let e = String::from_utf8(out.stderr).unwrap();
        assert!(e.starts_with("Error: ") && e.lines().count() == 1, "{e}");
    }
    // --format on the command line wins over the file's .mode.
    let out = ok(ursa(&[
        "-init",
        &init,
        "--format",
        "json",
        "-c",
        "SELECT * FROM v",
    ]));
    assert_eq!(out, "[{\"answer\":42}]\n");
    // SQL on stdin too.
    let out = ok(ursa_with_stdin(&["-init", &init], "SELECT * FROM v;"));
    assert_eq!(out, "answer\n42\n");
}

/// `~/.ursarc` is for the shell: scripts do not read it.
#[test]
fn scripts_do_not_read_ursarc() {
    let home = tempfile::tempdir().unwrap();
    std::fs::write(home.path().join(".ursarc"), ".mode csv\n").unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_ursa"))
        .args(["-c", "SELECT 1 AS x"])
        .env("HOME", home.path())
        .output()
        .unwrap();
    assert_eq!(
        ok(out),
        "+---+\n| x |\n+---+\n| 1 |\n+---+\n",
        "~/.ursarc changed a script's output"
    );
    let e = err(ursa(&["-init", "x.sql", "-no-init", "-c", "SELECT 1"]));
    assert!(e.contains("cannot be used with"), "{e}");
}

/// The Getting Started graph: `members` and `ties` over the karate files, and
/// `karate` over them.
fn define_karate() -> String {
    let data = "python/ursa/datasets/data";
    format!(
        "CREATE VIEW members AS SELECT * FROM '{data}/karate_nodes.csv';
         CREATE VIEW ties    AS SELECT * FROM '{data}/karate_edges.csv';
         CREATE PROPERTY GRAPH karate
           VERTEX TABLES (members KEY (id))
           EDGE TABLES (
             ties SOURCE KEY (src) REFERENCES members (id)
                  DESTINATION KEY (dst) REFERENCES members (id)
           );"
    )
}

/// Getting Started, "Run an algorithm".
#[test]
fn run_an_algorithm_matches_getting_started() {
    let sql = format!(
        "{}
         SELECT id, round(pagerank, 4) AS pagerank
         FROM pagerank(karate, direction => 'both')
         ORDER BY pagerank DESC
         LIMIT 5;",
        define_karate()
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+----+----------+
| id | pagerank |
+----+----------+
| 33 | 0.1009   |
| 0  | 0.097    |
| 32 | 0.0717   |
| 2  | 0.0571   |
| 1  | 0.0529   |
+----+----------+
"
    );
}

/// Getting Started, "Combine algorithms and attributes", with the joins
/// written with `ON`: DataFusion 55 cannot plan a chain of four `USING`
/// joins (see `ursa-engine/tests/graph_functions.rs`).
#[test]
fn combine_algorithms_and_attributes() {
    let sql = format!(
        "{}
         SELECT n.id, club, degree, triangle_count AS triangles, louvain AS community
         FROM karate.nodes AS n
         JOIN degree(karate, direction => 'both') AS d ON d.id = n.id
         JOIN triangle_count(karate)               AS t ON t.id = n.id
         JOIN louvain(karate, seed => 1)           AS l ON l.id = n.id
         ORDER BY degree DESC
         LIMIT 5;",
        define_karate()
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+----+---------+--------+-----------+-----------+
| id | club    | degree | triangles | community |
+----+---------+--------+-----------+-----------+
| 33 | Officer | 17     | 15        | 2         |
| 0  | Mr. Hi  | 16     | 18        | 0         |
| 32 | Officer | 12     | 13        | 2         |
| 2  | Mr. Hi  | 10     | 11        | 0         |
| 1  | Mr. Hi  | 9      | 12        | 0         |
+----+---------+--------+-----------+-----------+
"
    );
}

/// One `USING` join per algorithm works as written: the function's columns
/// are qualified by its name.
#[test]
fn an_algorithm_joins_using_id() {
    let sql = format!(
        "{}
         SELECT id, club, degree FROM karate.nodes
         JOIN degree(karate, direction => 'both') USING (id)
         ORDER BY degree DESC, id LIMIT 2;",
        define_karate()
    );
    assert_eq!(
        ok(ursa(&["--format", "csv", "-c", &sql])),
        "id,club,degree\n33,Officer,17\n0,Mr. Hi,16\n"
    );
}

#[test]
fn graph_function_errors_are_for_people() {
    let sql = format!("{} SELECT * FROM pagerank(karte)", define_karate());
    assert_eq!(
        err(ursa(&["-c", &sql])),
        "Error: graph 'karte' does not exist; did you mean 'karate'?\n"
    );
}

/// Getting Started, "Find out what is available", after "Define a graph"
/// (`ursa_functions()` is in `ursa_functions_lists_the_catalog`).
#[test]
fn find_out_what_is_available_matches_getting_started() {
    let sql = format!(
        "{}
         CREATE PROPERTY GRAPH karate_edges_only
           EDGE TABLES (ties SOURCE KEY (src) DESTINATION KEY (dst));",
        define_karate()
    );
    let out = ok(ursa(&[
        "-c",
        &sql,
        "-c",
        "SHOW GRAPHS; DESCRIBE GRAPH karate;",
    ]));
    assert_eq!(
        out,
        "\
+-------------------+------------+--------+-------------+--------------+------------+
| name              | edge_table | source | destination | vertex_table | vertex_key |
+-------------------+------------+--------+-------------+--------------+------------+
| karate            | ties       | src    | dst         | members      | id         |
| karate_edges_only | ties       | src    | dst         |              |            |
+-------------------+------------+--------+-------------+--------------+------------+
+------------+-------------+-----------+-------------+--------------+
| table_name | column_name | data_type | role        | origin       |
+------------+-------------+-----------+-------------+--------------+
| nodes      | id          | Int64     | node id     | members.id   |
| nodes      | club        | Utf8      |             | members.club |
| edges      | src         | Int64     | source      | ties.src     |
| edges      | dst         | Int64     | destination | ties.dst     |
+------------+-------------+-----------+-------------+--------------+
"
    );

    // As JSON, one object per row; NULLs are left out.
    let out = ok(ursa(&[
        "--format",
        "json",
        "-c",
        &sql,
        "-c",
        "SHOW GRAPHS; DESC GRAPH karate_edges_only",
    ]));
    assert_eq!(
        out,
        "\
[{\"name\":\"karate\",\"edge_table\":\"ties\",\"source\":\"src\",\"destination\":\"dst\",\"vertex_table\":\"members\",\"vertex_key\":\"id\"},\
{\"name\":\"karate_edges_only\",\"edge_table\":\"ties\",\"source\":\"src\",\"destination\":\"dst\"}]
[{\"table_name\":\"nodes\",\"column_name\":\"id\",\"data_type\":\"Int64\",\"role\":\"node id\",\"origin\":\"ties.src, ties.dst\"},\
{\"table_name\":\"edges\",\"column_name\":\"src\",\"data_type\":\"Int64\",\"role\":\"source\",\"origin\":\"ties.src\"},\
{\"table_name\":\"edges\",\"column_name\":\"dst\",\"data_type\":\"Int64\",\"role\":\"destination\",\"origin\":\"ties.dst\"}]
"
    );

    assert_eq!(
        err(ursa(&["-c", &sql, "-c", "DESCRIBE GRAPH karat"])),
        "Error: graph 'karat' does not exist; did you mean 'karate'?\n"
    );
}

/// A graph over bare file paths, with no views: the florentine families.
#[test]
fn a_graph_over_file_paths() {
    let data = "python/ursa/datasets/data";
    let sql = format!(
        "CREATE PROPERTY GRAPH florentine
           EDGE TABLES ('{data}/florentine_edges.csv' SOURCE KEY (src) DESTINATION KEY (dst));
         SHOW GRAPHS;
         SELECT id, degree FROM degree(florentine, direction => 'both')
         ORDER BY degree DESC, id LIMIT 3;
         SELECT count(*) AS families FROM florentine.nodes;"
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+------------+--------------------------------------------------+--------+-------------+--------------+------------+
| name       | edge_table                                       | source | destination | vertex_table | vertex_key |
+------------+--------------------------------------------------+--------+-------------+--------------+------------+
| florentine | 'python/ursa/datasets/data/florentine_edges.csv' | src    | dst         |              |            |
+------------+--------------------------------------------------+--------+-------------+--------------+------------+
+----------+--------+
| id       | degree |
+----------+--------+
| Medici   | 6      |
| Guadagni | 4      |
| Strozzi  | 4      |
+----------+--------+
+----------+
| families |
+----------+
| 15       |
+----------+
"
    );
}

#[test]
fn dropping_a_table_a_graph_uses_is_refused() {
    let sql = format!("{} DROP VIEW ties", define_karate());
    assert_eq!(
        err(ursa(&["-c", &sql])),
        "Error: cannot drop view 'ties': graph 'karate' uses it; drop property graph karate \
         first\n"
    );
    let sql = format!(
        "{} CREATE OR REPLACE VIEW members AS SELECT id AS member, club FROM members",
        define_karate()
    );
    let e = err(ursa(&["-c", &sql]));
    assert!(
        e.starts_with("Error: cannot replace view 'members': graph 'karate' uses it"),
        "{e}"
    );
    // After DROP PROPERTY GRAPH, the views can go, and SHOW TABLES works.
    let sql = format!(
        "{} DROP PROPERTY GRAPH karate; DROP VIEW ties; DROP VIEW members;
         SELECT count(*) AS n FROM information_schema.tables WHERE table_schema = 'public'",
        define_karate()
    );
    assert_eq!(ok(ursa(&["--format", "csv", "-c", &sql])), "n\n0\n");
}

/// Getting Started, "Combine algorithms and attributes", as written: one
/// `algorithms()` call, joined with `USING (id)`.
#[test]
fn combine_algorithms_and_attributes_with_algorithms() {
    let sql = format!(
        "{}
         SELECT id, club, degree, triangles, community
         FROM karate.nodes
         JOIN algorithms(karate,
                         degree(direction => 'both'),
                         triangles => triangle_count(),
                         community => louvain(seed => 1)) USING (id)
         ORDER BY degree DESC
         LIMIT 5;",
        define_karate()
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+----+---------+--------+-----------+-----------+
| id | club    | degree | triangles | community |
+----+---------+--------+-----------+-----------+
| 33 | Officer | 17     | 15        | 2         |
| 0  | Mr. Hi  | 16     | 18        | 0         |
| 32 | Officer | 12     | 13        | 2         |
| 2  | Mr. Hi  | 10     | 11        | 0         |
| 1  | Mr. Hi  | 9      | 12        | 0         |
+----+---------+--------+-----------+-----------+
"
    );
}

/// Les Misérables, as Getting Started names it, from the workspace root.
const LESMIS: &str =
    "CREATE VIEW lesmis_edges AS SELECT * FROM 'python/ursa/datasets/data/lesmis_edges.csv';
     CREATE PROPERTY GRAPH lesmis
       EDGE TABLES (lesmis_edges SOURCE KEY (src) DESTINATION KEY (dst));";

/// Getting Started, "Weights".
#[test]
fn weights_match_getting_started() {
    let sql = format!(
        "{LESMIS}
         SELECT * FROM pagerank(lesmis, weight => weight, direction => 'both')
         ORDER BY pagerank DESC
         LIMIT 5;"
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+----------+----------------------+
| id       | pagerank             |
+----------+----------------------+
| Valjean  | 0.09956068175644767  |
| Marius   | 0.051667656904091475 |
| Myriel   | 0.03923416880292588  |
| Cosette  | 0.03691018363299517  |
| Enjolras | 0.036614491459848165 |
+----------+----------------------+
"
    );
    // The page's second query returns all 77 characters, in six communities;
    // ordered and cut to five rows it prints a table short enough for the page.
    let sql =
        format!("{LESMIS} SELECT * FROM louvain(lesmis, weight => log(1 + weight), seed => 7);");
    let out = ok(ursa(&["--format", "csv", "-c", &sql]));
    assert_eq!(out.lines().count(), 78, "{out}");
    let communities: std::collections::BTreeSet<&str> = out
        .lines()
        .skip(1)
        .map(|l| l.rsplit(',').next().unwrap())
        .collect();
    assert_eq!(communities.len(), 6, "{out}");
    let sql = format!(
        "{LESMIS}
         SELECT * FROM louvain(lesmis, weight => log(1 + weight), seed => 7)
         ORDER BY id
         LIMIT 5;"
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+------------+---------+
| id         | louvain |
+------------+---------+
| Anzelma    | 3       |
| Babet      | 3       |
| Bahorel    | 5       |
| Bamatabois | 1       |
| BaronessT  | 4       |
+------------+---------+
"
    );
    assert_eq!(
        err(ursa(&[
            "-c",
            &format!("{LESMIS} SELECT * FROM pagerank(lesmis, weight => weight - 2)")
        ])),
        "Error: weight expression produced a negative value (-1); weights must be non-negative\n"
    );
}

/// Getting Started, "Subgraphs".
#[test]
fn subgraphs_match_getting_started() {
    let sql = format!(
        "{LESMIS}
         CREATE VIEW strong_ties AS SELECT * FROM lesmis_edges WHERE weight >= 3;

         CREATE PROPERTY GRAPH lesmis_strong
           EDGE TABLES (strong_ties SOURCE KEY (src) DESTINATION KEY (dst));

         SELECT count(DISTINCT connected_components) AS groups
         FROM connected_components(lesmis_strong);"
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+--------+
| groups |
+--------+
| 3      |
+--------+
"
    );
}

/// Getting Started, "Traversals": the three queries, in the shell's table
/// format.
#[test]
fn traversals_match_getting_started() {
    // "Member 0 has 16 friends, so this returns 16 rows."
    let sql = format!(
        "{}
         SELECT * FROM hop(karate, seeds => [0], n => 1, direction => 'both');",
        define_karate()
    );
    let out = ok(ursa(&["--format", "csv", "-c", &sql]));
    assert_eq!(out.lines().count(), 1 + 16, "{out}");
    assert_eq!(out.lines().next(), Some("src,dst"));
    assert!(out.lines().skip(1).all(|l| l.starts_with("0,")), "{out}");

    let sql = format!(
        "{}
         SELECT * FROM hop(karate,
                           seeds => (SELECT id FROM karate.nodes WHERE club = 'Officer'),
                           n => 2);",
        define_karate()
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+-----+-----+
| src | dst |
+-----+-----+
| 9   | 33  |
| 14  | 32  |
| 14  | 33  |
| 15  | 32  |
| 15  | 33  |
| 18  | 32  |
| 18  | 33  |
| 20  | 32  |
| 20  | 33  |
| 22  | 32  |
| 22  | 33  |
| 23  | 25  |
| 23  | 27  |
| 23  | 29  |
| 23  | 32  |
| 23  | 33  |
| 23  | 31  |
| 24  | 25  |
| 24  | 27  |
| 24  | 31  |
| 24  | 33  |
| 24  | 32  |
| 25  | 31  |
| 25  | 32  |
| 25  | 33  |
| 26  | 29  |
| 26  | 33  |
| 26  | 32  |
| 27  | 33  |
| 28  | 31  |
| 28  | 33  |
| 28  | 32  |
| 29  | 32  |
| 29  | 33  |
| 30  | 32  |
| 30  | 33  |
| 31  | 32  |
| 31  | 33  |
| 32  | 33  |
+-----+-----+
"
    );

    let sql = format!(
        "{}
         SELECT * FROM shortest_path(karate, source => 0, target => 33, direction => 'both');",
        define_karate()
    );
    assert_eq!(
        ok(ursa(&["-c", &sql])),
        "\
+-----+-----+-----+------+
| src | dst | hop | cost |
+-----+-----+-----+------+
| 0   | 8   | 0   | 1.0  |
| 8   | 33  | 1   | 2.0  |
+-----+-----+-----+------+
"
    );
    assert_eq!(
        err(ursa(&[
            "-c",
            &format!(
                "{} SELECT * FROM algorithms(karate, hop(seeds => [0]))",
                define_karate()
            )
        ])),
        "Error: algorithms(): hop() is a traversal, which returns rows of its own, not one per \
         node; call it on its own: SELECT * FROM hop(<graph>, seeds => [<id>, ...], n => 1, \
         direction => 'out')\n"
    );
}

/// Getting Started, "Find out what is available": `ursa_functions()`, which
/// an agent reads as JSON.
#[test]
fn ursa_functions_lists_the_catalog() {
    let out = ok(ursa(&[
        "--format",
        "json",
        "-c",
        "SELECT * FROM ursa_functions() WHERE name = 'pagerank'",
    ]));
    assert_eq!(
        out,
        "[{\"name\":\"pagerank\",\"family\":\"algorithm\",\
\"summary\":\"PageRank (pull-based fixpoint); a dangling node spreads its score to all nodes.\",\
\"networkx\":\"nx.pagerank(G, alpha=damping) (both: nx.pagerank(U))\",\
\"parameters\":[\
{\"name\":\"damping\",\"type\":\"number\",\"default\":\"0.85\",\"choices\":[],\
\"doc\":\"Probability of following an edge.\"},\
{\"name\":\"max_iter\",\"type\":\"integer\",\"default\":\"30\",\"choices\":[],\
\"doc\":\"Iteration cap.\"},\
{\"name\":\"tol\",\"type\":\"number\",\"default\":\"1e-6\",\"choices\":[],\
\"doc\":\"Convergence tolerance on the L1 change.\"},\
{\"name\":\"weight\",\"type\":\"expression\",\"default\":\"NULL\",\"choices\":[],\
\"doc\":\"A non-negative weight per edge; null is unweighted.\"},\
{\"name\":\"direction\",\"type\":\"string\",\"default\":\"'out'\",\"choices\":[\"out\",\"both\"],\
\"doc\":\"Follow the rows as stored, or read the graph as undirected.\"}],\
\"directions\":[\"out\",\"both\"],\
\"outputs\":[{\"name\":\"pagerank\",\"type\":\"Float64\",\"nullable\":false}]}]\n"
    );
    let out = ok(ursa(&[
        "--format",
        "csv",
        "-c",
        "SELECT name, family, cardinality(parameters) AS parameters, \
         array_to_string(directions, ' ') AS directions FROM ursa_functions()",
    ]));
    assert_eq!(
        out,
        "\
name,family,parameters,directions
degree,algorithm,1,out in both
pagerank,algorithm,5,out both
connected_components,algorithm,1,
triangle_count,algorithm,0,
clustering_coefficient,algorithm,0,
betweenness,algorithm,4,out both
closeness,algorithm,2,out in both
label_propagation,algorithm,2,
louvain,algorithm,3,
neighbors_agg,aggregation,4,out in both
density,statistic,1,out in both
avg_path_length,statistic,2,out in both
diameter,statistic,2,out in both
describe,statistic,3,out in both
hop,traversal,3,out in both
shortest_path,traversal,4,out in both
random_walk,traversal,4,
algorithms,combinator,0,
"
    );
    assert_eq!(
        err(ursa(&["-c", "SELECT * FROM ursa_functions('pagerank')"])),
        "Error: ursa_functions() takes no arguments: SELECT * FROM ursa_functions()\n"
    );
}

/// `-f` files and stdin take dot-commands, as `-init` and `.read` do (and as
/// DuckDB's do).
#[test]
fn scripts_take_dot_commands() {
    let dir = tempfile::tempdir().unwrap();
    let inner = dir.path().join("inner.sql");
    std::fs::write(&inner, "SELECT 2 AS b;\n").unwrap();
    let script = dir.path().join("q.sql");
    std::fs::write(
        &script,
        format!(
            ".timer on\n.mode csv\nSELECT 1 AS a;\n.read {}\n",
            inner.display()
        ),
    )
    .unwrap();
    let out = ok(ursa(&["-f", &script.display().to_string()]));
    let lines: Vec<&str> = out.lines().collect();
    assert_eq!(lines.len(), 6, "{out}");
    assert_eq!(&lines[..2], ["a", "1"]);
    assert!(lines[2].starts_with("Run Time: "), "{out}");
    assert_eq!(&lines[3..5], ["b", "2"]);
    assert!(lines[5].starts_with("Run Time: "), "{out}");

    // On stdin too.
    let out = ok(ursa_with_stdin(&[], ".mode json\nSELECT 1 AS a;\n"));
    assert_eq!(out, "[{\"a\":1}]\n");
    let out = ok(ursa_with_stdin(&[], ".help\n"));
    assert!(out.contains(".functions [NAME]"), "{out}");
    // And in -c.
    let out = ok(ursa(&["-c", ".mode csv", "-c", "SELECT 3 AS c"]));
    assert_eq!(out, "c\n3\n");
}

/// `.quit` and `.exit` end a script, and the run, without error.
#[test]
fn quit_ends_a_script() {
    let out = ok(ursa_with_stdin(
        &["--format", "csv"],
        "SELECT 1 AS a;\n.exit\nSELECT 2 AS b;\n",
    ));
    assert_eq!(out, "a\n1\n");
    let out = ok(ursa(&[
        "--format",
        "csv",
        "-c",
        ".quit",
        "-c",
        "SELECT 2 AS b",
    ]));
    assert_eq!(out, "");
}

/// A script stops at its first error, which names the script's line; a
/// syntax error anywhere in a file or -c runs none of it.
#[test]
fn a_script_stops_at_its_first_error() {
    let out = ursa_with_stdin(
        &["--format", "csv"],
        "SELECT 1 AS a;\nSELECT * FROM nowhere;\nSELECT 2 AS b;\n",
    );
    assert!(!out.status.success());
    assert_eq!(String::from_utf8(out.stdout).unwrap(), "a\n1\n");
    let message = String::from_utf8(out.stderr).unwrap();
    assert!(message.contains("nowhere"), "{message}");

    let out = ursa_with_stdin(
        &["--format", "csv"],
        ".mode json\nSELECT 1 AS a;\n\nSELECT 2\n  FROM t WHERE;\n",
    );
    assert!(!out.status.success());
    assert!(out.stdout.is_empty());
    let message = String::from_utf8(out.stderr).unwrap();
    assert!(
        message.starts_with("Error: syntax error: ") && message.contains("at Line: 5, Column: "),
        "{message}"
    );

    // An unknown dot-command is an error too.
    let e = err(ursa(&["-c", ".tabels", "-c", "SELECT 1"]));
    assert!(e.contains("did you mean '.tables'?"), "{e}");
}

/// With --format arrow, the output is one Arrow stream: the timer and other
/// dot-command text go to stderr.
#[test]
fn arrow_scripts_keep_the_stream_clean() {
    let out = ursa(&[
        "--format",
        "arrow",
        "-c",
        ".timer on",
        "-c",
        "SELECT 1 AS a",
    ]);
    assert!(out.status.success());
    assert!(out.stdout.starts_with(&[0xff, 0xff, 0xff, 0xff]));
    let stderr = String::from_utf8(out.stderr).unwrap();
    assert!(stderr.starts_with("Run Time: "), "{stderr}");
    let e = err(ursa(&[
        "--format",
        "arrow",
        "-c",
        "SELECT 1 AS a",
        "-c",
        "SELECT 2 AS b",
    ]));
    assert!(e.contains("--format arrow writes a single result"), "{e}");
}

/// Never silent: a statement that returns rows prints a result, with its
/// header even when there are none; a statement that returns no columns
/// (DDL, SET) prints nothing, as in DuckDB; anything else fails with a
/// message. (NDJSON has no header, so it prints nothing for no rows.)
#[test]
fn every_statement_prints_a_result_or_nothing_by_rule() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("out.csv").display().to_string();
    let edges = karate_edges();
    let graph = "CREATE VIEW ties AS SELECT * FROM (VALUES (1, 2)) AS t(src, dst); \
                 CREATE PROPERTY GRAPH g EDGE TABLES (ties SOURCE KEY (src) DESTINATION KEY (dst))";
    // (setup, statement, the result's header, or None for no result)
    let cases: Vec<(&str, String, Option<&str>)> = vec![
        ("", "SELECT 1 AS x WHERE false".into(), Some("x")),
        ("", "FROM (SELECT 1 AS x) WHERE x > 1".into(), Some("x")),
        (
            "",
            format!("FROM '{edges}' WHERE src > 1000"),
            Some("src,dst"),
        ),
        (
            "",
            "WITH a AS (SELECT 1 AS x) SELECT * FROM a WHERE x = 2".into(),
            Some("x"),
        ),
        ("", "VALUES (1) EXCEPT VALUES (1)".into(), Some("column1")),
        (
            "",
            "SHOW GRAPHS".into(),
            Some("name,edge_table,source,destination"),
        ),
        (
            "",
            "SHOW datafusion.execution.batch_size".into(),
            Some("name,value"),
        ),
        (
            "",
            "SHOW ursa.index_storage_limit".into(),
            Some("name,value"),
        ),
        (
            "",
            "DESCRIBE SELECT 1 AS x".into(),
            Some("column_name,data_type"),
        ),
        (
            "",
            format!("COPY (SELECT 1 AS x WHERE false) TO '{target}'"),
            Some("count"),
        ),
        ("", "EXPLAIN SELECT 1".into(), Some("plan_type,plan")),
        (
            "",
            "SELECT name FROM ursa_functions() WHERE name = 'none'".into(),
            Some("name"),
        ),
        (
            graph,
            "SELECT * FROM GRAPH_TABLE (g MATCH (a)-[e]->(b) WHERE a.id > 100 \
             COLUMNS (a.id AS a))"
                .into(),
            Some("a"),
        ),
        (
            graph,
            "SELECT * FROM hop(g, seeds => [100])".into(),
            Some("src,dst"),
        ),
        (
            graph,
            "DESCRIBE GRAPH g".into(),
            Some("table_name,column_name"),
        ),
        // DDL and SET: nothing, as in DuckDB.
        ("", "CREATE VIEW v AS SELECT 1 AS x".into(), None),
        (
            "",
            "CREATE TABLE t AS SELECT 1 AS x WHERE false".into(),
            None,
        ),
        (
            "",
            "SET datafusion.execution.batch_size = 1024".into(),
            None,
        ),
        ("", graph.into(), None),
        (graph, "DROP PROPERTY GRAPH g".into(), None),
        (graph, "DROP VIEW IF EXISTS nothing".into(), None),
    ];
    for (setup, statement, header) in &cases {
        let mut args = vec!["--format", "csv"];
        if !setup.is_empty() {
            args.extend(["-c", setup]);
        }
        args.extend(["-c", statement]);
        let out = ursa(&args);
        assert!(
            out.status.success(),
            "{statement}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let stdout = String::from_utf8(out.stdout).unwrap();
        match header {
            Some(header) => assert!(
                stdout.starts_with(header) && stdout.ends_with('\n'),
                "{statement} printed:\n{stdout}"
            ),
            None => assert_eq!(stdout, "", "{statement}"),
        }
        // The table and JSON formats print something for a result too.
        if header.is_some() {
            for format in ["table", "json"] {
                let mut args = vec!["--format", format];
                if !setup.is_empty() {
                    args.extend(["-c", setup]);
                }
                args.extend(["-c", statement]);
                let stdout = ok(ursa(&args));
                assert!(!stdout.trim().is_empty(), "{statement} ({format})");
            }
        }
    }
    // What does not parse, or cannot run, fails with a message.
    for statement in ["SELEC 1", "SELECT * FROM nowhere", "SUMMARIZE ties"] {
        let e = err(ursa(&["-c", statement]));
        assert!(e.starts_with("Error: "), "{statement}: {e}");
    }
}

/// DuckDB statements Ursa does not have say what to write instead.
#[test]
fn duckdb_only_syntax_says_what_to_use() {
    let e = err(ursa(&["-c", "SUMMARIZE t"]));
    assert!(
        e.starts_with("Error: SUMMARIZE is not supported; use DESCRIBE t"),
        "{e}"
    );
    let e = err(ursa(&["-c", "SELECT * FROM t USING SAMPLE 10"]));
    assert!(
        e.starts_with("Error: USING SAMPLE is not supported; use ORDER BY random() LIMIT n"),
        "{e}"
    );
}

/// `--skill` prints the agent skill, the copy in the crate of
/// skills/ursa-sql/SKILL.md. The crate is published on its own, so it
/// carries a copy; this test keeps the copy current.
#[test]
fn skill_prints_the_agent_skill() {
    let skill = std::fs::read_to_string(workspace().join("skills/ursa-sql/SKILL.md")).unwrap();
    let copy = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ursa-sql-skill.md");
    assert!(
        std::fs::read_to_string(&copy).unwrap() == skill,
        "{} is out of date: copy skills/ursa-sql/SKILL.md over it",
        copy.display()
    );
    assert_eq!(ok(ursa(&["--skill"])), skill);
}

/// `--help` ends with where to go next: the docs, a graph, the function
/// catalog, JSON for programs and the skill.
#[test]
fn help_points_onward() {
    let help = ok(ursa(&["--help"]));
    for needle in [
        "https://cldixon.github.io/ursa/sql/",
        "CREATE PROPERTY GRAPH g EDGE TABLES (ties SOURCE KEY (src) DESTINATION KEY (dst));",
        "SELECT * FROM ursa_functions()",
        "--format json",
        "ursa --skill",
    ] {
        assert!(help.contains(needle), "{needle} missing from:\n{help}");
    }
}