uqa-cli 0.6.1

usql: interactive REPL for UQA
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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

use super::*;
use rustyline::history::MemHistory;

fn session() -> Session {
    Session::new_without_history(None, None).unwrap()
}
fn script(session: &mut Session, text: &str) -> (String, bool) {
    let mut output = Vec::new();
    let mut buffer = String::new();
    let mut failed = false;
    for line in text.lines() {
        failed |= session.process_line(line, &mut buffer, &mut output, false)
            == PromptLineOutcome::Failed;
    }
    if !buffer.trim().is_empty() {
        failed |= session.finish_input(&mut buffer, &mut output).is_err();
    }
    (String::from_utf8(output).unwrap(), failed)
}

#[test]
fn editor_context_preserves_literals_comments_and_real_catalog_names() {
    let session = session();
    session
        .engine
        .sql(
            "CREATE TABLE shell_probe(id int); CREATE TABLE \"user\"(id int); CREATE TABLE \"이름 표\"(\"열 이름\" int)",
            &[],
        )
        .unwrap();
    let mut helper = session.repl_helper().unwrap();
    let history = MemHistory::new();
    let context = Context::new(&history);
    for input in [
        "SELECT * FROM shell_pr",
        "SELECT * FROM public.shell_pr",
        "SELECT * FROM \"이름",
        "SELECT * FROM \"us",
    ] {
        let (_, matches) = helper.complete(input, input.len(), &context).unwrap();
        assert!(!matches.is_empty(), "{input}");
    }
    // Only a keyword outside every literal and comment is colored, and nothing is colored when `NO_COLOR` is set.
    let colors = std::env::var_os("NO_COLOR").is_none();
    for (buffer, line, keyword) in [
        ("", "SELECT 'SEL", true),
        ("", "-- SEL", false),
        ("SELECT $é$", "SELECT", false),
        ("/* nested /* comment", "SELECT", false),
    ] {
        helper.configure(buffer, true, &crate::variables::Variables::default());
        let (_, matches) = helper.complete(line, line.len(), &context).unwrap();
        assert!(matches.is_empty(), "{buffer}\n{line}");
        assert_eq!(
            helper
                .highlight(line, line.len())
                .contains("\x1b[1;34mSELECT"),
            keyword && colors,
            "{buffer}\n{line}"
        );
    }
}

#[test]
fn completion_displays_controls_without_changing_the_inserted_identifier() {
    let name = "\"unsafe\x1b[31mname\"";
    let helper = UsqlHelper::new(vec![name.into()], Vec::new(), Vec::new());
    let candidates = helper.completion_candidates("\"unsafe", true);
    assert_eq!(candidates.len(), 1);
    assert!(!candidates[0].display.contains('\x1b'));
    assert_eq!(candidates[0].replacement, name);
}

#[test]
fn qualified_column_completion_preserves_aliases_and_table_qualification() {
    let session = session();
    session
        .engine
        .sql("CREATE TABLE shell_probe(name text)", &[])
        .unwrap();
    let helper = session.repl_helper().unwrap();
    let history = MemHistory::new();
    let context = Context::new(&history);
    for prefix in [
        "SELECT t.",
        "SELECT shell_probe.",
        "SELECT public.shell_probe.",
        "SELECT \"table.alias\".",
    ] {
        let input = format!("{prefix}na");
        let (start, candidates) = helper.complete(&input, input.len(), &context).unwrap();
        assert_eq!(start, prefix.len(), "{input}");
        assert!(
            candidates
                .iter()
                .any(|candidate| candidate.replacement == "name"),
            "{input}"
        );
    }
    let input = "SELECT * FROM public.shell_pr";
    let (start, candidates) = helper.complete(input, input.len(), &context).unwrap();
    assert_eq!(&input[..start], "SELECT * FROM ");
    assert!(candidates
        .iter()
        .any(|candidate| candidate.replacement == "public.shell_probe"));
}

#[test]
fn completion_catalog_failure_preserves_the_interactive_helper_and_rollback() {
    let session = session();
    session.engine.sql("BEGIN", &[]).unwrap();
    let token = session.engine.cancellation_token();
    token.cancel();
    let mut output = Vec::new();
    let helper = session.interactive_helper(&mut output);
    assert!(String::from_utf8(output)
        .unwrap()
        .contains("completion catalog error:"));
    assert!(!helper.completion_candidates("ROLLBACK", false).is_empty());
    token.reset();
    session.engine.sql("ROLLBACK", &[]).unwrap();
    assert_eq!(
        session.engine.sql("SELECT 42", &[]).unwrap().value_at(0, 0),
        Some(&Value::Int(42))
    );
}

