corium-cli 0.1.56

Corium CLI
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
//! Read-only interactive SQL shell.

use std::path::Path;
use std::time::Instant;

use corium_db::Db;
use corium_peer::Connection;
use corium_sql::{SqlColumn, SqlRow, SqlSession};

use crate::instant::{TimePoint, format_instant, parse_time_point};
use rustyline::DefaultEditor;
use rustyline::error::ReadlineError;

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
enum View {
    #[default]
    Current,
    AsOf(u64),
    Since(u64),
    History,
    /// As-of a wall-clock instant (Unix milliseconds).
    AsOfInstant(i64),
    /// Since a wall-clock instant (Unix milliseconds).
    SinceInstant(i64),
}

impl View {
    fn apply(self, db: &Db) -> Db {
        match self {
            Self::Current => db.clone(),
            Self::AsOf(t) => db.as_of(t),
            Self::Since(t) => db.since(t),
            Self::History => db.history(),
            Self::AsOfInstant(instant) => db.as_of_instant(instant),
            Self::SinceInstant(instant) => db.since_instant(instant),
        }
    }
}

#[derive(Default)]
struct Shell {
    view: View,
    timing: bool,
}

enum MetaAction {
    Continue,
    Quit,
}

/// Runs an interactive shell, a command, or a SQL file.
pub async fn run(
    connection: &Connection,
    command: Option<&str>,
    file: Option<&Path>,
) -> Result<(), String> {
    let mut shell = Shell::default();
    if let Some(command) = command {
        return execute_script(&shell, &connection.db(), command).await;
    }
    if let Some(path) = file {
        let sql = std::fs::read_to_string(path)
            .map_err(|error| format!("cannot read {}: {error}", path.display()))?;
        return execute_script(&shell, &connection.db(), &sql).await;
    }

    let mut editor = DefaultEditor::new().map_err(|error| error.to_string())?;
    let mut buffer = String::new();
    println!(
        "Corium SQL for {:?}. End statements with ';'; type \\help for commands.",
        connection.db_name()
    );
    loop {
        let prompt = if buffer.is_empty() {
            "corium-sql> "
        } else {
            "        -> "
        };
        match editor.readline(prompt) {
            Ok(line) => {
                if buffer.is_empty() && line.trim_start().starts_with('\\') {
                    match shell.meta(&connection.db(), line.trim()).await {
                        Ok(MetaAction::Continue) => {}
                        Ok(MetaAction::Quit) => return Ok(()),
                        Err(error) => eprintln!("error: {error}"),
                    }
                    continue;
                }
                if !line.trim().is_empty() {
                    if !buffer.is_empty() {
                        buffer.push('\n');
                    }
                    buffer.push_str(&line);
                }
                let (statements, remainder) = split_statements(&buffer);
                buffer = remainder;
                for statement in statements {
                    let _ = editor.add_history_entry(statement.as_str());
                    let base = connection.db();
                    let execution = shell.execute(&base, &statement);
                    tokio::select! {
                        result = execution => {
                            if let Err(error) = result {
                                eprintln!("error: {error}");
                            }
                        }
                        _ = tokio::signal::ctrl_c() => eprintln!("query cancelled"),
                    }
                }
            }
            Err(ReadlineError::Interrupted) => {
                buffer.clear();
                println!("^C");
            }
            Err(ReadlineError::Eof) if buffer.trim().is_empty() => return Ok(()),
            Err(ReadlineError::Eof) => {
                let statement = std::mem::take(&mut buffer);
                shell.execute(&connection.db(), &statement).await?;
                return Ok(());
            }
            Err(error) => return Err(error.to_string()),
        }
    }
}

impl Shell {
    async fn execute(&self, base: &Db, sql: &str) -> Result<(), String> {
        let started = Instant::now();
        let db = self.view.apply(base);
        let session = SqlSession::new(&db).map_err(|error| error.to_string())?;
        let query = session
            .query(sql)
            .await
            .map_err(|error| error.to_string())?;
        let columns = query.columns().to_vec();
        let rows = query.collect().await.map_err(|error| error.to_string())?;
        print_table(&columns, &rows);
        if self.timing {
            println!("Time: {:.3} ms", started.elapsed().as_secs_f64() * 1_000.0);
        }
        Ok(())
    }

