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
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Backslash command dispatch and catalog inspection commands.

use super::*;

impl Session {
    #[expect(
        clippy::too_many_lines,
        reason = "preserves meta-command output contracts"
    )]
    pub(super) fn handle_meta(&mut self, command: &str, out: &mut impl Write) -> PromptLineOutcome {
        let mut parts = command.trim().splitn(2, char::is_whitespace);
        let cmd = parts.next().unwrap_or("");
        let arg = parts.next().unwrap_or("").trim();
        let result = match cmd {
            "q" | "quit" | "exit" => return PromptLineOutcome::Quit,
            "?" | "help" => {
                print_backslash_help(out);
                Ok(())
            }
            "h" => crate::sql_help::print(arg, out),
            "history" => match arg {
                "" => {
                    for line in &self.history {
                        let _ = writeln!(out, "{}", crate::printing::message_text(line));
                    }
                    Ok(())
                }
                "clear" => {
                    let removal = self.history_path.as_ref().map_or(Ok(()), |path| {
                        std::fs::remove_file(path).or_else(|error| {
                            if error.kind() == io::ErrorKind::NotFound {
                                Ok(())
                            } else {
                                Err(error)
                            }
                        })
                    });
                    match removal {
                        Ok(()) => {
                            self.history.clear();
                            self.shell.clear_history = true;
                            let _ = writeln!(out, "history cleared");
                            Ok(())
                        }
                        Err(error) => Err(format!("history clear failed: {error}")),
                    }
                }
                other => Err(format!("usage: \\history [clear] (got {other:?})")),
            },
            "new" => {
                self.engine = Engine::new();
                if let Err(error) = crate::shell_notifications::configure(&self.engine) {
                    let _ = writeln!(out, "ERROR: {error}");
                    return PromptLineOutcome::Failed;
                }
                self.shell.listen_seen = false;
                self.db_path = None;
                self.db_key = None;
                self.location = ":memory:".into();
                let _ = writeln!(out, "fresh in-memory engine");
                Ok(())
            }
            "reset" => match open_engine(self.db_path.as_deref(), self.db_key.as_deref()) {
                Ok((engine, location, key)) => {
                    if let Err(error) = crate::shell_notifications::configure(&engine) {
                        let _ = writeln!(out, "ERROR: {error}");
                        return PromptLineOutcome::Failed;
                    }
                    self.shell.listen_seen = false;
                    self.engine = engine;
                    self.db_key = key;
                    self.location = location;
                    let _ = writeln!(out, "Engine reset.");
                    Ok(())
                }
                Err(err) => Err(format!("reset failed: {err}")),
            },
            "where" => {
                let _ = writeln!(out, "{}", crate::printing::terminal_text(&self.location));
                Ok(())
            }
            "stats" => self.cmd_show_stats(arg, out),
            "ds" => self.cmd_list_sequences(arg, out),
            "graphs" => self.cmd_list_graphs(out),
            "dfs" => self.cmd_list_foreign_servers(out),
            "dft" | "dF" => self.cmd_list_foreign_tables(out),
            "analyzers" => self
                .engine
                .list_named_analyzers()
                .map_err(|err| format!("Failed to read analyzers: {err}"))
                .map(|names| {
                    if names.is_empty() {
                        let _ = writeln!(out, "no analyzers registered");
                    } else {
                        for name in names {
                            let _ = writeln!(out, "  {name}");
                        }
                    }
                }),
            "migrate-python-db" => self.handle_migrate_python_db(arg, out),
            other => {
                print_backslash_help(out);
                Err(format!("unknown command: \\{other}"))
            }
        };
        match result {
            Ok(()) => PromptLineOutcome::Continue,
            Err(error) => {
                let _ = writeln!(out, "ERROR: {error}");
                PromptLineOutcome::Failed
            }
        }
    }

    pub(super) fn handle_output_redirect(
        &mut self,
        arg: &str,
        out: &mut impl Write,
    ) -> Result<(), String> {
        if arg.is_empty() {
            if let Some(path) = self.output_path.take() {
                let _ = writeln!(out, "Output restored to stdout (was: {}).", path.display());
            } else {
                let _ = writeln!(out, "Output already goes to stdout.");
            }
            return Ok(());
        }
        let path = PathBuf::from(arg);
        match OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&path)
        {
            Ok(_) => {
                self.output_path = Some(path);
                let _ = writeln!(out, "Output redirected to: {arg}");
                Ok(())
            }
            Err(error) => Err(format!("Output redirection failed for {arg}: {error}")),
        }
    }

    pub(super) fn cmd_describe_table(
        &self,
        name: &str,
        out: &mut impl Write,
    ) -> Result<(), String> {
        if name.is_empty() {
            return Err("Usage: \\d <table_name>".into());
        }
        match self.engine.describe_table(name) {
            Ok(Some(cols)) => {
                let _ = writeln!(out, "Table {}", crate::printing::terminal_text(name));
                print_columns(&cols, out);
                return Ok(());
            }
            Ok(None) => {}
            Err(err) => return Err(format!("Failed to describe table '{name}': {err}")),
        }
        match self.engine.foreign_table_definition(name) {
            Ok(Some(table)) => {
                let _ = writeln!(
                    out,
                    "Foreign table \"{}\" (server: {})",
                    crate::printing::terminal_text(name),
                    crate::printing::terminal_text(&table.server_name)
                );
                let rows = table
                    .columns
                    .iter()
                    .map(|col| {
                        result_row(vec![
                            ("column", Value::Str(col.name.clone())),
                            ("type", Value::Str(sql_type_name(&col.ty))),
                            ("constraints", Value::Str(String::new())),
                        ])
                    })
                    .collect();
                print_result(
                    &SQLResult::from_rows(
                        vec!["column".into(), "type".into(), "constraints".into()],
                        rows,
                    ),
                    out,
                );
                return Ok(());
            }
            Ok(None) => {}
            Err(err) => return Err(format!("Failed to read foreign table '{name}': {err}")),
        }
        Err(format!("Table '{name}' does not exist."))
    }

    pub(super) fn cmd_show_stats(&self, name: &str, out: &mut impl Write) -> Result<(), String> {
        if name.is_empty() {
            return Err("Usage: \\stats <table_name>".into());
        }
        match self.engine.describe_table(name) {
            Ok(Some(_)) => {}
            Ok(None) => return Err(format!("Table '{name}' does not exist.")),
            Err(err) => return Err(format!("Failed to describe table '{name}': {err}")),
        }
        let stats = self
            .engine
            .column_stats(name)
            .map_err(|err| format!("Failed to read statistics for '{name}': {err}"))?;
        if stats.is_empty() {
            let _ = writeln!(out, "No statistics for '{name}' (no declared columns).");
            return Ok(());
        }
        let row_count = stats.values().next().map_or(0, |s| s.row_count);
        let _ = writeln!(out, "Statistics for \"{name}\" ({row_count} rows)");
        let rows = stats
            .into_iter()
            .map(|(col, s)| {
                Ok(result_row(vec![
                    ("column", Value::Str(col)),
                    ("distinct", u64_count_value(s.distinct_count)),
                    ("nulls", u64_count_value(s.null_count)),
                    (
                        "min",
                        optional_value_to_display_value(s.min_value.as_ref())?,
                    ),
                    (
                        "max",
                        optional_value_to_display_value(s.max_value.as_ref())?,
                    ),
                    ("selectivity", Value::Float(s.equality_selectivity())),
                ]))
            })
            .collect::<Result<Vec<_>, String>>()?;
        print_result(
            &SQLResult::from_rows(
                vec![
                    "column".into(),
                    "distinct".into(),
                    "nulls".into(),
                    "min".into(),
                    "max".into(),
                    "selectivity".into(),
                ],
                rows,
            ),
            out,
        );
        Ok(())
    }

    pub(super) fn cmd_list_sequences(
        &self,
        name: &str,
        out: &mut impl Write,
    ) -> Result<(), String> {
        let rows: Vec<_> = if name.is_empty() {
            self.engine
                .try_sequences_snapshot()
                .map_err(|error| format!("Failed to read sequences: {error}"))?
                .into_iter()
                .map(sequence_row)
                .collect()
        } else {
            match self.engine.sequence_state(name) {
                Ok(Some((canonical, state))) => vec![sequence_row((canonical, state))],
                Ok(None) => return Err(format!("Sequence '{name}' does not exist.")),
                Err(error) => {
                    return Err(format!("Failed to read sequence '{name}': {error}"));
                }
            }
        };

        if rows.is_empty() {
            let _ = writeln!(out, "No sequences.");
            return Ok(());
        }
        print_result(
            &SQLResult::from_rows(
                vec![
                    "sequence_name".into(),
                    "start".into(),
                    "increment".into(),
                    "current".into(),
                ],
                rows,
            ),
            out,
        );
        Ok(())
    }

    pub(super) fn cmd_list_foreign_tables(&self, out: &mut impl Write) -> Result<(), String> {
        let names = self
            .engine
            .list_foreign_tables()
            .map_err(|err| format!("Failed to read foreign tables: {err}"))?;
        if names.is_empty() {
            let _ = writeln!(out, "No foreign tables.");
            return Ok(());
        }
        let mut rows = Vec::new();
        for name in names {
            match self.engine.foreign_table_definition(&name) {
                Ok(Some(table)) => {
                    let options = foreign_table_options_display(&table.options);
                    let source = table.options.get("source").cloned().unwrap_or_default();
                    rows.push(result_row(vec![
                        ("table_name", Value::Str(table.name)),
                        ("server", Value::Str(table.server_name)),
                        ("columns", usize_count_value(table.columns.len())),
                        ("source", Value::Str(source)),
                        ("options", Value::Str(options)),
                    ]));
                }
                Ok(None) => {
                    return Err(format!(
                        "foreign table '{name}' disappeared while listing its metadata"
                    ));
                }
                Err(err) => return Err(format!("Failed to read foreign table '{name}': {err}")),
            }
        }
        print_result(
            &SQLResult::from_rows(
                vec![
                    "table_name".into(),
                    "server".into(),
                    "columns".into(),
                    "source".into(),
                    "options".into(),
                ],
                rows,
            ),
            out,
        );
        Ok(())
    }

    pub(super) fn cmd_list_foreign_servers(&self, out: &mut impl Write) -> Result<(), String> {
        let names = self
            .engine
            .list_foreign_servers()
            .map_err(|err| format!("Failed to read foreign servers: {err}"))?;
        if names.is_empty() {
            let _ = writeln!(out, "No foreign servers.");
            return Ok(());
        }
        let mut rows = Vec::new();
        for name in names {
            match self.engine.foreign_server_definition(&name) {
                Ok(Some(server)) => rows.push(result_row(vec![
                    ("server_name", Value::Str(server.name)),
                    ("fdw_type", Value::Str(server.fdw_type)),
                    ("options", Value::Str(options_display(&server.options))),
                ])),
                Ok(None) => {
                    return Err(format!(
                        "foreign server '{name}' disappeared while listing its metadata"
                    ));
                }
                Err(err) => return Err(format!("Failed to read foreign server '{name}': {err}")),
            }
        }
        print_result(
            &SQLResult::from_rows(
                vec!["server_name".into(), "fdw_type".into(), "options".into()],
                rows,
            ),
            out,
        );
        Ok(())
    }

    pub(super) fn cmd_list_graphs(&self, out: &mut impl Write) -> Result<(), String> {
        let names = self
            .engine
            .list_graphs()
            .map_err(|err| format!("Failed to read graphs: {err}"))?;
        if names.is_empty() {
            let _ = writeln!(out, "No named graphs.");
            return Ok(());
        }
        let mut rows = Vec::new();
        for name in names {
            let counts = match self.engine.graph_with(&name, |store| {
                let vertices = store.vertex_ids_in_graph(&name)?.len();
                let edges = store.edges_in_graph(&name)?.len();
                Ok::<_, uqa_graph::GraphStoreError>((vertices, edges))
            }) {
                Ok(Some(Ok(counts))) => counts,
                Ok(Some(Err(err))) => {
                    return Err(format!("Failed to read graph '{name}': {err}"));
                }
                Ok(None) => {
                    return Err(format!(
                        "graph '{name}' disappeared while listing its metadata"
                    ));
                }
                Err(err) => return Err(format!("Failed to read graph '{name}': {err}")),
            };
            rows.push(result_row(vec![
                ("graph_name", Value::Str(name)),
                ("vertices", usize_count_value(counts.0)),
                ("edges", usize_count_value(counts.1)),
            ]));
        }
        print_result(
            &SQLResult::from_rows(
                vec!["graph_name".into(), "vertices".into(), "edges".into()],
                rows,
            ),
            out,
        );
        Ok(())
    }

    pub(super) fn handle_migrate_python_db(
        &mut self,
        arg: &str,
        out: &mut impl Write,
    ) -> Result<(), String> {
        let parts = arg.split_whitespace().collect::<Vec<_>>();
        if parts.len() != 2 {
            return Err("usage: \\migrate-python-db <source> <destination>".into());
        }
        let source = Path::new(parts[0]);
        let destination = Path::new(parts[1]);
        let report = migrate_python_database(source, destination)
            .map_err(|err| format!("migration failed: {err}"))?;
        print_migration_report(&report, out)
            .map_err(|error| format!("write migration report failed: {error}"))?;
        let engine = Engine::open(destination)
            .map_err(|err| format!("open migrated database failed: {err}"))?;
        self.engine = engine;
        self.db_path = Some(destination.to_path_buf());
        self.db_key = None;
        self.location = destination.display().to_string();
        let _ = writeln!(out, "opened {}", self.location);
        Ok(())
    }
}