qql-cli 0.4.2

Command-line interface, REPL, converter, and migration tools for QQL
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
//! Interactive QQL REPL (Read-Eval-Print Loop).
//!
//! Provides interactive query execution, multiline statement accumulation,
//! in-REPL formatting, query explanation, health diagnostics, and execution timing.

use std::time::Instant;

pub async fn run_repl(
    url: &str,
    use_edge: bool,
    executor: qql::executor::Executor,
    initial_params: Option<&serde_json::Value>,
) -> Result<(), Box<dyn std::error::Error>> {
    crate::output::print_banner();
    let target = if use_edge { "local edge" } else { url };
    crate::output::print_success(&format!("Connected to \x1b[36m{}\x1b[0m", target));
    println!(
        "Type \x1b[1mhelp\x1b[0m for available commands, \x1b[1m\\f\x1b[0m to format, or \x1b[1mexit\x1b[0m to quit.\n"
    );

    let mut rl = rustyline::DefaultEditor::new()?;
    let mut buffer = String::new();
    let mut session_params = match initial_params {
        Some(serde_json::Value::Object(map)) => map.clone(),
        _ => serde_json::Map::new(),
    };
    if !session_params.is_empty() {
        println!(
            "\x1b[1mLoaded {} session parameter(s) from startup:\x1b[0m",
            session_params.len()
        );
        for (k, v) in &session_params {
            println!("  \x1b[36m:{}\x1b[0m = {}", k, v);
        }
        println!();
    }

    loop {
        let prompt = if buffer.is_empty() {
            "\x1b[32m\x1b[1mqql>\x1b[0m "
        } else {
            "\x1b[32m\x1b[1mqql...>\x1b[0m "
        };

        let line = match rl.readline(prompt) {
            Ok(l) => l,
            Err(_) => {
                println!("\nBye.");
                break;
            }
        };

        let trimmed = line.trim();
        if trimmed.is_empty() {
            if !buffer.is_empty() {
                buffer.clear();
                println!("\x1b[2m(statement aborted)\x1b[0m");
            }
            continue;
        }

        // Meta-commands apply only when starting a new statement (buffer empty)
        if buffer.is_empty() {
            let lower = trimmed.to_lowercase();

            if lower == "exit" || lower == "quit" || lower == "\\q" || lower == ":q" {
                println!("Bye.");
                break;
            }

            if lower == "help" || lower == "\\h" || lower == "?" {
                print_repl_help();
                let _ = rl.add_history_entry(trimmed);
                continue;
            }

            if lower == "doctor" || lower == "\\d" {
                let _ = rl.add_history_entry(trimmed);
                let _ =
                    crate::commands::handle_doctor(url, use_edge, None, None, false, false).await;
                continue;
            }

            if let Some(args) = cut_command_prefix(trimmed, "param")
                .or_else(|| cut_command_prefix(trimmed, "\\param"))
                .or_else(|| cut_command_prefix(trimmed, "\\p"))
            {
                let _ = rl.add_history_entry(trimmed);
                let trimmed_args = args.trim();
                if trimmed_args.is_empty() {
                    if session_params.is_empty() {
                        println!("\x1b[2m(no session parameters set)\x1b[0m");
                    } else {
                        println!("\x1b[1mCurrent Session Parameters:\x1b[0m");
                        for (k, v) in &session_params {
                            println!("  \x1b[36m:{}\x1b[0m = {}", k, v);
                        }
                    }
                } else if trimmed_args.eq_ignore_ascii_case("clear") {
                    session_params.clear();
                    crate::output::print_success("Parameters cleared.");
                } else if let Some(path_str) = trimmed_args
                    .strip_prefix("load ")
                    .or_else(|| trimmed_args.strip_prefix("import "))
                    .map(str::trim)
                {
                    let p = path_str.trim_matches('\'').trim_matches('"');
                    match std::fs::read_to_string(p) {
                        Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
                            Ok(serde_json::Value::Object(map)) => {
                                let count = map.len();
                                for (k, v) in map {
                                    let key = k.strip_prefix(':').unwrap_or(&k).to_string();
                                    session_params.insert(key, v);
                                }
                                crate::output::print_success(&format!(
                                    "Loaded {count} parameter(s) from {p}."
                                ));
                            }
                            Ok(_) => {
                                crate::output::print_error(
                                    "parameter file must contain a JSON object with key-value pairs",
                                );
                            }
                            Err(e) => {
                                crate::output::print_error(&format!("invalid JSON in '{p}': {e}"));
                            }
                        },
                        Err(e) => {
                            crate::output::print_error(&format!(
                                "failed to read parameter file '{p}': {e}"
                            ));
                        }
                    }
                } else if let Some((key_raw, val_raw)) = trimmed_args.split_once('=') {
                    let key = key_raw
                        .trim()
                        .strip_prefix(':')
                        .unwrap_or(key_raw.trim())
                        .to_string();
                    let val_trimmed = val_raw.trim();
                    let val: serde_json::Value = serde_json::from_str(val_trimmed)
                        .unwrap_or_else(|_| serde_json::Value::String(val_trimmed.to_string()));
                    println!("Set parameter \x1b[36m:{key}\x1b[0m = {val}");
                    session_params.insert(key, val);
                } else {
                    crate::output::print_error(
                        "param usage: \\p [key=value | load <file.json> | clear]",
                    );
                }
                continue;
            }

            if let Some(args) =
                cut_command_prefix(trimmed, "fmt").or_else(|| cut_command_prefix(trimmed, "\\f"))
            {
                let _ = rl.add_history_entry(trimmed);
                match qql_core::fmt::format(&args) {
                    Ok(formatted) => {
                        println!("\x1b[1mFormatted QQL:\x1b[0m\n{}", formatted);
                    }
                    Err(e) => crate::output::print_error(&format!("format error: {}", e)),
                }
                continue;
            }

            if let Some(args) = cut_command_prefix(trimmed, "explain") {
                let _ = rl.add_history_entry(trimmed);
                match crate::commands::explain_query_str(&args) {
                    Ok(plan) => {
                        println!("\x1b[1mQuery Plan:\x1b[0m\n{}", plan);
                    }
                    Err(e) => crate::output::print_error(&format!("explain error: {}", e)),
                }
                continue;
            }

            if let Some(args) =
                cut_command_prefix(trimmed, "run").or_else(|| cut_command_prefix(trimmed, "\\e"))
            {
                let _ = rl.add_history_entry(trimmed);
                match crate::script::read_script(&args) {
                    Ok(statements) => {
                        let start = Instant::now();
                        let mut ok_count = 0;
                        let mut fail_count = 0;
                        for (idx, stmt) in statements.iter().enumerate() {
                            match executor
                                .execute(stmt, qql::executor::OnError::Continue)
                                .await
                            {
                                Ok(report) => {
                                    ok_count += report.succeeded;
                                    fail_count += report.failed;
                                    for r in report.results.iter().filter(|r| !r.ok) {
                                        crate::output::print_error(&format!(
                                            "statement {} ({}): {}",
                                            idx + 1,
                                            r.operation,
                                            r.message
                                        ));
                                    }
                                }
                                Err(e) => {
                                    fail_count += 1;
                                    crate::output::print_error(&format!(
                                        "statement {}: {}",
                                        idx + 1,
                                        e
                                    ));
                                }
                            }
                        }
                        let elapsed = start.elapsed();
                        crate::output::print_success(&format!(
                            "Ran script '{}' ({} succeeded, {} failed in {:.2?})",
                            args, ok_count, fail_count, elapsed
                        ));
                    }
                    Err(e) => crate::output::print_error(&format!(
                        "cannot read script file '{}': {}",
                        args, e
                    )),
                }
                continue;
            }

            if let Some(args) = cut_command_prefix(trimmed, "dump") {
                let _ = rl.add_history_entry(trimmed);
                let parts: Vec<&str> = args.split_whitespace().collect();
                let dump_parts = if parts.len() >= 3 && parts[0].eq_ignore_ascii_case("collection")
                {
                    &parts[1..]
                } else {
                    &parts
                };
                if dump_parts.len() != 2 {
                    crate::output::print_error(
                        "dump error: usage DUMP [COLLECTION] <name> <output.qql>",
                    );
                    continue;
                }
                match crate::dump::dump_collection(
                    &executor,
                    dump_parts[0],
                    dump_parts[1],
                    50,
                    None,
                )
                .await
                {
                    Ok(stats) => crate::output::print_success(&format!(
                        "Dumped collection '{}' to {} ({} written, {} skipped, {} batches)",
                        dump_parts[0], dump_parts[1], stats.written, stats.skipped, stats.batches
                    )),
                    Err(e) => crate::output::print_error(&format!("dump error: {}", e)),
                }
                continue;
            }
        }

        // Multiline accumulation
        if !buffer.is_empty() {
            buffer.push('\n');
        }
        buffer.push_str(trimmed);

        if !is_statement_complete(&buffer) {
            continue;
        }

        let full_query = core::mem::take(&mut buffer);
        let _ = rl.add_history_entry(&full_query);

        let effective_query = if !session_params.is_empty() {
            // NOTE: session params are named-only (`:name`). Positional `?`
            // placeholders have no REPL surface — adding one (e.g. an ordered
            // `\p ? v` list mixed with the named map) is ambiguous about
            // ordering vs. the map, so `?` queries must go through
            // `qql run --params-file` with a JSON array instead.
            match qql_core::params_json::bind_str_with_params(
                &full_query,
                &serde_json::Value::Object(session_params.clone()),
                false,
            ) {
                Ok(bound) => bound,
                Err(e) => {
                    crate::output::print_error(&format!("bind error: {}", e));
                    continue;
                }
            }
        } else {
            full_query
        };

        let start = Instant::now();
        match executor
            .execute(&effective_query, qql::executor::OnError::Stop)
            .await
        {
            Ok(report) => {
                let elapsed = start.elapsed();
                if let Err(e) = crate::table::render_report(&report, false) {
                    crate::output::print_error(&format!("display error: {}", e));
                } else {
                    println!("\x1b[2m(completed in {:.2?})\x1b[0m\n", elapsed);
                }
            }
            Err(e) => crate::output::print_error(&format!("execution error: {}", e)),
        }
    }

    executor.close().await?;
    Ok(())
}