    async fn meta(&mut self, base: &Db, line: &str) -> Result<MetaAction, String> {
        let mut words = line.split_whitespace();
        let command = words.next().unwrap_or_default();
        let argument = words.next();
        if !matches!(command, "\\as-of" | "\\since") && words.next().is_some() {
            return Err("too many command arguments".into());
        }
        let time_argument = || {
            let trimmed = line[command.len()..].trim();
            (!trimmed.is_empty()).then_some(trimmed)
        };
        match command {
            "\\q" | "\\quit" => Ok(MetaAction::Quit),
            "\\help" | "\\?" => {
                println!(
                    "\\as-of t|timestamp | \\since t|timestamp | \\history on|off | \\current | \\basis | \\dt | \\d table | \\timing on|off | \\q"
                );
                Ok(MetaAction::Continue)
            }
            "\\as-of" => {
                self.view = match parse_time_point(time_argument(), "\\as-of")? {
                    TimePoint::T(t) => View::AsOf(t),
                    TimePoint::Instant(instant) => View::AsOfInstant(instant),
                };
                println!("View: {}", view_name(self.view));
                Ok(MetaAction::Continue)
            }
            "\\since" => {
                self.view = match parse_time_point(time_argument(), "\\since")? {
                    TimePoint::T(t) => View::Since(t),
                    TimePoint::Instant(instant) => View::SinceInstant(instant),
                };
                println!("View: {}", view_name(self.view));
                Ok(MetaAction::Continue)
            }
            "\\history" => {
                self.view = match argument {
                    Some("on") => View::History,
                    Some("off") => View::Current,
                    _ => return Err("usage: \\history on|off".into()),
                };
                println!("View: {}", view_name(self.view));
                Ok(MetaAction::Continue)
            }
            "\\current" if argument.is_none() => {
                self.view = View::Current;
                println!("View: current");
                Ok(MetaAction::Continue)
            }
            "\\current" => Err("usage: \\current".into()),
            "\\basis" if argument.is_none() => {
                let db = self.view.apply(base);
                println!("basis_t={} view={}", db.basis_t(), view_name(self.view));
                Ok(MetaAction::Continue)
            }
            "\\basis" => Err("usage: \\basis".into()),
            "\\timing" => {
                self.timing = match argument {
                    Some("on") => true,
                    Some("off") => false,
                    _ => return Err("usage: \\timing on|off".into()),
                };
                println!("Timing is {}", if self.timing { "on" } else { "off" });
                Ok(MetaAction::Continue)
            }
            "\\dt" if argument.is_none() => {
                let db = self.view.apply(base);
                let session = SqlSession::new(&db).map_err(|error| error.to_string())?;
                for table in session.tables() {
                    println!("{table}");
                }
                Ok(MetaAction::Continue)
            }
            "\\dt" => Err("usage: \\dt".into()),
            "\\d" => {
                let table = argument.ok_or_else(|| "usage: \\d table".to_owned())?;
                self.execute(base, &format!("SELECT * FROM {table} LIMIT 0"))
                    .await?;
                Ok(MetaAction::Continue)
            }
            _ => Err(format!("unknown SQL shell command {command}; try \\help")),
        }
    }
}

async fn execute_script(shell: &Shell, db: &Db, script: &str) -> Result<(), String> {
    let (mut statements, remainder) = split_statements(script);
    if !remainder.trim().is_empty() {
        statements.push(remainder);
    }
    for statement in statements {
        shell.execute(db, &statement).await?;
    }
    Ok(())
}