#[test]
fn filename_completion_inserts_psql_quotes_for_spaces_and_apostrophes() {
    let mut session = session();
    let directory = tempfile::tempdir().unwrap();
    let path = directory.path().join("script name's.sql");
    std::fs::write(&path, "SELECT 42 AS completed_file;\n").unwrap();
    let prefix = format!("\\i {}/scr", directory.path().display());
    let helper = session.repl_helper().unwrap();
    let history = MemHistory::new();
    let context = Context::new(&history);
    let (start, candidates) = helper.complete(&prefix, prefix.len(), &context).unwrap();
    assert_eq!(candidates.len(), 1);
    let completed = format!("{}{}", &prefix[..start], candidates[0].replacement);
    let (output, failed) = script(&mut session, &completed);
    assert!(!failed, "{completed}: {output}");
    assert!(output.contains("completed_file"), "{output}");
}

#[test]
fn timing_and_expanded_arguments_are_settings_not_toggles() {
    let mut session = session();
    let (output, failed) = script(
        &mut session,
        "\\timing off\n\\timing off\n\\x auto\n\\x off\n\\x off\n",
    );
    assert!(!failed, "{output}");
    assert!(!session.show_timing);
    assert_eq!(session.shell.printing.expanded, "off");
    assert_eq!(output.matches("Timing is off.").count(), 2);
    let (_, failed) = script(&mut session, "\\timing invalid\n\\x invalid\n");
    assert!(failed);
    assert!(!session.show_timing);
    assert_eq!(session.shell.printing.expanded, "off");
}

#[test]
fn query_buffer_variables_conditionals_and_gset_preserve_execution_order() {
    let mut session = session();
    let (output, failed) = script(
        &mut session,
        r"\set ON_ERROR_STOP on
\set n 41
SELECT :n+1 AS answer
\gset result_
\if :{?result_answer}
SELECT :'result_answer' AS value \g
\else
SELECT nonexistent FROM nonexistent;
\endif
SELECT 9
\r
SELECT 7 \gx
",
    );
    assert!(!failed, "{output}");
    assert_eq!(session.shell.variables.get("result_answer"), Some("42"));
    assert!(output.contains("42"));
    assert!(output.contains("RECORD 1"));
    assert!(!output.contains("nonexistent"));
}

#[test]
fn meta_variable_values_are_atomic_and_keep_their_requested_sql_quoting() {
    let mut session = session();
    let (output, failed) = script(
        &mut session,
        r#"\set value 'two words'
\set copied :value
\echo :copied
\echo :'value'
\echo :"value"
\echo 'it''s'
\echo 'it\'s'
CREATE TABLE "two words"(id int);
\dt :"value"
"#,
    );
    assert!(!failed, "{output}");
    assert_eq!(session.shell.variables.get("copied"), Some("two words"));
    assert!(output.starts_with("two words\n'two words'\n"), "{output}");
    assert!(output.contains("\"two words\"\nit's\nit's\n"), "{output}");
    assert!(output.contains("table_name"), "{output}");
}

#[test]
fn finished_statements_do_not_execute_the_incomplete_tail() {
    let mut session = session();
    let mut output = Vec::new();
    let mut buffer = String::new();
    assert_eq!(
        session.process_line(
            "CREATE TABLE saved(id int); INSERT INTO saved VALUES ('",
            &mut buffer,
            &mut output,
            false
        ),
        PromptLineOutcome::Continue
    );
    assert!(session.engine.describe_table("saved").unwrap().is_some());
    assert!(buffer.contains("INSERT INTO"));
    assert_eq!(
        session.process_line("1');", &mut buffer, &mut output, false),
        PromptLineOutcome::Continue
    );
    assert!(buffer.is_empty());
}

#[test]
fn query_failure_consumes_g_buffer_and_does_not_repeat_a_write() {
    let mut session = session();
    let (output,failed)=script(&mut session,"CREATE TABLE calls(id int PRIMARY KEY);\nINSERT INTO calls VALUES (1)\\; SELECT missing\n\\g\nSELECT COUNT(*) FROM calls;\n");
    assert!(failed, "{output}");
    let result = session
        .engine
        .sql("SELECT COUNT(*) FROM calls", &[])
        .unwrap();
    assert_eq!(result.value_at(0, 0), Some(&Value::Int(0)));
}