fn is_statement_complete(query: &str) -> bool {
    let trimmed = query.trim();
    if trimmed.is_empty() {
        return false;
    }

    // Quick path: standalone single-line admin commands
    let upper = trimmed.to_uppercase();
    if upper == "SHOW COLLECTIONS"
        || upper == "SHOW QUOTAS"
        || upper.starts_with("SHOW SHARD KEYS")
        || upper.starts_with("SHOW COLLECTION ")
    {
        return true;
    }

    // Use the official lexer to tokenize input, accurately handling comments,
    // backtick strings, and escape sequences without hand-rolled state machines.
    let mut lexer = qql_core::lexer::Lexer::new(trimmed);
    let mut depth = 0;
    let mut has_semicolon = false;

    loop {
        match lexer.next_token() {
            Ok(token) => match token.kind {
                qql_core::token::TokenKind::Eof => break,
                qql_core::token::TokenKind::Lparen
                | qql_core::token::TokenKind::Lbracket
                | qql_core::token::TokenKind::Lbrace => depth += 1,
                qql_core::token::TokenKind::Rparen
                | qql_core::token::TokenKind::Rbracket
                | qql_core::token::TokenKind::Rbrace
                    if depth > 0 =>
                {
                    depth -= 1;
                }
                qql_core::token::TokenKind::Semicolon => {
                    has_semicolon = true;
                }
                _ => {}
            },
            Err(e) => {
                // If lexing encountered an unterminated string or incomplete token,
                // the statement is in progress across lines.
                let msg = e.to_string();
                if msg.contains("unterminated") {
                    return false;
                }
                break;
            }
        }
    }

    if depth > 0 {
        return false;
    }

    if has_semicolon || trimmed.ends_with(';') {
        return true;
    }

    // If all delimiters are closed and the query already parses cleanly as a valid
    // statement, execute it immediately without requiring a semicolon on a separate line.
    qql_core::parser::Parser::parse(trimmed).is_ok()
}

