ursa-cli 0.10.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
//! `ursa club.ursa`: a database file kept between processes.

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

/// A temporary directory holding copies of the karate CSVs.
fn karate_dir() -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    let data = Path::new(env!("CARGO_MANIFEST_DIR")).join("../python/ursa/datasets/data");
    for file in ["karate_edges.csv", "karate_nodes.csv"] {
        std::fs::copy(data.join(file), dir.path().join(file)).unwrap();
    }
    dir
}

/// Run `ursa` in `cwd` with no stdin.
fn ursa_in(cwd: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_ursa"))
        .args(args)
        .current_dir(cwd)
        .stdin(Stdio::null())
        .output()
        .expect("ursa runs")
}

/// A directory other than the database's, so relative paths are tested.
fn elsewhere() -> PathBuf {
    std::env::temp_dir()
}

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

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()
}

const DEFINE: &str = "CREATE VIEW members AS SELECT * FROM 'karate_nodes.csv';
CREATE VIEW ties    AS SELECT * FROM '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)
  );";

const QUERY: &str =
    "SELECT id, degree FROM degree(karate, direction => 'both') ORDER BY degree DESC, id LIMIT 5;
SELECT * FROM karate.nodes ORDER BY id LIMIT 3";

const EXPECTED: &str = "\
┌───────┬────────┐
│  id   │ degree │
│ Int64 │ UInt32 │
├───────┼────────┤
│    33 │     17 │
│     0 │     16 │
│    32 │     12 │
│     2 │     10 │
│     1 │      9 │
└───────┴────────┘
┌───────┬────────┐
│  id   │  club  │
│ Int64 │  Utf8  │
├───────┼────────┤
│     0 │ Mr. Hi │
│     1 │ Mr. Hi │
│     2 │ Mr. Hi │
└───────┴────────┘
";

/// `DEFINE` with each `karate_…` file named by `prefix` (`../db/data/`).
fn define_from(prefix: &str) -> String {
    DEFINE.replace("'karate_", &format!("'{prefix}karate_"))
}

/// The statements of the catalog file at `path`.
fn catalog(path: &Path) -> Vec<String> {
    ursa_engine::database::Database::open(path, &ursa_engine::database::OpenOptions::read_only())
        .unwrap()
        .statements()
}

/// A layout with three directories: `db/` holds the database, `work/` is
/// where the first process runs, and the karate files are in `db/data/`
/// (inside the database's directory) or `data/` (outside it).
fn three_dirs(data_inside: bool) -> (tempfile::TempDir, PathBuf, PathBuf) {
    let parent = tempfile::tempdir().unwrap();
    let db = parent.path().join("db");
    let work = parent.path().join("work");
    std::fs::create_dir_all(&db).unwrap();
    std::fs::create_dir_all(&work).unwrap();
    let data = if data_inside {
        db.join("data")
    } else {
        parent.path().join("data")
    };
    std::fs::rename(karate_dir().keep(), &data).unwrap();
    (parent, db, work)
}

/// One process, run from a directory other than the database's, defines the
/// graph with relative paths into a third directory: they resolve against
/// its current directory. A second process, run from yet another directory,
/// queries it without defining anything.
#[test]
fn a_second_process_sees_what_the_first_defined() {
    let (parent, db_dir, work) = three_dirs(true);
    let define = define_from("../db/data/");
    assert_eq!(ok(ursa_in(&work, &["../db/club.ursa", "-c", &define])), "");
    // Stored relative to the database's directory.
    let stored = catalog(&db_dir.join("club.ursa"));
    assert_eq!(
        stored[..2],
        [
            "CREATE VIEW members AS SELECT * FROM 'data/karate_nodes.csv'",
            "CREATE VIEW ties AS SELECT * FROM 'data/karate_edges.csv'",
        ]
    );
    let db = db_dir.join("club.ursa");
    let db = db.to_str().unwrap();
    assert_eq!(ok(ursa_in(&elsewhere(), &[db, "-c", QUERY])), EXPECTED);
    assert_eq!(ok(ursa_in(parent.path(), &[db, "-c", QUERY])), EXPECTED);
    assert!(db_dir.join("club.ursa.d/lock").is_file());
}

