prqlc 0.13.11

PRQL is a modern language for transforming data — a simple, powerful, pipelined SQL replacement.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
use std::env::current_dir;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;

use insta_cmd::assert_cmd_snapshot;
use insta_cmd::get_cargo_bin;
use tempfile::TempDir;
use walkdir::WalkDir;

#[cfg(not(windows))] // Windows has slightly different output (e.g. `prqlc.exe`), so we exclude.
#[test]
fn help() {
    assert_cmd_snapshot!(prqlc_command().arg("--help"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    Usage: prqlc [OPTIONS] [COMMAND]

    Commands:
      parse             Parse into PL AST
      lex               Lex into Lexer Representation
      fmt               Parse & generate PRQL code back
      collect           Parse the whole project and collect it into a single PRQL source file
      debug             Commands for meant for debugging, prone to change
      experimental      Experimental commands are prone to change
      compile           Parse, resolve, lower into RQ & compile to SQL
      watch             Watch a directory and compile .prql files to .sql files
      list-targets      Show available compile target names
      shell-completion  Print a shell completion for supported shells
      help              Print this message or the help of the given subcommand(s)

    Options:
          --color <WHEN>  Controls when to use color [default: auto] [possible values: auto, always,
                          never]
      -h, --help          Print help
      -V, --version       Print version

    ----- stderr -----
    ");

    // without arguments
    assert_cmd_snapshot!(prqlc_command(), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    Usage: prqlc [OPTIONS] [COMMAND]

    Commands:
      parse             Parse into PL AST
      lex               Lex into Lexer Representation
      fmt               Parse & generate PRQL code back
      collect           Parse the whole project and collect it into a single PRQL source file
      debug             Commands for meant for debugging, prone to change
      experimental      Experimental commands are prone to change
      compile           Parse, resolve, lower into RQ & compile to SQL
      watch             Watch a directory and compile .prql files to .sql files
      list-targets      Show available compile target names
      shell-completion  Print a shell completion for supported shells
      help              Print this message or the help of the given subcommand(s)

    Options:
          --color <WHEN>  Controls when to use color [default: auto] [possible values: auto, always,
                          never]
      -h, --help          Print help
      -V, --version       Print version

    ----- stderr -----
    ");
}

#[test]
fn get_targets() {
    assert_cmd_snapshot!(prqlc_command().arg("list-targets"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    sql.any
    sql.ansi
    sql.bigquery
    sql.clickhouse
    sql.duckdb
    sql.generic
    sql.glaredb
    sql.mssql
    sql.mysql
    sql.postgres
    sql.redshift
    sql.sqlite
    sql.snowflake

    ----- stderr -----
    ");
}

#[test]
fn compile() {
    assert_cmd_snapshot!(prqlc_command()
        .args(["compile", "--hide-signature-comment"])
        .pass_stdin("from tracks"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    SELECT
      *
    FROM
      tracks

    ----- stderr -----
    ");
}

#[cfg(not(windows))] // Windows has slightly different output (e.g. `prqlc.exe`), so we exclude.
#[test]
fn compile_help() {
    assert_cmd_snapshot!(prqlc_command().args(["compile", "--help"]), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    Parse, resolve, lower into RQ & compile to SQL

    Only displays the main pipeline and does not handle loop.

    Usage: prqlc compile [OPTIONS] [INPUT] [OUTPUT] [MAIN_PATH]

    Arguments:
      [INPUT]
              [default: -]

      [OUTPUT]
              [default: -]

      [MAIN_PATH]
              Identifier of the main pipeline

    Options:
          --hide-signature-comment
              Exclude the signature comment containing the PRQL version

          --no-format
              Emit unformatted, dense SQL

      -t, --target <TARGET>
              Target to compile to
              
              [env: PRQLC_TARGET=]
              [default: sql.any]

          --debug-log <DEBUG_LOG>
              File path into which to write the debug log to
              
              [env: PRQLC_DEBUG_LOG=]

          --color <WHEN>
              Controls when to use color
              
              [default: auto]
              [possible values: auto, always, never]

      -h, --help
              Print help (see a summary with '-h')

    ----- stderr -----
    ");
}

#[test]
fn long_query() {
    assert_cmd_snapshot!(prqlc_command()
        .args(["compile", "--hide-signature-comment", "--debug-log=log_test.html"])
        .pass_stdin(r#"
let long_query = (
  from employees
  filter gross_cost > 0
  group {title} (
      aggregate {
          ct = count this,
      }
  )
  sort ct
  filter ct > 200
  take 20
  sort ct
  filter ct > 200
  take 20
  sort ct
  filter ct > 200
  take 20
  sort ct
  filter ct > 200
  take 20
)
from long_query
  "#), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    WITH table_2 AS (
      SELECT
        title,
        COUNT(*) AS ct
      FROM
        employees
      WHERE
        gross_cost > 0
      GROUP BY
        title
      HAVING
        COUNT(*) > 200
      ORDER BY
        ct
      LIMIT
        20
    ), table_1 AS (
      SELECT
        title,
        ct
      FROM
        table_2
      WHERE
        ct > 200
      ORDER BY
        ct
      LIMIT
        20
    ), table_0 AS (
      SELECT
        title,
        ct
      FROM
        table_1
      WHERE
        ct > 200
      ORDER BY
        ct
      LIMIT
        20
    ), long_query AS (
      SELECT
        title,
        ct
      FROM
        table_0
      WHERE
        ct > 200
      ORDER BY
        ct
      LIMIT
        20
    )
    SELECT
      title,
      ct
    FROM
      long_query
    ORDER BY
      ct

    ----- stderr -----
    ");

    // don't check the contents, they are very prone to change
    assert!(PathBuf::from_str("./log_test.html").unwrap().is_file());
}

#[test]
fn compile_project() {
    let mut cmd = prqlc_command();
    cmd.args([
        "compile",
        "--hide-signature-comment",
        "--debug-log=log_test.json",
        project_path().to_str().unwrap(),
        "-",
        "main",
    ]);

    assert_cmd_snapshot!(cmd, @r"
    success: true
    exit_code: 0
    ----- stdout -----
    WITH table_1 AS (
      SELECT
        120 AS artist_id,
        DATE '2023-05-18' AS last_listen
      UNION
      ALL
      SELECT
        7 AS artist_id,
        DATE '2023-05-16' AS last_listen
    ),
    favorite_artists AS (
      SELECT
        artist_id,
        last_listen
      FROM
        table_1
    ),
    table_0 AS (
      SELECT
        *
      FROM
        read_parquet('artists.parquet')
    ),
    input AS (
      SELECT
        *
      FROM
        table_0
    )
    SELECT
      favorite_artists.artist_id,
      favorite_artists.last_listen,
      input.*
    FROM
      favorite_artists
      LEFT OUTER JOIN input ON favorite_artists.artist_id = input.artist_id

    ----- stderr -----
    ");

    // don't check the contents, they are very prone to change
    assert!(PathBuf::from_str("./log_test.json").unwrap().is_file());

    assert_cmd_snapshot!(prqlc_command()
      .args([
        "compile",
        "--hide-signature-comment",
        project_path().to_str().unwrap(),
        "-",
        "favorite_artists",
    ]), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    WITH table_0 AS (
      SELECT
        120 AS artist_id,
        DATE '2023-05-18' AS last_listen
      UNION
      ALL
      SELECT
        7 AS artist_id,
        DATE '2023-05-16' AS last_listen
    )
    SELECT
      artist_id,
      last_listen
    FROM
      table_0

    ----- stderr -----
    ");
}

#[test]
fn format() {
    // Test stdin formatting
    assert_cmd_snapshot!(prqlc_command().args(["fmt"]).pass_stdin("from tracks | take 20"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    from tracks
    take 20

    ----- stderr -----
    ");

    // Test formatting a path:

    // Create a temporary directory
    let temp_dir = TempDir::new().expect("Failed to create temp directory");

    // Copy files from project_path() to temp_dir
    copy_dir(&project_path(), temp_dir.path());

    // Run fmt command on the temp directory
    let _result = prqlc_command()
        .args(["fmt", temp_dir.path().to_str().unwrap()])
        .status()
        .unwrap();

    // Check if files in temp_dir match the original files
    compare_directories(&project_path(), temp_dir.path());
}

fn copy_dir(src: &Path, dst: &Path) {
    for entry in WalkDir::new(src) {
        let entry = entry.unwrap();
        let path = entry.path();
        if path.is_file() {
            let relative_path = path.strip_prefix(src).unwrap();
            let target_path = dst.join(relative_path);
            fs::create_dir_all(target_path.parent().unwrap()).unwrap();
            fs::copy(path, target_path).unwrap();
        }
    }
}

fn compare_directories(dir1: &Path, dir2: &Path) {
    for entry in WalkDir::new(dir1).into_iter().filter_map(|e| e.ok()) {
        let path1 = entry.path();
        if path1.is_file() {
            let relative_path = path1.strip_prefix(dir1).unwrap();
            let path2 = dir2.join(relative_path);

            assert!(
                path2.exists(),
                "File {relative_path:?} doesn't exist in the formatted directory"
            );

            similar_asserts::assert_eq!(
                fs::read_to_string(path1).unwrap(),
                fs::read_to_string(path2).unwrap()
            );
        }
    }
}

#[test]
fn debug() {
    assert_cmd_snapshot!(prqlc_command()
        .args(["debug", "lineage"])
        .pass_stdin("from tracks | select {artist, album}"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    frames:
    - - 1:14-36
      - columns:
        - !Single
          name:
          - tracks
          - artist
          target_id: 118
          target_name: null
        - !Single
          name:
          - tracks
          - album
          target_id: 119
          target_name: null
        inputs:
        - id: 116
          name: tracks
          table:
          - default_db
          - tracks
    nodes:
    - id: 116
      kind: Ident
      span: 1:0-11
      ident: !Ident
      - default_db
      - tracks
      parent: 121
    - id: 118
      kind: Ident
      span: 1:22-28
      ident: !Ident
      - this
      - tracks
      - artist
      targets:
      - 116
      parent: 120
    - id: 119
      kind: Ident
      span: 1:30-35
      ident: !Ident
      - this
      - tracks
      - album
      targets:
      - 116
      parent: 120
    - id: 120
      kind: Tuple
      span: 1:21-36
      children:
      - 118
      - 119
      parent: 121
    - id: 121
      kind: 'TransformCall: Select'
      span: 1:14-36
      children:
      - 116
      - 120
    ast:
      name: Project
      stmts:
      - VarDef:
          kind: Main
          name: main
          value:
            Pipeline:
              exprs:
              - FuncCall:
                  name:
                    Ident:
                    - from
                    span: 1:0-4
                  args:
                  - Ident:
                    - tracks
                    span: 1:5-11
                span: 1:0-11
              - FuncCall:
                  name:
                    Ident:
                    - select
                    span: 1:14-20
                  args:
                  - Tuple:
                    - Ident:
                      - artist
                      span: 1:22-28
                    - Ident:
                      - album
                      span: 1:30-35
                    span: 1:21-36
                span: 1:14-36
            span: 1:0-36
        span: 1:0-36

    ----- stderr -----
    ");

    // Don't test the output of this, since on one min-versions check it had
    // different results, and didn't repro on Mac. It having different results
    // makes it difficult to debug, and we get most of the value by just
    // checking it runs successfully.
    prqlc_command()
        .args(["debug", "ast"])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .unwrap();
}

// The output of `prqlc debug json-schema` is long, so rather than
// comparing the full output as a snapshot, we just verify that the
// standard output parses as JSON and check a couple top-level keys.
#[test]
fn debug_json_schema() {
    use serde_json::Value;

    let output = prqlc_command()
        .args(["debug", "json-schema", "--ir-type", "pl"])
        .output()
        .unwrap();

    assert!(output.status.success());

    let stdout = std::str::from_utf8(&output.stdout).unwrap();
    let parsed: Value = serde_json::from_str(stdout).unwrap();

    assert_eq!(
        parsed["$schema"],
        "https://json-schema.org/draft/2020-12/schema"
    );
    assert_eq!(parsed["type"], "object");
    assert_eq!(parsed["title"], "ModuleDef");
}

#[test]
fn shell_completion() {
    for shell in ["bash", "fish", "powershell", "zsh"].iter() {
        assert_cmd_snapshot!(prqlc_command().args(["shell-completion", shell]));
    }
}

fn project_path() -> PathBuf {
    current_dir()
        .unwrap()
        // We canonicalize so that it doesn't matter where the cwd is.
        .canonicalize()
        .unwrap()
        .join("tests/integration/project")
}

fn prqlc_command() -> Command {
    let mut cmd = Command::new(get_cargo_bin("prqlc"));
    normalize_prqlc(&mut cmd);
    cmd
}

fn normalize_prqlc(cmd: &mut Command) -> &mut Command {
    cmd
        // We set `CLICOLOR_FORCE` in CI to force color output, but we don't want `prqlc` to
        // output color for our snapshot tests. And it seems to override the
        // `--color=never` flag.
        .env_remove("CLICOLOR_FORCE")
        .env("NO_COLOR", "1")
        .args(["--color=never"])
        // We don't want the tests to be affected by the user's `RUST_BACKTRACE` setting.
        .env_remove("RUST_BACKTRACE")
        .env_remove("RUST_LOG")
}

#[test]
fn compile_no_prql_files() {
    assert_cmd_snapshot!(prqlc_command().args(["compile", "README.md"]), @r"
    success: false
    exit_code: 1
    ----- stdout -----

    ----- stderr -----
    Error: No `.prql` files found in the source tree
    ");
}

#[test]
fn lex() {
    assert_cmd_snapshot!(prqlc_command().args(["lex"]).pass_stdin("from tracks"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    - kind: Start
      span:
        start: 0
        end: 0
    - kind: !Ident from
      span:
        start: 0
        end: 4
    - kind: !Ident tracks
      span:
        start: 5
        end: 11

    ----- stderr -----
    ");

    assert_cmd_snapshot!(prqlc_command().args(["lex", "--format=json"]).pass_stdin("from tracks"), @r#"
    success: true
    exit_code: 0
    ----- stdout -----
    [
      {
        "kind": "Start",
        "span": {
          "start": 0,
          "end": 0
        }
      },
      {
        "kind": {
          "Ident": "from"
        },
        "span": {
          "start": 0,
          "end": 4
        }
      },
      {
        "kind": {
          "Ident": "tracks"
        },
        "span": {
          "start": 5,
          "end": 11
        }
      }
    ]
    ----- stderr -----
    "#);
}

#[cfg(feature = "lsp")]
#[test]
fn lsp() {
    let init = serde_json::to_string(&lsp_server::Message::Request(lsp_server::Request {
        method: "initialize".into(),
        id: lsp_server::RequestId::from(1),
        params: serde_json::json!({"capabilities": {}}),
    }))
    .unwrap();
    let initialized = serde_json::to_string(&lsp_server::Message::Notification(
        lsp_server::Notification {
            method: "initialized".into(),
            params: serde_json::json!({}),
        },
    ))
    .unwrap();
    let ex1 = serde_json::to_string(&lsp_server::Message::Notification(
        lsp_server::Notification {
            method: "exit".into(),
            params: serde_json::Value::Null,
        },
    ))
    .unwrap();

    assert_cmd_snapshot!(prqlc_command().args(["lsp"])
        .pass_stdin(format!("Content-Length: {}\r\n\r\n{}Content-Length: {}\r\n\r\n{}Content-Length: {}\r\n\r\n{}",
            init.len(), init,
            initialized.len(), initialized,
            ex1.len(), ex1))
        , @r###"
    success: true
    exit_code: 0
    ----- stdout -----
    Content-Length: 78

    {"jsonrpc":"2.0","id":1,"result":{"capabilities":{"definitionProvider":true}}}
    ----- stderr -----
    starting PRQL LSP server
    starting main loop
    got msg: Notification(Notification { method: "exit", params: Null })
    got notification: Notification { method: "exit", params: Null }
    shutting down server
    "###);
}