#[test]
fn formats_preserve_positional_columns_and_escape_terminal_controls() {
    let mut session = session();
    let (output, failed) = script(
        &mut session,
        "\\pset format csv\nSELECT 1 AS x, 2 AS x;\nSELECT '' AS empty, NULL AS null;\n",
    );
    assert!(!failed, "{output}");
    assert!(output.contains("x,x\n1,2\n"), "{output}");
    assert!(output.contains("empty,null\n,\n"), "{output}");
    let (output,failed)=script(&mut session,"\\pset format aligned\nSELECT '한글' AS v, 1 AS n UNION ALL SELECT 'a', 2;\nSELECT chr(27)||'[31mred' AS v;\n");
    assert!(!failed, "{output}");
    assert!(!output.contains('\x1b'));
    assert!(output.contains("한글 |"), "{output}");
    assert!(output.contains("a    |"), "{output}");
}

#[test]
fn expanded_footers_and_numeric_null_alignment_match_postgresql() {
    let mut session = session();
    let (output, failed) = script(&mut session, "\\x on\nSELECT 1;\nSELECT 1 WHERE false;\n");
    assert!(!failed, "{output}");
    assert!(output.contains("RECORD 1"), "{output}");
    assert!(!output.contains("(1 row)"), "{output}");
    assert!(output.contains("(0 rows)"), "{output}");
    let (output, failed) = script(
        &mut session,
        "\\x off\n\\pset null 'nil'\nSELECT 1.2::numeric AS price, NULL::numeric AS amount;\n",
    );
    assert!(!failed, "{output}");
    assert!(output.contains("   1.2 |    nil \n"), "{output}");
}

#[test]
fn file_copy_round_trip_and_failed_export_preserve_destination() {
    let mut session = session();
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("rows with spaces.csv");
    let (output,failed)=script(&mut session,&format!("CREATE TABLE copied(id int, body text);\nINSERT INTO copied VALUES (1, 'a,b'),(2,'한글');\n\\copy copied TO '{}' WITH (FORMAT CSV, HEADER)\nDELETE FROM copied;\n\\copy copied FROM '{}' WITH (FORMAT CSV, HEADER)\n",path.display(),path.display()));
    assert!(!failed, "{output}");
    let before = std::fs::read(&path).unwrap();
    let (_, failed) = script(
        &mut session,
        &format!(
            "\\copy (SELECT 1/0) TO '{}' WITH (FORMAT CSV)",
            path.display()
        ),
    );
    assert!(failed);
    assert_eq!(std::fs::read(&path).unwrap(), before);
    assert_eq!(
        session
            .engine
            .sql("SELECT COUNT(*) FROM copied", &[])
            .unwrap()
            .value_at(0, 0),
        Some(&Value::Int(2))
    );
}

#[test]
fn script_relative_includes_conditionals_and_cycle_detection() {
    let mut session = session();
    let dir = tempfile::tempdir().unwrap();
    let outer = dir.path().join("outer.sql");
    let inner = dir.path().join("inner.sql");
    std::fs::write(&inner, "\\set answer 42\n").unwrap();
    std::fs::write(&outer, "\\ir inner.sql\nSELECT :answer;\n").unwrap();
    let mut output = Vec::new();
    session.include_script(&outer, &mut output).unwrap();
    assert!(String::from_utf8(output).unwrap().contains("42"));
    std::fs::write(&inner, "\\ir outer.sql\n").unwrap();
    assert!(session.include_script(&outer, &mut Vec::new()).is_err());
    assert!(session.shell.includes.is_empty());
}

#[test]
fn catalog_patterns_and_role_alias_do_not_ignore_arguments() {
    let mut session = session();
    let (output,failed)=script(&mut session,"CREATE TABLE keep(id int PRIMARY KEY); CREATE TABLE other(id int);\n\\dt kee*\n\\dg\n\\di\n");
    assert!(!failed, "{output}");
    assert!(output.contains("keep"));
    assert!(!output.contains("other"));
    assert!(output.contains("rolname"));
    assert!(output.contains("keep_pkey"));
}