/// A path outside the database's directory is stored absolute, and found
/// from anywhere.
#[test]
fn a_path_outside_the_database_directory_is_stored_absolute() {
    let (parent, db_dir, work) = three_dirs(false);
    let define = define_from("../data/");
    ok(ursa_in(&work, &["../db/club.ursa", "-c", &define]));
    let data = std::fs::canonicalize(parent.path().join("data")).unwrap();
    let stored = catalog(&db_dir.join("club.ursa"));
    assert_eq!(
        stored[0],
        format!(
            "CREATE VIEW members AS SELECT * FROM '{}'",
            data.join("karate_nodes.csv").display()
        )
    );
    let db = db_dir.join("club.ursa");
    assert_eq!(
        ok(ursa_in(&elsewhere(), &[db.to_str().unwrap(), "-c", QUERY])),
        EXPECTED
    );
}

/// A database moved with its data keeps working.
#[test]
fn a_database_moves_with_its_files() {
    let (parent, db_dir, work) = three_dirs(true);
    ok(ursa_in(
        &work,
        &["../db/club.ursa", "-c", &define_from("../db/data/")],
    ));
    let moved = parent.path().join("moved");
    std::fs::rename(&db_dir, &moved).unwrap();
    let db = moved.join("club.ursa");
    assert_eq!(
        ok(ursa_in(&elsewhere(), &[db.to_str().unwrap(), "-c", QUERY])),
        EXPECTED
    );
    assert_eq!(ok(ursa_in(&moved, &["club.ursa", "-c", QUERY])), EXPECTED);
}

/// In a session with a database, a query's relative path and a `COPY`
/// target resolve against the current directory, not the database's.
#[test]
fn queries_and_copy_resolve_against_the_current_directory() {
    let (parent, db_dir, work) = three_dirs(true);
    let db = db_dir.join("club.ursa");
    let db = db.to_str().unwrap();
    let out = ok(ursa_in(
        &work,
        &[
            db,
            "--format",
            "csv",
            "-c",
            "SELECT count(*) AS n FROM '../db/data/karate_edges.csv'; \
             COPY (SELECT 1 AS x) TO 'out.csv'",
        ],
    ));
    assert_eq!(out, "n\n78\ncount\n1\n");
    assert!(work.join("out.csv").is_file());
    assert!(!db_dir.join("out.csv").exists());
    // A path relative to the database's directory is not found from
    // elsewhere.
    let e = err(ursa_in(
        parent.path(),
        &[db, "-c", "SELECT count(*) FROM 'data/karate_edges.csv'"],
    ));
    assert!(
        e.contains("no file found at 'data/karate_edges.csv'"),
        "{e}"
    );
    // An external table's LOCATION too; it is stored relative to the
    // database, as written otherwise (its columns and options).
    ok(ursa_in(
        &work,
        &[
            db,
            "-c",
            "CREATE EXTERNAL TABLE edges (src BIGINT, dst BIGINT) STORED AS CSV \
             LOCATION '../db/data/karate_edges.csv' OPTIONS ('format.has_header' 'true')",
        ],
    ));
    assert_eq!(
        catalog(&db_dir.join("club.ursa")),
        [
            "CREATE EXTERNAL TABLE edges (src BIGINT, dst BIGINT) STORED AS CSV \
          LOCATION 'data/karate_edges.csv' OPTIONS ('format.has_header' 'true')"
        ]
    );
    let out = ok(ursa_in(
        &elsewhere(),
        &[
            db,
            "--format",
            "csv",
            "-c",
            "SELECT count(*) AS n FROM edges",
        ],
    ));
    assert_eq!(out, "n\n78\n");
}

/// A graph over bare file paths, defined from another directory.
#[test]
fn a_graph_over_file_paths_defined_from_another_directory() {
    let (_parent, db_dir, work) = three_dirs(true);
    let create = "CREATE PROPERTY GRAPH k VERTEX TABLES ('../db/data/karate_nodes.csv' KEY (id)) \
                  EDGE TABLES ('../db/data/karate_edges.csv' SOURCE KEY (src) \
                  REFERENCES '../db/data/karate_nodes.csv' (id) DESTINATION KEY (dst))";
    ok(ursa_in(&work, &["../db/club.ursa", "-c", create]));
    assert_eq!(
        catalog(&db_dir.join("club.ursa")),
        [create.replace("../db/data/", "data/")]
    );
    let db = db_dir.join("club.ursa");
    let out = ok(ursa_in(
        &elsewhere(),
        &[
            db.to_str().unwrap(),
            "--format",
            "csv",
            "-c",
            "SELECT sum(degree) AS s FROM degree(k)",
        ],
    ));
    assert_eq!(out, "s\n78\n");
}