fn print_table(columns: &[SqlColumn], rows: &[SqlRow]) {
    if columns.is_empty() {
        println!("({} rows)", rows.len());
        return;
    }
    let mut widths = columns
        .iter()
        .map(|column| column.name.chars().count())
        .collect::<Vec<_>>();
    let rendered = rows
        .iter()
        .map(|row| {
            row.iter()
                .enumerate()
                .map(|(index, value)| {
                    let text = value.to_string().replace('\n', "\\n");
                    widths[index] = widths[index].max(text.chars().count());
                    text
                })
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();
    print_row(
        &columns
            .iter()
            .map(|column| column.name.clone())
            .collect::<Vec<_>>(),
        &widths,
    );
    println!(
        "{}",
        widths
            .iter()
            .map(|width| "-".repeat(*width))
            .collect::<Vec<_>>()
            .join("-+-")
    );
    for row in &rendered {
        print_row(row, &widths);
    }
    println!("({} rows)", rows.len());
}

fn print_row(row: &[String], widths: &[usize]) {
    println!(
        "{}",
        row.iter()
            .zip(widths)
            .map(|(value, width)| format!("{value:width$}"))
            .collect::<Vec<_>>()
            .join(" | ")
    );
}

/// Splits complete semicolon-terminated statements outside quoted strings and
/// SQL comments. The returned remainder is an incomplete trailing statement.
fn split_statements(input: &str) -> (Vec<String>, String) {
    #[derive(Clone, Copy, Eq, PartialEq)]
    enum State {
        Normal,
        SingleQuote,
        DoubleQuote,
        LineComment,
        BlockComment,
    }
    let bytes = input.as_bytes();
    let mut state = State::Normal;
    let mut statements = Vec::new();
    let mut start = 0;
    let mut index = 0;
    while index < bytes.len() {
        let byte = bytes[index];
        let next = bytes.get(index + 1).copied();
        match state {
            State::Normal => match (byte, next) {
                (b'\'', _) => state = State::SingleQuote,
                (b'"', _) => state = State::DoubleQuote,
                (b'-', Some(b'-')) => {
                    state = State::LineComment;
                    index += 1;
                }
                (b'/', Some(b'*')) => {
                    state = State::BlockComment;
                    index += 1;
                }
                (b';', _) => {
                    let statement = input[start..index].trim();
                    if !statement.is_empty() {
                        statements.push(statement.to_owned());
                    }
                    start = index + 1;
                }
                _ => {}
            },
            State::SingleQuote => {
                if byte == b'\'' {
                    if next == Some(b'\'') {
                        index += 1;
                    } else {
                        state = State::Normal;
                    }
                }
            }
            State::DoubleQuote => {
                if byte == b'"' {
                    if next == Some(b'"') {
                        index += 1;
                    } else {
                        state = State::Normal;
                    }
                }
            }
            State::LineComment if byte == b'\n' => state = State::Normal,
            State::BlockComment if byte == b'*' && next == Some(b'/') => {
                state = State::Normal;
                index += 1;
            }
            State::LineComment | State::BlockComment => {}
        }
        index += 1;
    }
    (statements, input[start..].trim().to_owned())
}

fn view_name(view: View) -> String {
    match view {
        View::Current => "current".into(),
        View::AsOf(t) => format!("as-of {t}"),
        View::Since(t) => format!("since {t}"),
        View::History => "history".into(),
        View::AsOfInstant(instant) => format!("as-of {}", format_instant(instant)),
        View::SinceInstant(instant) => format!("since {}", format_instant(instant)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn statement_splitter_respects_quotes_and_comments() {
        let sql = "SELECT ';' AS x; -- ; ignored\nSELECT \"a;b\"; SELECT 3";
        let (statements, remainder) = split_statements(sql);
        assert_eq!(
            statements,
            vec!["SELECT ';' AS x", "-- ; ignored\nSELECT \"a;b\""]
        );
        assert_eq!(remainder, "SELECT 3");
    }

    #[tokio::test]
    async fn time_views_accept_space_separated_timestamps() {
        let db = Db::new(corium_core::Schema::default());
        let mut shell = Shell::default();
        shell
            .meta(&db, "\\as-of 2026-07-25 09:30:00")
            .await
            .expect("as-of timestamp");
        assert!(matches!(shell.view, View::AsOfInstant(_)));
        shell
            .meta(&db, "\\since 2026-07-25 09:30:00")
            .await
            .expect("since timestamp");
        assert!(matches!(shell.view, View::SinceInstant(_)));
    }
}