#[test]
fn catalog_name_patterns_preserve_non_ascii_identifiers() {
    let mut session = session();
    session.engine.sql(
        "CREATE TABLE \"꟎_case\"(id int); CREATE TABLE \"Ω_case\"(id int); CREATE TABLE ascii_case(id int)",
        &[],
    ).unwrap();
    // PostgreSQL 18.4 psql under UTF-8 preserves non-ASCII pattern characters.
    for (pattern, name) in [
        ("*.꟎_case", "꟎_case"),
        ("*.Ω_case", "Ω_case"),
        ("*.ASCII_CASE", "ascii_case"),
    ] {
        let (output, failed) = script(&mut session, &format!("\\dt {pattern}\n"));
        assert!(!failed, "{output}");
        assert!(output.contains(name), "pattern {pattern}: {output}");
        for other in ["꟎_case", "Ω_case", "ascii_case"] {
            if other != name {
                assert!(!output.contains(other), "pattern {pattern}: {output}");
            }
        }
    }
}

#[test]
fn autocommit_and_gset_preserve_multi_statement_transaction_boundaries() {
    let mut session = session();
    let (output,failed)=script(&mut session,"\\set AUTOCOMMIT off\nCREATE TABLE pending(id int);\nINSERT INTO pending VALUES (1);\nROLLBACK;\n");
    assert!(!failed, "{output}");
    assert!(session.engine.describe_table("pending").unwrap().is_none());
    let (output,failed)=script(&mut session,"\\set AUTOCOMMIT on\nCREATE TABLE atomic_write(id int);\nINSERT INTO atomic_write VALUES (1)\\; SELECT absent\n\\gset\n");
    assert!(failed, "{output}");
    assert_eq!(
        session
            .engine
            .sql("SELECT COUNT(*) FROM atomic_write", &[])
            .unwrap()
            .value_at(0, 0),
        Some(&Value::Int(0))
    );
}

#[test]
fn history_settings_control_duplicates_spaces_and_retained_length() {
    let mut session = session();
    session
        .shell
        .variables
        .set("HISTCONTROL", "none".into())
        .unwrap();
    session.remember_prompt_line("SELECT 1");
    session.remember_prompt_line("SELECT 1");
    assert_eq!(session.history.len(), 2);
    session
        .shell
        .variables
        .set("HISTCONTROL", "ignoreboth".into())
        .unwrap();
    assert!(!session.remember_prompt_line("SELECT 1"));
    assert!(!session.remember_prompt_line(" SELECT 2"));
    session.shell.variables.set("HISTSIZE", "1".into()).unwrap();
    session.remember_prompt_line("SELECT 3");
    assert_eq!(session.history, vec!["SELECT 3"]);
}

#[test]
fn no_idle_notification_polling_after_unlisten_or_rolled_back_listen() {
    let mut session = session();
    let mut out = Vec::new();
    session
        .run_statement_with_history("LISTEN updates", &mut out, false)
        .unwrap();
    assert!(session.shell.listen_seen);
    session
        .run_statement_with_history("UNLISTEN *", &mut out, false)
        .unwrap();
    assert!(!session.shell.listen_seen);
    session
        .run_statement_with_history("BEGIN", &mut out, false)
        .unwrap();
    session
        .run_statement_with_history("LISTEN updates", &mut out, false)
        .unwrap();
    session
        .run_statement_with_history("ROLLBACK", &mut out, false)
        .unwrap();
    assert!(!session.shell.listen_seen);
}

#[test]
fn postgres_csv_reference_preserves_boolean_array_null_and_duplicate_columns() {
    let mut session = session();
    session.shell.printing.format = "csv".into();
    let (output, failed) = script(
        &mut session,
        "SELECT true AS b, ARRAY[true,false] AS a, '' AS empty, NULL AS null, 1 AS x, 2 AS x;\n",
    );
    assert!(!failed, "{output}");
    // Captured independently from PostgreSQL 18.4 psql, with its default CSV and NULL settings.
    assert_eq!(output, "b,a,empty,null,x,x\nt,\"{t,f}\",,,1,2\n");
}

#[test]
fn finite_watch_executes_the_same_buffer_and_does_not_change_print_settings() {
    let mut session = session();
    let (output, failed) = script(&mut session, "SELECT 7 AS value\n\\watch 0.001 c=2\n");
    assert!(!failed, "{output}");
    assert_eq!(output.matches("(1 row)").count(), 2);
    assert_eq!(session.shell.printing.expanded, "off");
}