#[test]
fn readonly_refuses_ddl() {
    let dir = karate_dir();
    let db = dir.path().join("club.ursa");
    let db = db.to_str().unwrap();
    ok(ursa_in(dir.path(), &[db, "-c", DEFINE]));
    let before = std::fs::read(dir.path().join("club.ursa")).unwrap();

    let out = ok(ursa_in(
        dir.path(),
        &[
            "--readonly",
            db,
            "--format",
            "csv",
            "-c",
            "SELECT count(*) AS n FROM karate.edges",
        ],
    ));
    assert_eq!(out, "n\n78\n");
    let e = err(ursa_in(
        dir.path(),
        &[db, "--readonly", "-c", "DROP PROPERTY GRAPH karate"],
    ));
    assert_eq!(
        e,
        format!(
            "Error: {db} is open read-only (--readonly), so DROP PROPERTY GRAPH cannot change it\n"
        )
    );
    assert_eq!(std::fs::read(dir.path().join("club.ursa")).unwrap(), before);

    let e = err(ursa_in(
        dir.path(),
        &["--readonly", "new.ursa", "-c", "SELECT 1"],
    ));
    assert_eq!(
        e,
        "Error: cannot open 'new.ursa' read-only: the file does not exist\n"
    );
    assert!(!dir.path().join("new.ursa").exists());
}

#[test]
fn tables_with_data_are_refused() {
    let dir = karate_dir();
    let e = err(ursa_in(
        dir.path(),
        &["club.ursa", "-c", "CREATE TABLE t AS SELECT 1 AS x"],
    ));
    assert!(
        e.starts_with("Error: CREATE TABLE … AS is not supported in a database file"),
        "{e}"
    );
    assert!(e.contains("COPY (SELECT …) TO 't.parquet'"), "{e}");
    // In memory they work.
    let out = ok(ursa_in(
        dir.path(),
        &[
            "--format",
            "csv",
            "-c",
            "CREATE TABLE t AS SELECT 1 AS x; INSERT INTO t VALUES (2); SELECT sum(x) AS s FROM t",
        ],
    ));
    assert_eq!(out, "count\n1\ns\n3\n");
}

/// A second writer waits briefly, then fails.
#[test]
fn a_database_in_use_is_refused() {
    let dir = karate_dir();
    let path = dir.path().join("club.ursa");
    let held = ursa_engine::database::Database::open(&path, &Default::default()).unwrap();
    let e = err(ursa_in(dir.path(), &["club.ursa", "-c", "SELECT 1"]));
    assert_eq!(
        e,
        format!(
            "Error: club.ursa is in use by another process (process {}), which has it open \
             for writing; open it read-only to query it meanwhile (ursa --readonly club.ursa), \
             or wait for that process to finish\n",
            std::process::id()
        )
    );
    // A reader is not blocked.
    ok(ursa_in(
        dir.path(),
        &["club.ursa", "--readonly", "-c", "SELECT 1"],
    ));
    drop(held);
    ok(ursa_in(dir.path(), &["club.ursa", "-c", "SELECT 1"]));
}

#[test]
fn attach_opens_a_database() {
    let dir = karate_dir();
    ok(ursa_in(dir.path(), &["club.ursa", "-c", DEFINE]));
    let out = ok(ursa_in(
        &elsewhere(),
        &[
            "--format",
            "csv",
            "-c",
            &format!(
                "ATTACH '{}'; SELECT count(*) AS n FROM karate.nodes",
                dir.path().join("club.ursa").display()
            ),
        ],
    ));
    assert_eq!(out, "n\n34\n");
}

