ursa-cli 0.6.0

The ursa command-line tool: SQL over Parquet and CSV 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
//! 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}"
    );
}

#[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 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 AS t SOURCE KEY (src) DESTINATION KEY (dst))",
    ]));
    assert!(
        e.starts_with("Error: table aliases (AS) are not supported yet"),
        "{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"
    );
}