fn cut_command_prefix(input: &str, prefix: &str) -> Option<String> {
    let input_trimmed = input.trim();
    let lower = input_trimmed.to_lowercase();

    if lower.len() <= prefix.len() || !lower.starts_with(prefix) {
        return None;
    }

    let after = &input_trimmed[prefix.len()..];
    if after.starts_with(' ') {
        Some(after.trim().to_string())
    } else {
        None
    }
}

fn print_repl_help() {
    let help = "\x1b[1mAvailable Statements:\x1b[0m\n\
\n  \x1b[33mUPSERT INTO\x1b[0m <name> \x1b[33mVALUES\x1b[0m {id: 1, text: '...', ...}\n\
\n  \x1b[33mCREATE COLLECTION\x1b[0m <name> [\x1b[33mHYBRID\x1b[0m [\x1b[33mRERANK\x1b[0m]]\n\
\n  \x1b[33mDROP COLLECTION\x1b[0m <name>\n\
\n  \x1b[33mSHOW COLLECTIONS\x1b[0m\n\
\n  \x1b[33mQUERY\x1b[0m ['<text>' | [<vector>] | NEAREST POINT <id> | ...]\n\
      \x1b[33mFROM\x1b[0m <collection> [\x1b[33mUSING\x1b[0m <vector> [\x1b[33mAS DENSE|SPARSE\x1b[0m]] \x1b[33mLIMIT\x1b[0m <n>\n\
\n  \x1b[33mQUERY POINTS\x1b[0m (<id>, ...) \x1b[33mFROM\x1b[0m <name> [\x1b[33mWITH PAYLOAD false\x1b[0m]\n\
\n  \x1b[33mFACET\x1b[0m <field> \x1b[33mFROM\x1b[0m <name> [\x1b[33mWHERE\x1b[0m <filter>] [\x1b[33mLIMIT\x1b[0m <n>] [\x1b[33mEXACT true\x1b[0m]\n\
\n  \x1b[33mSCROLL FROM\x1b[0m <name> [\x1b[33mWHERE\x1b[0m <filter>] [\x1b[33mAFTER\x1b[0m '<id>'] [\x1b[33mWITH VECTOR\x1b[0m] \x1b[33mLIMIT\x1b[0m <n>\n\
\n  \x1b[33mDELETE FROM\x1b[0m <name> \x1b[33mWHERE\x1b[0m id = '<id>' | <field> = '<value>'\n\
\n\x1b[1mBuilt-in Commands:\x1b[0m\n\
\n  \x1b[36mhelp\x1b[0m, \x1b[36m\\h\x1b[0m, \x1b[36m?\x1b[0m       Show this help card (note: bare ? triggers help)\n\
  \x1b[36mdoctor\x1b[0m, \x1b[36m\\d\x1b[0m         Check connection health and loaded model hosts\n\
  \x1b[36mparam [k=v | load <file> | clear]\x1b[0m, \x1b[36m\\p\x1b[0m Set, load JSON, inspect, or clear session query parameters\n\
  (named `:name` params only; positional `?` needs `qql run --params-file`)\n\
  \x1b[36mfmt <qql>\x1b[0m, \x1b[36m\\f\x1b[0m      Format QQL into canonical syntax\n\
  \x1b[36mexplain <qql>\x1b[0m     Show hierarchical tree query execution plan\n\
  \x1b[36mrun <file>\x1b[0m, \x1b[36m\\e\x1b[0m      Run a .qql script file against Qdrant\n\
  \x1b[36mdump <name> <file>\x1b[0m Dump collection schema and points to .qql\n\
  \x1b[36mexit\x1b[0m, \x1b[36mquit\x1b[0m, \x1b[36m\\q\x1b[0m    Exit the shell\n\
\n\x1b[1mKeyboard Shortcuts:\x1b[0m\n\
\n  Ctrl-C         Cancel current input / abort multiline buffer\n\
  Ctrl-D         Exit shell\n";
    println!("{}", help);
}

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

    #[test]
    fn test_is_statement_complete_with_comments() {
        assert!(is_statement_complete(
            "QUERY TEXT 'x' FROM docs -- it's a comment\n;"
        ));
        assert!(is_statement_complete(
            "QUERY TEXT 'x' FROM docs -- (see docs\n;"
        ));
    }

    #[test]
    fn test_is_statement_complete_with_quotes() {
        assert!(is_statement_complete(
            "UPSERT INTO t VALUES {id: 1, text: 'it\\'s ok'};"
        ));
        assert!(!is_statement_complete("QUERY TEXT 'unterminated"));
    }

    #[test]
    fn test_is_statement_complete_single_line_queries() {
        assert!(is_statement_complete(
            "QUERY TEXT 'hello' FROM docs LIMIT 5;"
        ));
        assert!(is_statement_complete("SHOW COLLECTIONS"));
    }
}