/// Getting Started, "Open a database" and "Define a graph", each statement
/// in its own process, then later sections against the same file.
#[test]
fn open_a_database_matches_getting_started() {
    let dir = karate_dir();
    let cwd = dir.path();
    // `ursa club.ursa` creates the file (with stdin not a terminal, it starts no shell).
    let out = ursa_in(cwd, &["club.ursa"]);
    assert!(out.status.success());
    assert!(cwd.join("club.ursa").is_file());

    for sql in [
        "CREATE VIEW members AS SELECT * FROM 'karate_nodes.csv';
         CREATE VIEW ties    AS SELECT * FROM '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));",
    ] {
        assert_eq!(ok(ursa_in(cwd, &["club.ursa", "-c", sql])), "");
    }
    // Getting Started omits the ORDER BY; row order is not guaranteed.
    assert_eq!(
        ok(ursa_in(
            cwd,
            &[
                "club.ursa",
                "-c",
                "SELECT * FROM karate.nodes ORDER BY id LIMIT 3;"
            ]
        )),
        "\
┌───────┬────────┐
│  id   │  club  │
│ Int64 │  Utf8  │
├───────┼────────┤
│     0 │ Mr. Hi │
│     1 │ Mr. Hi │
│     2 │ Mr. Hi │
└───────┴────────┘
"
    );
    assert_eq!(
        ok(ursa_in(
            cwd,
            &[
                "club.ursa",
                "--format",
                "csv",
                "-c",
                "SELECT count(*) AS n FROM karate_edges_only.nodes"
            ]
        )),
        "n\n34\n"
    );
    assert_eq!(
        ok(ursa_in(
            cwd,
            &[
                "club.ursa",
                "-c",
                "SELECT id, round(pagerank, 4) AS pagerank
                 FROM pagerank(karate, direction => 'both')
                 ORDER BY pagerank DESC
                 LIMIT 5;"
            ]
        )),
        "\
┌───────┬──────────┐
│  id   │ pagerank │
│ Int64 │ Float64  │
├───────┼──────────┤
│    33 │   0.1009 │
│     0 │    0.097 │
│    32 │   0.0717 │
│     2 │   0.0571 │
│     1 │   0.0529 │
└───────┴──────────┘
"
    );
    let catalog = std::fs::read_to_string(cwd.join("club.ursa")).unwrap();
    assert!(catalog.contains("\"version\": 1"), "{catalog}");
    assert_eq!(catalog.matches("CREATE ").count(), 4, "{catalog}");
}

/// Run `ursa` in `cwd` asking for its index counts; its stdout, and
/// `(built, loaded)`.
fn ursa_counting(cwd: &Path, args: &[&str]) -> (String, (u64, u64)) {
    let output = Command::new(env!("CARGO_BIN_EXE_ursa"))
        .args(args)
        .current_dir(cwd)
        .env("URSA_INDEX_STATS", "1")
        .stdin(Stdio::null())
        .output()
        .expect("ursa runs");
    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
    let stdout = ok(output);
    let line = stderr
        .lines()
        .find_map(|l| l.strip_prefix("ursa: graph indexes built "))
        .unwrap_or_else(|| panic!("no index counts in: {stderr}"));
    let (built, loaded) = line.split_once(", loaded ").unwrap();
    (stdout, (built.parse().unwrap(), loaded.parse().unwrap()))
}

/// Getting Started, "Combine algorithms and attributes", in a `.ursa`
/// session: the second process loads the index the first stored.
#[test]
fn combine_in_a_database_loads_the_stored_index_in_a_second_process() {
    let dir = karate_dir();
    let cwd = dir.path();
    assert_eq!(ok(ursa_in(cwd, &["club.ursa", "-c", DEFINE])), "");
    let combine = "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;";
    let expected = "\
┌───────┬─────────┬────────┬───────────┬───────────┐
│  id   │  club   │ degree │ triangles │ community │
│ Int64 │  Utf8   │ UInt32 │  UInt32   │  UInt32   │
├───────┼─────────┼────────┼───────────┼───────────┤
│    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 │
└───────┴─────────┴────────┴───────────┴───────────┘
";
    assert_eq!(
        ursa_counting(cwd, &["club.ursa", "-c", combine]),
        (expected.to_string(), (1, 0))
    );
    let indexes = cwd.join("club.ursa.d/indexes");
    assert!(indexes.join("manifest.json").is_file());
    assert_eq!(
        ursa_counting(cwd, &["club.ursa", "-c", combine]),
        (expected.to_string(), (0, 1))
    );
    // A read-only process loads it too.
    assert_eq!(
        ursa_counting(cwd, &["club.ursa", "--readonly", "-c", combine]),
        (expected.to_string(), (0, 1))
    );
    // Editing the edge file makes the next process rebuild.
    let edges = cwd.join("karate_edges.csv");
    let mut text = std::fs::read_to_string(&edges).unwrap();
    text.push_str("0,33\n");
    std::fs::write(&edges, text).unwrap();
    let (_, counts) = ursa_counting(cwd, &["club.ursa", "-c", combine]);
    assert_eq!(counts, (1, 0));
}

/// Write a Parquet edge list of `n` seeded pseudo-random edges.
fn write_parquet_edges(path: &Path, n: usize) {
    use std::sync::Arc;

    use arrow::array::{Int64Array, RecordBatch};
    use arrow::datatypes::{DataType, Field, Schema};
    use datafusion::parquet::arrow::ArrowWriter;

    let schema = Arc::new(Schema::new(vec![
        Field::new("src", DataType::Int64, false),
        Field::new("dst", DataType::Int64, false),
    ]));
    let file = std::fs::File::create(path).unwrap();
    let mut writer = ArrowWriter::try_new(file, Arc::clone(&schema), None).unwrap();
    let nodes = (n / 6) as u64;
    let mut state: u64 = 0x2545_f491_4f6c_dd1d;
    let mut next = || {
        state = state
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        ((state >> 33) % nodes) as i64
    };
    let mut written = 0;
    while written < n {
        let len = (n - written).min(1 << 16);
        let src: Vec<i64> = (0..len).map(|_| next()).collect();
        let dst: Vec<i64> = (0..len).map(|_| next()).collect();
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            vec![
                Arc::new(Int64Array::from(src)),
                Arc::new(Int64Array::from(dst)),
            ],
        )
        .unwrap();
        writer.write(&batch).unwrap();
        written += len;
    }
    writer.close().unwrap();
}

/// Two `ursa club.ursa -c` processes over one Parquet edge list: the second
/// loads the index. Wall times are printed (run with `--nocapture`), not
/// asserted.
#[test]
fn a_second_process_over_parquet_loads_the_index() {
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    let n: usize = std::env::var("URSA_TEST_EDGES")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(400_000);
    write_parquet_edges(&cwd.join("edges.parquet"), n);
    assert_eq!(
        ok(ursa_in(
            cwd,
            &[
                "club.ursa",
                "-c",
                "CREATE VIEW ties AS SELECT * FROM 'edges.parquet';
                 CREATE PROPERTY GRAPH g EDGE TABLES (ties SOURCE KEY (src) DESTINATION KEY (dst));"
            ]
        )),
        ""
    );
    let query = "SELECT id, round(pagerank, 8) AS pagerank FROM pagerank(g)
                 ORDER BY pagerank DESC, id LIMIT 3";
    let args = ["club.ursa", "--format", "csv", "-c", query];
    let started = std::time::Instant::now();
    let (first, counts) = ursa_counting(cwd, &args);
    let first_time = started.elapsed();
    assert_eq!(counts, (1, 0));
    let started = std::time::Instant::now();
    let (second, counts) = ursa_counting(cwd, &args);
    let second_time = started.elapsed();
    assert_eq!(counts, (0, 1));
    assert_eq!(second, first);
    eprintln!("{n} edges, pagerank: first process {first_time:?}, second process {second_time:?}");
}

/// Notices go to stderr, one line each, and leave stdout as it was (#327).
#[test]
fn notices_go_to_stderr_and_leave_stdout_alone() {
    let dir = karate_dir();
    let cwd = dir.path();
    assert_eq!(ok(ursa_in(cwd, &["club.ursa", "-c", DEFINE])), "");
    let query = "SELECT count(*) AS n FROM degree(karate)";
    let csv = "--format=csv";
    let run = |args: &[&str]| {
        let out = ursa_in(cwd, args);
        let stderr = String::from_utf8(out.stderr.clone()).unwrap();
        (ok(out), stderr)
    };

    // A quick build that is stored says nothing at the default level.
    let (stdout, stderr) = run(&["club.ursa", csv, "-c", query]);
    assert_eq!((stdout.as_str(), stderr.as_str()), ("n\n34\n", ""));

    // Every load and build at 'all', on stderr only.
    let all = format!("SET ursa.notices = 'all'; {query}");
    let (stdout, stderr) = run(&["club.ursa", csv, "-c", &all]);
    assert_eq!(stdout, "n\n34\n");
    assert!(
        stderr.starts_with("ursa: loaded the index for karate (78 edges) from club.ursa ("),
        "{stderr}"
    );
    assert_eq!(stderr.lines().count(), 1, "{stderr}");

    // An index too large for the limit is not stored, and says how to keep it.
    let tiny = format!("SET ursa.index_storage_limit = '1KiB'; {query}; {query}");
    std::fs::remove_dir_all(cwd.join("club.ursa.d/indexes")).unwrap();
    let (stdout, stderr) = run(&["club.ursa", csv, "-c", &tiny]);
    assert_eq!(stdout, "n\n34\nn\n34\n");
    let lines: Vec<&str> = stderr.lines().collect();
    assert_eq!(lines.len(), 1, "once per build, not per query: {stderr}");
    assert!(
        lines[0].starts_with("ursa: built the index for karate (78 edges) in ")
            && lines[0].contains(
                "; not stored: it takes 2.7 KiB, more than ursa.index_storage_limit (1KiB); SET \
                 ursa.index_storage_limit = '1MiB' to keep it"
            ),
        "{stderr}"
    );

    // Read-only, at 'all': built, and not stored.
    let (stdout, stderr) = run(&["club.ursa", "--readonly", csv, "-c", &all]);
    assert_eq!(stdout, "n\n34\n");
    assert!(
        stderr.ends_with("; not stored: club.ursa is open read-only\n"),
        "{stderr}"
    );

    // --quiet says nothing; errors are still said.
    let (stdout, stderr) = run(&["club.ursa", "--quiet", csv, "-c", &all]);
    assert_eq!((stdout.as_str(), stderr.as_str()), ("n\n34\n", ""));
    let e = err(ursa_in(cwd, &["club.ursa", "-q", "-c", "SELECT nope"]));
    assert!(e.starts_with("Error: "), "{e}");
}

/// SET lasts for the process, as in DuckDB and Postgres (#353): nothing is
/// stored in the database; an -init file keeps a setting. A limit Ursa 0.8 or
/// 0.9 saved is said once, on stderr, and removed.
#[test]
fn set_lasts_for_the_process_and_a_saved_limit_is_said_once() {
    let dir = karate_dir();
    let cwd = dir.path();
    assert_eq!(ok(ursa_in(cwd, &["club.ursa", "-c", DEFINE])), "");
    let catalog = std::fs::read_to_string(cwd.join("club.ursa")).unwrap();
    let show = "SHOW ursa.index_storage_limit";
    let shown = |args: &[&str]| {
        let out = ursa_in(cwd, args);
        let stderr = String::from_utf8(out.stderr.clone()).unwrap();
        (ok(out), stderr)
    };

    let set = format!("SET ursa.index_storage_limit = '50MiB'; {show}");
    let (stdout, stderr) = shown(&["club.ursa", "--format=csv", "-c", &set]);
    assert_eq!(
        stdout,
        "name,value\nursa.index_storage_limit,50MiB (SET for this session)\n"
    );
    assert_eq!(stderr, "");
    assert_eq!(
        std::fs::read_to_string(cwd.join("club.ursa")).unwrap(),
        catalog
    );
    // The next process has the default, and says where it comes from.
    let (stdout, _) = shown(&["club.ursa", "--format=csv", "-c", show]);
    assert!(
        stdout.starts_with("name,value\nursa.index_storage_limit,\"")
            && stdout.contains("iB (the default: 25% of ")
            && stdout.contains(" free on the disk of club.ursa"),
        "{stdout}"
    );
    // An -init file keeps it.
    std::fs::write(
        cwd.join("init.sql"),
        "SET ursa.index_storage_limit = '50MiB';\n",
    )
    .unwrap();
    let (stdout, _) = shown(&["club.ursa", "-init", "init.sql", "--format=csv", "-c", show]);
    assert_eq!(
        stdout,
        "name,value\nursa.index_storage_limit,50MiB (SET for this session)\n"
    );

    // A limit 0.8 or 0.9 saved: not applied, said once, and removed.
    let saved = catalog.replacen(
        "\n}\n",
        ",\n  \"settings\": {\n    \"ursa.index_storage_limit\": \"50MiB\"\n  }\n}\n",
        1,
    );
    std::fs::write(cwd.join("club.ursa"), &saved).unwrap();
    let notice = "ursa: club.ursa has a saved ursa.index_storage_limit = 50MiB, which is no \
                  longer applied; SET now lasts for the session. To keep it, add SET \
                  ursa.index_storage_limit = '50MiB' to ~/.ursarc (or an -init file)\n";
    let (stdout, stderr) = shown(&["club.ursa", "--readonly", "--format=csv", "-c", show]);
    assert!(stdout.contains("(the default: "), "{stdout}");
    assert_eq!(stderr, notice);
    assert_eq!(
        std::fs::read_to_string(cwd.join("club.ursa")).unwrap(),
        saved
    );
    let (stdout, stderr) = shown(&["club.ursa", "--format=csv", "-c", show]);
    assert!(stdout.contains("(the default: "), "{stdout}");
    assert_eq!(stderr, notice);
    assert_eq!(
        std::fs::read_to_string(cwd.join("club.ursa")).unwrap(),
        catalog
    );
    let (_, stderr) = shown(&["club.ursa", "--format=csv", "-c", show]);
    assert_eq!(stderr, "");
}