• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tstack / lnav / 17955647695-2537

23 Sep 2025 06:33PM UTC coverage: 64.851% (-0.1%) from 64.974%
17955647695-2537

push

github

tstack
[build] left local path in cargo

45984 of 70907 relevant lines covered (64.85%)

406352.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.34
/src/command_executor.cc
1
/**
2
 * Copyright (c) 2015, Timothy Stack
3
 *
4
 * All rights reserved.
5
 *
6
 * Redistribution and use in source and binary forms, with or without
7
 * modification, are permitted provided that the following conditions are met:
8
 *
9
 * * Redistributions of source code must retain the above copyright notice, this
10
 * list of conditions and the following disclaimer.
11
 * * Redistributions in binary form must reproduce the above copyright notice,
12
 * this list of conditions and the following disclaimer in the documentation
13
 * and/or other materials provided with the distribution.
14
 * * Neither the name of Timothy Stack nor the names of its contributors
15
 * may be used to endorse or promote products derived from this software
16
 * without specific prior written permission.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
19
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
22
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 */
29

30
#include <vector>
31

32
#include "command_executor.hh"
33

34
#include "base/ansi_scrubber.hh"
35
#include "base/ansi_vars.hh"
36
#include "base/fs_util.hh"
37
#include "base/humanize.hh"
38
#include "base/injector.hh"
39
#include "base/itertools.hh"
40
#include "base/paths.hh"
41
#include "base/string_util.hh"
42
#include "bound_tags.hh"
43
#include "config.h"
44
#include "curl_looper.hh"
45
#include "db_sub_source.hh"
46
#include "help_text_formatter.hh"
47
#include "lnav.hh"
48
#include "lnav.indexing.hh"
49
#include "lnav.prompt.hh"
50
#include "lnav_config.hh"
51
#include "lnav_util.hh"
52
#include "log_format_loader.hh"
53
#include "prql-modules.h"
54
#include "readline_highlighters.hh"
55
#include "service_tags.hh"
56
#include "shlex.hh"
57
#include "sql_help.hh"
58
#include "sql_util.hh"
59
#include "vtab_module.hh"
60

61
#ifdef HAVE_RUST_DEPS
62
#    include "lnav_rs_ext.cxx.hh"
63
#endif
64

65
using namespace std::literals::chrono_literals;
66
using namespace lnav::roles::literals;
67

68
exec_context INIT_EXEC_CONTEXT;
69

70
static sig_atomic_t sql_counter = 0;
71

72
int
73
sql_progress(const log_cursor& lc)
11,711✔
74
{
75
    if (lnav_data.ld_window == nullptr) {
11,711✔
76
        return 0;
11,711✔
77
    }
78

79
    if (!lnav_data.ld_looping) {
×
80
        return 1;
×
81
    }
82

83
    if (ui_periodic_timer::singleton().time_to_update(sql_counter)) {
×
84
        ssize_t total = lnav_data.ld_log_source.text_line_count();
×
85
        off_t off = lc.lc_curr_line;
×
86

87
        if (off >= 0 && off <= total) {
×
88
            lnav_data.ld_bottom_source.update_loading(off, total);
×
89
            lnav_data.ld_status[LNS_BOTTOM].set_needs_update();
×
90
        }
91
        lnav_data.ld_status_refresher(lnav::func::op_type::blocking);
×
92
    }
93

94
    return 0;
×
95
}
96

97
void
98
sql_progress_finished()
1,633✔
99
{
100
    if (sql_counter == 0) {
1,633✔
101
        return;
1,633✔
102
    }
103

104
    sql_counter = 0;
×
105

106
    if (lnav_data.ld_window == nullptr) {
×
107
        return;
×
108
    }
109

110
    lnav_data.ld_bottom_source.update_loading(0, 0);
×
111
    lnav_data.ld_status[LNS_BOTTOM].set_needs_update();
×
112
    lnav_data.ld_status_refresher(lnav::func::op_type::blocking);
×
113
    lnav_data.ld_views[LNV_DB].redo_search();
×
114
}
115

116
static Result<std::string, lnav::console::user_message> execute_from_file(
117
    exec_context& ec,
118
    const std::string& src,
119
    int line_number,
120
    const std::string& cmdline);
121

122
Result<std::string, lnav::console::user_message>
123
execute_command(exec_context& ec, const std::string& cmdline)
678✔
124
{
125
    std::vector<std::string> args;
678✔
126

127
    log_info("Executing: %s", cmdline.c_str());
678✔
128

129
    split_ws(cmdline, args);
678✔
130

131
    if (!args.empty()) {
678✔
132
        readline_context::command_map_t::iterator iter;
678✔
133

134
        if ((iter = lnav_commands.find(args[0])) == lnav_commands.end()) {
678✔
135
            return ec.make_error("unknown command - {}", args[0]);
×
136
        }
137

138
        ec.ec_current_help = &iter->second->c_help;
678✔
139
        try {
140
            auto retval = iter->second->c_func(ec, cmdline, args);
678✔
141
            if (retval.isErr()) {
678✔
142
                auto um = retval.unwrapErr();
42✔
143

144
                ec.add_error_context(um);
42✔
145
                ec.ec_current_help = nullptr;
42✔
146
                return Err(um);
42✔
147
            }
42✔
148
            ec.ec_current_help = nullptr;
636✔
149

150
            return retval;
636✔
151
        } catch (const std::exception& e) {
678✔
152
            auto um = lnav::console::user_message::error(
×
153
                          attr_line_t("unexpected error while executing: ")
×
154
                              .append(lnav::roles::quoted_code(cmdline)))
×
155
                          .with_reason(e.what());
×
156
            return Err(um);
×
157
        }
×
158
    }
159

160
    return ec.make_error("no command to execute");
×
161
}
678✔
162

163
static Result<std::map<std::string, scoped_value_t>,
164
              lnav::console::user_message>
165
bind_sql_parameters(exec_context& ec, sqlite3_stmt* stmt)
1,626✔
166
{
167
    std::map<std::string, scoped_value_t> retval;
1,626✔
168
    auto param_count = sqlite3_bind_parameter_count(stmt);
1,626✔
169
    for (int lpc = 0; lpc < param_count; lpc++) {
1,788✔
170
        std::map<std::string, std::string>::iterator ov_iter;
163✔
171
        const auto* name = sqlite3_bind_parameter_name(stmt, lpc + 1);
163✔
172
        if (name == nullptr) {
163✔
173
            auto um
174
                = lnav::console::user_message::error("invalid SQL statement")
2✔
175
                      .with_reason(
2✔
176
                          "using a question-mark (?) for bound variables "
177
                          "is not supported, only named bound parameters "
178
                          "are supported")
179
                      .with_help(
2✔
180
                          "named parameters start with a dollar-sign "
181
                          "($) or colon (:) followed by the variable name")
182
                      .move();
1✔
183
            ec.add_error_context(um);
1✔
184

185
            return Err(um);
1✔
186
        }
1✔
187

188
        if (name[0] == '$') {
162✔
189
            const auto& lvars = ec.ec_local_vars.top();
133✔
190
            const auto& gvars = ec.ec_global_vars;
133✔
191
            std::map<std::string, scoped_value_t>::const_iterator local_var,
133✔
192
                global_var;
133✔
193
            const char* env_value;
194

195
            if (lnav_data.ld_window) {
133✔
196
                char buf[32];
197
                unsigned int lines, cols;
198

199
                ncplane_dim_yx(lnav_data.ld_window, &lines, &cols);
×
200
                if (strcmp(name, "$LINES") == 0) {
×
201
                    snprintf(buf, sizeof(buf), "%d", lines);
×
202
                    sqlite3_bind_text(stmt, lpc + 1, buf, -1, SQLITE_TRANSIENT);
×
203
                } else if (strcmp(name, "$COLS") == 0) {
×
204
                    snprintf(buf, sizeof(buf), "%d", cols);
×
205
                    sqlite3_bind_text(stmt, lpc + 1, buf, -1, SQLITE_TRANSIENT);
×
206
                }
207
            }
208

209
            if ((local_var = lvars.find(&name[1])) != lvars.end()) {
399✔
210
                mapbox::util::apply_visitor(
122✔
211
                    sqlitepp::bind_visitor(stmt, lpc + 1), local_var->second);
122✔
212
                retval[name] = local_var->second;
366✔
213
            } else if ((global_var = gvars.find(&name[1])) != gvars.end()) {
33✔
214
                mapbox::util::apply_visitor(
×
215
                    sqlitepp::bind_visitor(stmt, lpc + 1), global_var->second);
×
216
                retval[name] = global_var->second;
×
217
            } else if ((env_value = getenv(&name[1])) != nullptr) {
11✔
218
                sqlite3_bind_text(stmt, lpc + 1, env_value, -1, SQLITE_STATIC);
3✔
219
                retval[name] = string_fragment::from_c_str(env_value);
9✔
220
            }
221
        } else if (name[0] == ':' && ec.ec_line_values != nullptr) {
29✔
222
            for (auto& lv : ec.ec_line_values->lvv_values) {
159✔
223
                if (lv.lv_meta.lvm_name != &name[1]) {
130✔
224
                    continue;
101✔
225
                }
226
                switch (lv.lv_meta.lvm_kind) {
29✔
227
                    case value_kind_t::VALUE_BOOLEAN:
×
228
                        sqlite3_bind_int64(stmt, lpc + 1, lv.lv_value.i);
×
229
                        retval[name] = fmt::to_string(lv.lv_value.i);
×
230
                        break;
×
231
                    case value_kind_t::VALUE_FLOAT:
×
232
                        sqlite3_bind_double(stmt, lpc + 1, lv.lv_value.d);
×
233
                        retval[name] = fmt::to_string(lv.lv_value.d);
×
234
                        break;
×
235
                    case value_kind_t::VALUE_INTEGER:
×
236
                        sqlite3_bind_int64(stmt, lpc + 1, lv.lv_value.i);
×
237
                        retval[name] = fmt::to_string(lv.lv_value.i);
×
238
                        break;
×
239
                    case value_kind_t::VALUE_NULL:
×
240
                        sqlite3_bind_null(stmt, lpc + 1);
×
241
                        retval[name] = string_fragment::from_c_str(
×
242
                            db_label_source::NULL_STR);
×
243
                        break;
×
244
                    default:
29✔
245
                        sqlite3_bind_text(stmt,
29✔
246
                                          lpc + 1,
247
                                          lv.text_value(),
248
                                          lv.text_length(),
29✔
249
                                          SQLITE_TRANSIENT);
250
                        retval[name] = lv.to_string();
87✔
251
                        break;
29✔
252
                }
253
            }
254
        } else {
29✔
255
            sqlite3_bind_null(stmt, lpc + 1);
×
256
            log_warning("Could not bind variable: %s", name);
×
257
            retval[name]
×
258
                = string_fragment::from_c_str(db_label_source::NULL_STR);
×
259
        }
260
    }
261

262
    return Ok(retval);
1,625✔
263
}
1,626✔
264

265
static void
266
execute_search(const std::string& search_cmd)
7✔
267
{
268
    textview_curses* tc = get_textview_for_mode(lnav_data.ld_mode);
7✔
269
    auto search_term = string_fragment(search_cmd)
7✔
270
                           .find_right_boundary(0, string_fragment::tag1{'\n'})
7✔
271
                           .to_string();
7✔
272
    tc->execute_search(search_term);
7✔
273
}
7✔
274

275
Result<std::string, lnav::console::user_message>
276
execute_sql(exec_context& ec, const std::string& sql, std::string& alt_msg)
1,639✔
277
{
278
    auto_mem<sqlite3_stmt> stmt(sqlite3_finalize);
1,639✔
279
    timeval start_tv, end_tv;
280
    std::string stmt_str = trim(sql);
1,639✔
281
    std::string retval;
1,639✔
282
    int retcode = SQLITE_OK;
1,639✔
283

284
    if (lnav::sql::is_prql(stmt_str)) {
1,639✔
285
        log_info("compiling PRQL: %s", stmt_str.c_str());
42✔
286

287
#if HAVE_RUST_DEPS
288
        extern rust::Vec<lnav_rs_ext::SourceTreeElement> sqlite_extension_prql;
289
        auto opts = lnav_rs_ext::Options{true, "sql.sqlite", true};
42✔
290

291
        auto tree = sqlite_extension_prql;
42✔
292
        for (const auto& mod : lnav_prql_modules) {
126✔
293
            log_debug("lnav_rs_ext adding mod %s", mod.get_name());
84✔
294
            tree.emplace_back(lnav_rs_ext::SourceTreeElement{
168✔
295
                mod.get_name(),
296
                mod.to_string_fragment_producer()->to_string(),
168✔
297
            });
298
        }
299
        tree.emplace_back(lnav_rs_ext::SourceTreeElement{"", stmt_str});
42✔
300
        log_debug("BEGIN compiling tree");
42✔
301
        auto cr = lnav_rs_ext::compile_tree(tree, opts);
42✔
302
        log_debug("END compiling tree");
42✔
303

304
        for (const auto& msg : cr.messages) {
42✔
305
            if (msg.kind != lnav_rs_ext::MessageKind::Error) {
1✔
306
                continue;
×
307
            }
308

309
            auto stmt_al = attr_line_t(stmt_str);
1✔
310
            readline_sql_highlighter(stmt_al, lnav::sql::dialect::prql, 0);
1✔
311
            auto um
312
                = lnav::console::user_message::error(
×
313
                      attr_line_t("unable to compile PRQL: ").append(stmt_al))
2✔
314
                      .with_reason(
1✔
315
                          attr_line_t::from_ansi_str((std::string) msg.reason));
2✔
316
            if (!msg.display.empty()) {
1✔
317
                um.with_note(
1✔
318
                    attr_line_t::from_ansi_str((std::string) msg.display));
2✔
319
            }
320
            for (const auto& hint : msg.hints) {
1✔
321
                um.with_help(attr_line_t::from_ansi_str((std::string) hint));
×
322
                break;
×
323
            }
324
            return Err(um);
1✔
325
        }
1✔
326
        log_debug("done!");
41✔
327
        stmt_str = (std::string) cr.output;
41✔
328
#else
329
        auto um = lnav::console::user_message::error(
330
            attr_line_t("PRQL is not supported in this build"));
331
        return Err(um);
332
#endif
333
    }
44✔
334

335
    log_info("Executing SQL: %s", stmt_str.c_str());
1,638✔
336

337
    auto old_mode = lnav_data.ld_mode;
1,638✔
338
    lnav_data.ld_mode = ln_mode_t::BUSY;
1,638✔
339
    auto mode_fin = finally([old_mode]() { lnav_data.ld_mode = old_mode; });
1,638✔
340
    lnav_data.ld_bottom_source.grep_error("");
1,638✔
341
    lnav_data.ld_status[LNS_BOTTOM].set_needs_update();
1,638✔
342

343
    if (startswith(stmt_str, ".")) {
1,638✔
344
        std::vector<std::string> args;
5✔
345
        split_ws(stmt_str, args);
5✔
346

347
        const auto* sql_cmd_map
348
            = injector::get<readline_context::command_map_t*,
349
                            sql_cmd_map_tag>();
5✔
350
        auto cmd_iter = sql_cmd_map->find(args[0]);
5✔
351

352
        if (cmd_iter != sql_cmd_map->end()) {
5✔
353
            ec.ec_current_help = &cmd_iter->second->c_help;
5✔
354
            auto retval = cmd_iter->second->c_func(ec, stmt_str, args);
5✔
355
            ec.ec_current_help = nullptr;
5✔
356

357
            return retval;
5✔
358
        }
5✔
359
    }
5✔
360

361
    ec.ec_accumulator->clear();
1,633✔
362

363
    require(!ec.ec_source.empty());
1,633✔
364
    const auto& source = ec.ec_source.back();
1,633✔
365
    sql_progress_guard progress_guard(sql_progress,
366
                                      sql_progress_finished,
367
                                      source.s_location,
368
                                      source.s_content);
1,633✔
369
    gettimeofday(&start_tv, nullptr);
1,633✔
370

371
    const auto* curr_stmt = stmt_str.c_str();
1,633✔
372
    auto last_is_readonly = false;
1,633✔
373
    while (curr_stmt != nullptr) {
3,203✔
374
        const char* tail = nullptr;
3,203✔
375
        while (isspace(*curr_stmt)) {
3,203✔
376
            curr_stmt += 1;
×
377
        }
378
        retcode = sqlite3_prepare_v2(
3,203✔
379
            lnav_data.ld_db.in(), curr_stmt, -1, stmt.out(), &tail);
380
        if (retcode != SQLITE_OK) {
3,203✔
381
            const char* errmsg = sqlite3_errmsg(lnav_data.ld_db);
7✔
382

383
            alt_msg = "";
7✔
384

385
            auto um = lnav::console::user_message::error(
14✔
386
                          "failed to compile SQL statement")
387
                          .with_reason(errmsg)
14✔
388
                          .with_snippets(ec.ec_source)
14✔
389
                          .move();
7✔
390

391
            auto annotated_sql = annotate_sql_with_error(
392
                lnav_data.ld_db.in(), curr_stmt, tail);
7✔
393
            auto loc = um.um_snippets.back().s_location;
7✔
394
            if (curr_stmt == stmt_str.c_str()) {
7✔
395
                um.um_snippets.pop_back();
7✔
396
            } else {
397
                auto tail_iter = stmt_str.begin();
×
398

399
                std::advance(tail_iter, (curr_stmt - stmt_str.c_str()));
×
400
                loc.sl_line_number
×
401
                    += std::count(stmt_str.begin(), tail_iter, '\n');
×
402
            }
403

404
            um.with_snippet(lnav::console::snippet::from(loc, annotated_sql));
7✔
405

406
            return Err(um);
7✔
407
        }
7✔
408
        if (stmt == nullptr) {
3,196✔
409
            retcode = SQLITE_DONE;
1,570✔
410
            break;
1,570✔
411
        }
412
#ifdef HAVE_SQLITE3_STMT_READONLY
413
        last_is_readonly = sqlite3_stmt_readonly(stmt.in());
1,626✔
414
        if (ec.is_read_only() && !last_is_readonly) {
1,626✔
415
            return ec.make_error(
416
                "modifying statements are not allowed in this context: {}",
417
                sql);
×
418
        }
419
#endif
420
        bool done = false;
1,626✔
421

422
        auto bound_values = TRY(bind_sql_parameters(ec, stmt.in()));
1,626✔
423
        if (last_is_readonly) {
1,625✔
424
            ec.ec_sql_callback(ec, stmt.in());
1,508✔
425
        }
426
        while (!done) {
5,825✔
427
            retcode = sqlite3_step(stmt.in());
4,255✔
428

429
            switch (retcode) {
4,255✔
430
                case SQLITE_OK:
1,570✔
431
                case SQLITE_DONE: {
432
                    auto changes = sqlite3_changes(lnav_data.ld_db.in());
1,570✔
433

434
                    log_info("sqlite3_changes() -> %d", changes);
1,570✔
435
                    done = true;
1,570✔
436
                    break;
1,570✔
437
                }
438

439
                case SQLITE_ROW:
2,630✔
440
                    ec.ec_sql_callback(ec, stmt.in());
2,630✔
441
                    break;
2,630✔
442

443
                default: {
55✔
444
                    attr_line_t bound_note;
55✔
445

446
                    if (!bound_values.empty()) {
55✔
447
                        bound_note.append(
3✔
448
                            "the bound parameters are set as follows:\n");
449
                        for (const auto& bval : bound_values) {
11✔
450
                            auto val_as_str = fmt::to_string(bval.second);
8✔
451
                            auto sql_type = bval.second.match(
8✔
452
                                [](const std::string&) { return SQLITE_TEXT; },
5✔
453
                                [](const string_fragment&) {
×
454
                                    return SQLITE_TEXT;
×
455
                                },
456
                                [](bool) { return SQLITE_INTEGER; },
×
457
                                [](int64_t) { return SQLITE_INTEGER; },
1✔
458
                                [](null_value_t) { return SQLITE_NULL; },
1✔
459
                                [](double) { return SQLITE_FLOAT; });
1✔
460
                            auto scrubbed_val = scrub_ws(val_as_str.c_str());
8✔
461
                            truncate_to(scrubbed_val, 40);
8✔
462
                            bound_note.append("  ")
8✔
463
                                .append(lnav::roles::variable(bval.first))
16✔
464
                                .append(":")
8✔
465
                                .append(sqlite3_type_to_string(sql_type))
8✔
466
                                .append(" = ")
8✔
467
                                .append_quoted(scrubbed_val)
16✔
468
                                .append("\n");
8✔
469
                        }
8✔
470
                    }
471

472
                    log_error("sqlite3_step error code: %d", retcode);
55✔
473
                    auto um = sqlite3_error_to_user_message(lnav_data.ld_db)
110✔
474
                                  .with_note(bound_note)
55✔
475
                                  .move();
55✔
476

477
                    if (!ec.get_provenance<exec_context::keyboard_input>()) {
55✔
478
                        um.with_context_snippets(ec.ec_source)
110✔
479
                            .remove_internal_snippets();
55✔
480
                    }
481

482
                    return Err(um);
55✔
483
                }
55✔
484
            }
485
        }
486

487
        curr_stmt = tail;
1,570✔
488
    }
1,625✔
489

490
    if (last_is_readonly && !ec.ec_label_source_stack.empty()) {
1,570✔
491
        auto& dls = *ec.ec_label_source_stack.back();
1,483✔
492
        dls.dls_query_end = std::chrono::steady_clock::now();
1,483✔
493

494
        size_t memory_usage = 0, total_size = 0, cached_chunks = 0;
1,483✔
495
        for (auto cc = dls.dls_cell_container.cc_first.get(); cc != nullptr;
2,967✔
496
             cc = cc->cc_next.get())
1,484✔
497
        {
498
            total_size += cc->cc_capacity;
1,484✔
499
            if (cc->cc_data) {
1,484✔
500
                cached_chunks += 1;
1,483✔
501
                memory_usage += cc->cc_capacity;
1,483✔
502
            } else {
503
                memory_usage += cc->cc_compressed_size;
1✔
504
            }
505
        }
506
        log_debug(
1,483✔
507
            "cell memory footprint: total=%zu; actual=%zu; cached-chunks=%zu",
508
            total_size,
509
            memory_usage,
510
            cached_chunks);
511
    }
512
    gettimeofday(&end_tv, nullptr);
1,570✔
513
    lnav_data.ld_mode = old_mode;
1,570✔
514
    if (retcode == SQLITE_DONE) {
1,570✔
515
        if (lnav_data.ld_log_source.is_line_meta_changed()) {
1,570✔
516
            lnav_data.ld_log_source.text_filters_changed();
9✔
517
            lnav_data.ld_views[LNV_LOG].reload_data();
9✔
518
        }
519
        lnav_data.ld_filter_view.reload_data();
1,570✔
520
        lnav_data.ld_files_view.reload_data();
1,570✔
521

522
        lnav_data.ld_active_files.fc_files
523
            | lnav::itertools::for_each(&logfile::dump_stats);
1,570✔
524
        if (ec.ec_sql_callback != sql_callback) {
1,570✔
525
            retval = ec.ec_accumulator->get_string();
39✔
526
        } else {
527
            auto& dls = *(ec.ec_label_source_stack.back());
1,531✔
528
            if (!dls.dls_row_cursors.empty()) {
1,531✔
529
                lnav_data.ld_views[LNV_DB].reload_data();
1,428✔
530
                lnav_data.ld_views[LNV_DB].set_selection(0_vl);
1,428✔
531
                lnav_data.ld_views[LNV_DB].set_left(0);
1,428✔
532
                if (lnav_data.ld_flags & LNF_HEADLESS) {
1,428✔
533
                    if (ec.ec_local_vars.size() == 1) {
944✔
534
                        ensure_view(&lnav_data.ld_views[LNV_DB]);
854✔
535
                    }
536

537
                    retval = "";
944✔
538
                    alt_msg = "";
944✔
539
                } else if (dls.dls_row_cursors.size() == 1) {
484✔
540
                    retval = dls.get_row_as_string(0_vl);
436✔
541
                } else {
542
                    int row_count = dls.dls_row_cursors.size();
48✔
543
                    char row_count_buf[128];
544
                    timeval diff_tv;
545

546
                    timersub(&end_tv, &start_tv, &diff_tv);
48✔
547
                    snprintf(row_count_buf,
48✔
548
                             sizeof(row_count_buf),
549
                             ANSI_BOLD("%'d") " row%s matched in " ANSI_BOLD(
550
                                 "%ld.%03ld") " seconds",
551
                             row_count,
552
                             row_count == 1 ? "" : "s",
553
                             diff_tv.tv_sec,
554
                             std::max((long) diff_tv.tv_usec / 1000, 1L));
48✔
555
                    retval = row_count_buf;
48✔
556
                    if (dls.has_log_time_column()) {
48✔
557
                        alt_msg
558
                            = HELP_MSG_1(Q,
2✔
559
                                         "to switch back to the previous view "
560
                                         "at the matching 'log_time' value");
561
                    } else {
562
                        alt_msg = "";
46✔
563
                    }
564
                }
565
            }
566
#ifdef HAVE_SQLITE3_STMT_READONLY
567
            else if (last_is_readonly)
103✔
568
            {
569
                retval = "info: No rows matched";
25✔
570
                alt_msg = "";
25✔
571

572
                if (lnav_data.ld_flags & LNF_HEADLESS) {
25✔
573
                    if (ec.ec_local_vars.size() == 1) {
25✔
574
                        lnav_data.ld_views[LNV_DB].reload_data();
14✔
575
                        ensure_view(&lnav_data.ld_views[LNV_DB]);
14✔
576
                    }
577
                }
578
            }
579
#endif
580
        }
581
    }
582

583
    return Ok(retval);
1,570✔
584
}
1,639✔
585

586
Result<void, lnav::console::user_message>
587
multiline_executor::handle_command(const std::string& cmdline)
216✔
588
{
589
    this->me_last_result = TRY(execute_from_file(this->me_exec_context,
216✔
590
                                                 this->p_source,
591
                                                 this->p_starting_line_number,
592
                                                 cmdline));
593

594
    return Ok();
212✔
595
}
596

597
static Result<std::string, lnav::console::user_message>
598
execute_file_contents(exec_context& ec, const std::filesystem::path& path)
36✔
599
{
600
    static const std::filesystem::path stdin_path("-");
36✔
601
    static const std::filesystem::path dev_stdin_path("/dev/stdin");
36✔
602

603
    FILE* file;
604

605
    if (path == stdin_path || path == dev_stdin_path) {
36✔
606
        if (isatty(STDIN_FILENO)) {
3✔
607
            return ec.make_error("stdin has already been consumed");
×
608
        }
609
        file = stdin;
3✔
610
    } else if ((file = fopen(path.c_str(), "re")) == nullptr) {
33✔
611
        return ec.make_error("unable to open file");
×
612
    }
613

614
    std::string out_name;
36✔
615

616
    auto_mem<char> line;
36✔
617
    size_t line_max_size;
618
    ssize_t line_size;
619
    multiline_executor me(ec, path.string());
36✔
620

621
    ec.ec_local_vars.top()["0"] = path.string();
108✔
622
    ec.ec_path_stack.emplace_back(path.parent_path());
36✔
623
    exec_context::output_guard og(ec);
72✔
624
    while ((line_size = getline(line.out(), &line_max_size, file)) != -1) {
832✔
625
        TRY(me.push_back(string_fragment::from_bytes(line.in(), line_size)));
800✔
626
    }
627

628
    TRY(me.final());
32✔
629
    auto retval = std::move(me.me_last_result);
32✔
630

631
    if (file == stdin) {
32✔
632
        if (isatty(STDOUT_FILENO)) {
3✔
633
            log_perror(dup2(STDOUT_FILENO, STDIN_FILENO));
×
634
        }
635
    } else {
636
        fclose(file);
29✔
637
    }
638
    ec.ec_path_stack.pop_back();
32✔
639

640
    return Ok(retval);
32✔
641
}
36✔
642

643
Result<std::string, lnav::console::user_message>
644
execute_file(exec_context& ec, const std::string& path_and_args)
37✔
645
{
646
    static const intern_string_t SRC = intern_string::lookup("cmdline");
87✔
647

648
    std::string retval, msg;
37✔
649
    shlex lexer(path_and_args);
37✔
650

651
    log_info("Executing file: %s", path_and_args.c_str());
37✔
652

653
    auto split_args_res = lexer.split(scoped_resolver{&ec.ec_local_vars.top()});
37✔
654
    if (split_args_res.isErr()) {
37✔
655
        auto split_err = split_args_res.unwrapErr();
×
656
        auto um = lnav::console::user_message::error(
×
657
                      "unable to parse script command-line")
658
                      .with_reason(split_err.se_error.te_msg)
×
659
                      .with_snippet(lnav::console::snippet::from(
×
660
                          SRC, lexer.to_attr_line(split_err.se_error)))
×
661
                      .move();
×
662

663
        return Err(um);
×
664
    }
665
    auto split_args = split_args_res.unwrap();
37✔
666
    if (split_args.empty()) {
37✔
667
        return ec.make_error("no script specified");
×
668
    }
669

670
    ec.ec_local_vars.emplace();
37✔
671

672
    auto script_name = split_args[0].se_value;
37✔
673
    auto& vars = ec.ec_local_vars.top();
37✔
674
    std::string star, open_error = "file not found";
74✔
675

676
    add_ansi_vars(vars);
37✔
677

678
    vars["#"] = fmt::to_string(split_args.size() - 1);
111✔
679
    for (size_t lpc = 0; lpc < split_args.size(); lpc++) {
114✔
680
        vars[fmt::to_string(lpc)] = split_args[lpc].se_value;
77✔
681
    }
682
    for (size_t lpc = 1; lpc < split_args.size(); lpc++) {
77✔
683
        if (lpc > 1) {
40✔
684
            star.append(" ");
21✔
685
        }
686
        star.append(split_args[lpc].se_value);
40✔
687
    }
688
    vars["__all__"] = star;
37✔
689

690
    std::vector<script_metadata> paths_to_exec;
37✔
691

692
    auto scripts = find_format_scripts(lnav_data.ld_config_paths);
37✔
693
    auto iter = scripts.as_scripts.find(script_name);
37✔
694
    if (iter != scripts.as_scripts.end()) {
37✔
695
        paths_to_exec = iter->second;
26✔
696
    }
697
    if (lnav::filesystem::is_url(script_name)) {
37✔
698
        auto_mem<CURLU> cu(curl_url_cleanup);
×
699
        cu = curl_url();
×
700
        auto set_rc = curl_url_set(cu, CURLUPART_URL, script_name.c_str(), 0);
×
701
        if (set_rc == CURLUE_OK) {
×
702
            auto_mem<char> scheme_part(curl_free);
×
703
            auto get_rc
704
                = curl_url_get(cu, CURLUPART_SCHEME, scheme_part.out(), 0);
×
705
            if (get_rc == CURLUE_OK
×
706
                && string_fragment::from_c_str(scheme_part.in()) == "file")
×
707
            {
708
                auto_mem<char> path_part;
×
709
                auto get_rc
710
                    = curl_url_get(cu, CURLUPART_PATH, path_part.out(), 0);
×
711
                if (get_rc == CURLUE_OK) {
×
712
                    auto rp_res = lnav::filesystem::realpath(path_part.in());
×
713
                    if (rp_res.isOk()) {
×
714
                        struct script_metadata meta;
×
715

716
                        meta.sm_path = rp_res.unwrap();
×
717
                        extract_metadata_from_file(meta);
×
718
                        paths_to_exec.push_back(meta);
×
719
                    }
720
                }
721
            }
722
        }
723
    }
724
    if (script_name == "-" || script_name == "/dev/stdin") {
37✔
725
        paths_to_exec.push_back({script_name, "", "", ""});
3✔
726
    } else if (access(script_name.c_str(), R_OK) == 0) {
34✔
727
        struct script_metadata meta;
7✔
728
        auto rp_res = lnav::filesystem::realpath(script_name);
7✔
729

730
        if (rp_res.isErr()) {
7✔
731
            log_error("unable to get realpath() of %s -- %s",
×
732
                      script_name.c_str(),
733
                      rp_res.unwrapErr().c_str());
734
            meta.sm_path = script_name;
×
735
        } else {
736
            meta.sm_path = rp_res.unwrap();
7✔
737
        }
738
        extract_metadata_from_file(meta);
7✔
739
        paths_to_exec.push_back(meta);
7✔
740
    } else if (errno != ENOENT) {
34✔
741
        open_error = strerror(errno);
×
742
    } else {
743
        auto script_path = std::filesystem::path(script_name);
27✔
744

745
        if (!script_path.is_absolute()) {
27✔
746
            script_path = ec.ec_path_stack.back() / script_path;
27✔
747
        }
748

749
        if (std::filesystem::is_regular_file(script_path)) {
27✔
750
            script_metadata meta;
×
751

752
            meta.sm_path = script_path;
×
753
            extract_metadata_from_file(meta);
×
754
            paths_to_exec.push_back(meta);
×
755
        } else if (errno != ENOENT) {
27✔
756
            open_error = strerror(errno);
×
757
        }
758
    }
27✔
759

760
    if (!paths_to_exec.empty()) {
37✔
761
        for (auto& path_iter : paths_to_exec) {
68✔
762
            if (!ec.ec_output_stack.empty()) {
36✔
763
                ec.ec_output_stack.back().od_format
36✔
764
                    = path_iter.sm_output_format;
36✔
765
                log_info("%s: setting out format for '%s' to %d",
36✔
766
                         script_name.c_str(),
767
                         ec.ec_output_stack.back().od_name.c_str(),
768
                         ec.ec_output_stack.back().od_format);
769
            }
770
            retval = TRY(execute_file_contents(ec, path_iter.sm_path));
36✔
771
        }
772
    }
773
    ec.ec_local_vars.pop();
33✔
774

775
    if (paths_to_exec.empty()) {
33✔
776
        return ec.make_error(
777
            "unknown script -- {} -- {}", script_name, open_error);
1✔
778
    }
779

780
    return Ok(retval);
32✔
781
}
52✔
782

783
Result<std::string, lnav::console::user_message>
784
execute_from_file(exec_context& ec,
216✔
785
                  const std::string& src,
786
                  int line_number,
787
                  const std::string& cmdline)
788
{
789
    std::string retval, alt_msg;
216✔
790
    auto _sg
791
        = ec.enter_source(intern_string::lookup(src), line_number, cmdline);
216✔
792

793
    lnav_data.ld_view_stack.top() | [&ec](auto* tc) {
216✔
794
        ec.ec_top_line = tc->get_selection().value_or(0_vl);
216✔
795
    };
216✔
796
    switch (cmdline[0]) {
216✔
797
        case ':':
95✔
798
            retval = TRY(execute_command(ec, cmdline.substr(1)));
95✔
799
            break;
95✔
800
        case '/':
1✔
801
            execute_search(cmdline.substr(1));
1✔
802
            break;
1✔
803
        case ';': {
118✔
804
            if (!ec.ec_msg_callback_stack.empty()) {
118✔
805
                auto src_slash = src.rfind('/');
114✔
806
                auto cmd_al
807
                    = attr_line_t(cmdline.substr(0, cmdline.find('\n')));
114✔
808
                readline_lnav_highlighter(cmd_al, std::nullopt);
114✔
809
                const auto um = lnav::console::user_message::info(
114✔
810
                                    attr_line_t("Executing command at ")
114✔
811
                                        .append(lnav::roles::file(
114✔
812
                                            src_slash != std::string::npos
813
                                                ? src.substr(src_slash + 1)
228✔
814
                                                : src))
815
                                        .append(":")
114✔
816
                                        .append(lnav::roles::number(
228✔
817
                                            fmt::to_string(line_number)))
228✔
818
                                        .append(" \u2014 ")
114✔
819
                                        .append(cmd_al))
114✔
820
                                    .move();
114✔
821
                ec.ec_msg_callback_stack.back()(um);
114✔
822
            }
114✔
823

824
            setup_logline_table(ec);
118✔
825
            retval = TRY(execute_sql(ec, cmdline.substr(1), alt_msg));
118✔
826
            break;
114✔
827
        }
828
        case '|':
2✔
829
            retval = TRY(execute_file(ec, cmdline.substr(1)));
2✔
830
            break;
2✔
831
        default:
×
832
            retval = TRY(execute_command(ec, cmdline));
×
833
            break;
×
834
    }
835

836
    log_info(
212✔
837
        "%s:%d:execute result -- %s", src.c_str(), line_number, retval.c_str());
838

839
    return Ok(retval);
212✔
840
}
216✔
841

842
Result<std::string, lnav::console::user_message>
843
execute_any(exec_context& ec, const std::string& cmdline_with_mode)
34✔
844
{
845
    if (cmdline_with_mode.empty()) {
34✔
846
        auto um = lnav::console::user_message::error("empty command")
×
847
                      .with_help(
×
848
                          "a command should start with ':', ';', '/', '|' and "
849
                          "followed by the operation to perform")
850
                      .move();
×
851
        if (!ec.ec_source.empty()) {
×
852
            um.with_snippet(ec.ec_source.back());
×
853
        }
854
        return Err(um);
×
855
    }
856

857
    std::string retval, alt_msg, cmdline = cmdline_with_mode.substr(1);
34✔
858
    auto _cleanup = finally([&ec] {
34✔
859
        if (ec.is_read_write() &&
34✔
860
            // only rebuild in a script or non-interactive mode so we don't
861
            // block the UI.
862
            lnav_data.ld_flags & LNF_HEADLESS)
×
863
        {
864
            rescan_files();
×
865
            wait_for_pipers(std::nullopt);
×
866
            rebuild_indexes_repeatedly();
×
867
        }
868
    });
68✔
869

870
    switch (cmdline_with_mode[0]) {
34✔
871
        case ':':
×
872
            retval = TRY(execute_command(ec, cmdline));
×
873
            break;
×
874
        case '/':
×
875
            execute_search(cmdline);
×
876
            break;
×
877
        case ';':
30✔
878
            setup_logline_table(ec);
30✔
879
            retval = TRY(execute_sql(ec, cmdline, alt_msg));
30✔
880
            break;
30✔
881
        case '|': {
4✔
882
            retval = TRY(execute_file(ec, cmdline));
4✔
883
            break;
4✔
884
        }
885
        default:
×
886
            retval = TRY(execute_command(ec, cmdline));
×
887
            break;
×
888
    }
889

890
    return Ok(retval);
34✔
891
}
34✔
892

893
void
894
execute_init_commands(
568✔
895
    exec_context& ec,
896
    std::vector<std::pair<Result<std::string, lnav::console::user_message>,
897
                          std::string>>& msgs)
898
{
899
    if (lnav_data.ld_cmd_init_done) {
568✔
900
        return;
×
901
    }
902

903
    std::string out_name;
568✔
904
    std::optional<exec_context::output_t> ec_out;
568✔
905
    auto_fd fd_copy;
568✔
906
    auto& dls = *(ec.ec_label_source_stack.back());
568✔
907
    int option_index = 1;
568✔
908

909
    {
910
        log_info("Executing initial commands");
568✔
911
        exec_context::output_guard og(ec, out_name, ec_out);
568✔
912

913
        for (auto& cmd : lnav_data.ld_commands) {
1,498✔
914
            static const auto COMMAND_OPTION_SRC
915
                = intern_string::lookup("command-option");
1,924✔
916

917
            std::string alt_msg;
930✔
918
            auto has_db_query = false;
930✔
919

920
            wait_for_children();
930✔
921

922
            lnav_data.ld_view_stack.top() | [&ec](auto* tc) {
930✔
923
                ec.ec_top_line = tc->get_selection().value_or(0_vl);
930✔
924
            };
930✔
925
            log_debug("init cmd: %s", cmd.c_str());
930✔
926
            {
927
                auto _sg
928
                    = ec.enter_source(COMMAND_OPTION_SRC, option_index++, cmd);
930✔
929
                switch (cmd.at(0)) {
930✔
930
                    case ':':
568✔
931
                        msgs.emplace_back(execute_command(ec, cmd.substr(1)),
568✔
932
                                          alt_msg);
933
                        break;
568✔
934
                    case '/':
6✔
935
                        execute_search(cmd.substr(1));
6✔
936
                        break;
6✔
937
                    case ';':
330✔
938
                        setup_logline_table(ec);
330✔
939
                        msgs.emplace_back(
330✔
940
                            execute_sql(ec, cmd.substr(1), alt_msg), alt_msg);
660✔
941
                        has_db_query = true;
330✔
942
                        break;
330✔
943
                    case '|':
26✔
944
                        msgs.emplace_back(execute_file(ec, cmd.substr(1)),
26✔
945
                                          alt_msg);
946
                        break;
26✔
947
                }
948

949
                rescan_files();
930✔
950
                auto deadline = ui_clock::now();
930✔
951
                if (lnav_data.ld_flags & LNF_HEADLESS) {
930✔
952
                    deadline += 5s;
930✔
953
                } else {
954
                    deadline += 500ms;
×
955
                }
956
                wait_for_pipers(deadline);
930✔
957
                rebuild_indexes_repeatedly();
930✔
958
            }
930✔
959
            if (has_db_query && !dls.dls_headers.empty()
330✔
960
                && lnav_data.ld_view_stack.size() == 1)
1,260✔
961
            {
962
                lnav_data.ld_views[LNV_DB].reload_data();
9✔
963
                ensure_view(LNV_DB);
9✔
964
            }
965
        }
930✔
966
    }
568✔
967
    lnav_data.ld_commands.clear();
568✔
968
    lnav_data.ld_cmd_init_done = true;
568✔
969
}
568✔
970

971
int
972
sql_callback(exec_context& ec, sqlite3_stmt* stmt)
4,053✔
973
{
974
    auto& dls = *(ec.ec_label_source_stack.back());
4,053✔
975
    const int ncols = sqlite3_column_count(stmt);
4,053✔
976

977
    if (!sqlite3_stmt_busy(stmt)) {
4,053✔
978
        dls.clear();
1,470✔
979

980
        for (int lpc = 0; lpc < ncols; lpc++) {
4,417✔
981
            const int type = sqlite3_column_type(stmt, lpc);
2,947✔
982
            std::string colname = sqlite3_column_name(stmt, lpc);
2,947✔
983

984
            dls.push_header(colname, type);
2,947✔
985
        }
2,947✔
986
        return 0;
1,470✔
987
    }
988

989
    int retval = 0;
2,583✔
990
    auto set_vars = dls.dls_row_cursors.empty();
2,583✔
991

992
    if (dls.dls_row_cursors.empty()) {
2,583✔
993
        dls.dls_query_start = std::chrono::steady_clock::now();
1,420✔
994
        for (int lpc = 0; lpc < ncols; lpc++) {
4,185✔
995
            int type = sqlite3_column_type(stmt, lpc);
2,765✔
996
            std::string colname = sqlite3_column_name(stmt, lpc);
2,765✔
997

998
            bool graphable = (type == SQLITE_INTEGER || type == SQLITE_FLOAT);
2,765✔
999
            auto& hm = dls.dls_headers[lpc];
2,765✔
1000
            hm.hm_column_type = type;
2,765✔
1001
            if (lnav_data.ld_db_key_names.count(colname) > 0) {
2,765✔
1002
                hm.hm_graphable = false;
536✔
1003
            } else if (graphable) {
2,229✔
1004
                dls.set_col_as_graphable(lpc);
641✔
1005
            }
1006
        }
2,765✔
1007
    }
1008

1009
    dls.dls_row_cursors.emplace_back(dls.dls_cell_container.end_cursor());
2,583✔
1010
    dls.dls_push_column = 0;
2,583✔
1011
    for (int lpc = 0; lpc < ncols; lpc++) {
11,458✔
1012
        const auto value_type = sqlite3_column_type(stmt, lpc);
8,875✔
1013
        db_label_source::column_value_t value;
8,875✔
1014
        auto& hm = dls.dls_headers[lpc];
8,875✔
1015

1016
        switch (value_type) {
8,875✔
1017
            case SQLITE_INTEGER:
2,587✔
1018
                value = (int64_t) sqlite3_column_int64(stmt, lpc);
2,587✔
1019
                hm.hm_align = text_align_t::end;
2,587✔
1020
                break;
2,587✔
1021
            case SQLITE_FLOAT:
231✔
1022
                value = sqlite3_column_double(stmt, lpc);
231✔
1023
                hm.hm_align = text_align_t::end;
231✔
1024
                break;
231✔
1025
            case SQLITE_NULL:
2,088✔
1026
                value = null_value_t{};
2,088✔
1027
                break;
2,088✔
1028
            default: {
3,969✔
1029
                auto frag = string_fragment::from_bytes(
3,969✔
1030
                    sqlite3_column_text(stmt, lpc),
1031
                    sqlite3_column_bytes(stmt, lpc));
3,969✔
1032
                if (!frag.empty()) {
3,969✔
1033
                    if (isdigit(frag[0])) {
3,909✔
1034
                        hm.hm_align = text_align_t::end;
1,365✔
1035
                        if (!hm.hm_graphable.has_value()) {
1,365✔
1036
                            auto split_res = humanize::try_from<double>(frag);
241✔
1037
                            if (split_res.has_value()) {
241✔
1038
                                dls.set_col_as_graphable(lpc);
59✔
1039
                            } else {
1040
                                hm.hm_graphable = false;
182✔
1041
                            }
1042
                        }
1043
                    } else if (!hm.hm_graphable.has_value()) {
2,544✔
1044
                        hm.hm_graphable = false;
1,016✔
1045
                    }
1046
                }
1047
                value = frag;
3,969✔
1048
                break;
3,969✔
1049
            }
1050
        }
1051
        dls.push_column(value);
8,875✔
1052
        if ((hm.hm_column_type == SQLITE_TEXT
8,875✔
1053
             || hm.hm_column_type == SQLITE_NULL)
4,825✔
1054
            && hm.hm_sub_type == 0)
6,092✔
1055
        {
1056
            switch (value_type) {
5,990✔
1057
                case SQLITE_TEXT:
3,869✔
1058
                    auto* raw_value = sqlite3_column_value(stmt, lpc);
3,869✔
1059
                    hm.hm_column_type = SQLITE_TEXT;
3,869✔
1060
                    hm.hm_sub_type = sqlite3_value_subtype(raw_value);
3,869✔
1061
                    break;
3,869✔
1062
            }
1063
        }
1064
        if (set_vars && !ec.ec_local_vars.empty() && !ec.ec_dry_run) {
8,875✔
1065
            if (sql_ident_needs_quote(hm.hm_name.c_str())) {
2,765✔
1066
                continue;
1,144✔
1067
            }
1068
            auto& vars = ec.ec_local_vars.top();
1,621✔
1069

1070
            vars[hm.hm_name] = value.match(
3,242✔
1071
                [](const string_fragment& sf) {
×
1072
                    return scoped_value_t{sf.to_string()};
712✔
1073
                },
1074
                [](int64_t i) { return scoped_value_t{i}; },
460✔
1075
                [](double d) { return scoped_value_t{d}; },
15✔
1076
                [](null_value_t) { return scoped_value_t{null_value_t{}}; });
3,676✔
1077
        }
1078
    }
8,875✔
1079

1080
    return retval;
2,583✔
1081
}
1082

1083
int
1084
internal_sql_callback(exec_context& ec, sqlite3_stmt* stmt)
14✔
1085
{
1086
    if (!sqlite3_stmt_busy(stmt)) {
14✔
1087
        return 0;
7✔
1088
    }
1089

1090
    const int ncols = sqlite3_column_count(stmt);
7✔
1091

1092
    auto& vars = ec.ec_local_vars.top();
7✔
1093

1094
    for (int lpc = 0; lpc < ncols; lpc++) {
15✔
1095
        const char* column_name = sqlite3_column_name(stmt, lpc);
8✔
1096

1097
        if (sql_ident_needs_quote(column_name)) {
8✔
1098
            continue;
×
1099
        }
1100

1101
        auto value_type = sqlite3_column_type(stmt, lpc);
8✔
1102
        scoped_value_t value;
8✔
1103
        switch (value_type) {
8✔
1104
            case SQLITE_INTEGER:
×
1105
                value = (int64_t) sqlite3_column_int64(stmt, lpc);
×
1106
                break;
×
1107
            case SQLITE_FLOAT:
×
1108
                value = sqlite3_column_double(stmt, lpc);
×
1109
                break;
×
1110
            case SQLITE_NULL:
×
1111
                value = null_value_t{};
×
1112
                break;
×
1113
            default:
8✔
1114
                value
1115
                    = std::string((const char*) sqlite3_column_text(stmt, lpc),
16✔
1116
                                  sqlite3_column_bytes(stmt, lpc));
16✔
1117
                break;
8✔
1118
        }
1119
        vars[column_name] = value;
8✔
1120
    }
8✔
1121

1122
    return 0;
7✔
1123
}
1124

1125
std::future<std::string>
1126
pipe_callback(exec_context& ec, const std::string& cmdline, auto_fd& fd)
7✔
1127
{
1128
    static auto& prompt = lnav::prompt::get();
7✔
1129
    auto out = ec.get_output();
7✔
1130

1131
    if (out) {
7✔
1132
        FILE* file = *out;
7✔
1133

1134
        return std::async(std::launch::async, [fd = std::move(fd), file]() {
14✔
1135
            char buffer[1024];
1136
            ssize_t rc;
1137

1138
            if (file == stdout) {
7✔
1139
                lnav_data.ld_stdout_used = true;
7✔
1140
            }
1141

1142
            while ((rc = read(fd, buffer, sizeof(buffer))) > 0) {
14✔
1143
                fwrite(buffer, rc, 1, file);
7✔
1144
            }
1145

1146
            return std::string();
14✔
1147
        });
7✔
1148
    }
1149
    std::error_code errc;
×
1150
    std::filesystem::create_directories(lnav::paths::workdir(), errc);
×
1151
    auto open_temp_res = lnav::filesystem::open_temp_file(lnav::paths::workdir()
×
1152
                                                          / "exec.XXXXXX");
×
1153
    if (open_temp_res.isErr()) {
×
1154
        return lnav::futures::make_ready_future(
1155
            fmt::format(FMT_STRING("error: cannot open temp file -- {}"),
×
1156
                        open_temp_res.unwrapErr()));
×
1157
    }
1158

1159
    auto tmp_pair = open_temp_res.unwrap();
×
1160

1161
    auto reader = std::thread(
1162
        [in_fd = std::move(fd), out_fd = std::move(tmp_pair.second)]() {
×
1163
            char buffer[1024];
1164
            ssize_t rc;
1165

1166
            while ((rc = read(in_fd, buffer, sizeof(buffer))) > 0) {
×
1167
                write(out_fd, buffer, rc);
×
1168
            }
1169
        });
×
1170
    reader.detach();
×
1171

1172
    static int exec_count = 0;
1173
    auto desc
1174
        = fmt::format(FMT_STRING("exec-{}-output {}"), exec_count++, cmdline);
×
1175
    lnav_data.ld_active_files.fc_file_names[tmp_pair.first]
×
1176
        .with_filename(desc)
×
1177
        .with_include_in_session(false)
×
1178
        .with_detect_format(false)
×
1179
        .with_init_location(0_vl);
×
1180
    lnav_data.ld_files_to_front.emplace_back(desc);
×
1181
    prompt.p_editor.set_alt_value(HELP_MSG_1(X, "to close the file"));
×
1182

1183
    return lnav::futures::make_ready_future(std::string());
×
1184
}
1185

1186
void
1187
add_global_vars(exec_context& ec)
638✔
1188
{
1189
    for (const auto& iter : lnav_config.lc_global_vars) {
10,214✔
1190
        shlex subber(iter.second);
9,576✔
1191
        std::string str;
9,576✔
1192

1193
        if (!subber.eval(str, scoped_resolver{&ec.ec_global_vars})) {
9,576✔
1194
            log_error("Unable to evaluate global variable value: %s",
×
1195
                      iter.second.c_str());
1196
            continue;
×
1197
        }
1198

1199
        ec.ec_global_vars[iter.first] = str;
9,576✔
1200
    }
9,576✔
1201
}
638✔
1202

1203
void
1204
exec_context::set_output(const std::string& name,
570✔
1205
                         FILE* file,
1206
                         int (*closer)(FILE*))
1207
{
1208
    log_info("redirecting command output to: %s", name.c_str());
570✔
1209
    this->ec_output_stack.back().od_output | [](auto out) {
570✔
1210
        if (out.second != nullptr) {
×
1211
            out.second(out.first);
×
1212
        }
1213
    };
1214
    this->ec_output_stack.back()
570✔
1215
        = output_desc{name, std::make_pair(file, closer)};
1,140✔
1216
}
570✔
1217

1218
void
1219
exec_context::clear_output()
70✔
1220
{
1221
    log_info("redirecting command output to screen");
70✔
1222
    this->ec_output_stack.back().od_output | [](auto out) {
70✔
1223
        if (out.second != nullptr) {
34✔
1224
            out.second(out.first);
34✔
1225
        }
1226
    };
34✔
1227
    this->ec_output_stack.back().od_name = "default";
70✔
1228
    this->ec_output_stack.back().od_output = std::nullopt;
70✔
1229
}
70✔
1230

1231
exec_context::exec_context(logline_value_vector* line_values,
3,407✔
1232
                           sql_callback_t sql_callback,
1233
                           pipe_callback_t pipe_callback)
3,407✔
1234
    : ec_line_values(line_values),
3,407✔
1235
      ec_accumulator(std::make_unique<attr_line_t>()),
3,407✔
1236
      ec_sql_callback(sql_callback), ec_pipe_callback(pipe_callback)
6,814✔
1237
{
1238
    this->ec_local_vars.push(std::map<std::string, scoped_value_t>());
3,407✔
1239
    this->ec_path_stack.emplace_back(".");
3,407✔
1240
    this->ec_output_stack.emplace_back("screen", std::nullopt);
3,407✔
1241
}
3,407✔
1242

1243
Result<std::string, lnav::console::user_message>
1244
exec_context::execute(source_location loc, const std::string& cmdline)
2✔
1245
{
1246
    static auto& prompt = lnav::prompt::get();
2✔
1247
    static const auto& dls = lnav_data.ld_db_row_source;
1248

1249
    lnav::textinput::history::op_guard hist_guard;
2✔
1250
    auto sg = this->enter_source(loc, cmdline);
2✔
1251

1252
    auto before_dls_gen = dls.dls_generation;
2✔
1253
    if (this->get_provenance<mouse_input>() && !prompt.p_editor.is_enabled()) {
2✔
1254
        auto& hist = prompt.get_history_for(cmdline[0]);
×
1255
        hist_guard = hist.start_operation(cmdline.substr(1));
×
1256
    }
1257

1258
    auto exec_res = execute_any(*this, cmdline);
2✔
1259
    if (exec_res.isErr()) {
2✔
1260
        hist_guard.og_status = log_level_t::LEVEL_ERROR;
×
1261
        if (!this->ec_msg_callback_stack.empty()) {
×
1262
            this->ec_msg_callback_stack.back()(exec_res.unwrapErr());
×
1263
        }
1264
    } else {
1265
        if (before_dls_gen != dls.dls_generation
4✔
1266
            && dls.dls_row_cursors.size() > 1)
2✔
1267
        {
1268
            ensure_view(LNV_DB);
×
1269
        }
1270
    }
1271

1272
    return exec_res;
4✔
1273
}
2✔
1274

1275
void
1276
exec_context::add_error_context(lnav::console::user_message& um)
69✔
1277
{
1278
    switch (um.um_level) {
69✔
1279
        case lnav::console::user_message::level::raw:
×
1280
        case lnav::console::user_message::level::info:
1281
        case lnav::console::user_message::level::ok:
1282
            return;
×
1283
        default:
69✔
1284
            break;
69✔
1285
    }
1286

1287
    if (!this->get_provenance<keyboard_input>() && um.um_snippets.empty()) {
69✔
1288
        um.with_snippets(this->ec_source);
30✔
1289
        um.remove_internal_snippets();
30✔
1290
    }
1291

1292
    if (this->ec_current_help != nullptr && um.um_help.empty()) {
69✔
1293
        attr_line_t help;
31✔
1294

1295
        format_help_text_for_term(*this->ec_current_help,
31✔
1296
                                  70,
1297
                                  help,
1298
                                  help_text_content::synopsis_and_summary);
1299
        um.with_help(help);
31✔
1300
    }
31✔
1301
}
1302

1303
exec_context::sql_callback_guard
1304
exec_context::push_callback(sql_callback_t cb)
5✔
1305
{
1306
    return sql_callback_guard(*this, cb);
5✔
1307
}
1308

1309
exec_context::source_guard
1310
exec_context::enter_source(source_location loc, const std::string& content)
2,360✔
1311
{
1312
    attr_line_t content_al{content};
2,360✔
1313
    content_al.with_attr_for_all(VC_ROLE.value(role_t::VCR_QUOTED_CODE));
2,360✔
1314
    readline_lnav_highlighter(content_al, -1);
2,360✔
1315
    this->ec_source.emplace_back(lnav::console::snippet::from(loc, content_al));
2,360✔
1316
    return {this};
4,720✔
1317
}
2,360✔
1318

1319
exec_context::output_guard::output_guard(exec_context& context,
636✔
1320
                                         std::string name,
1321
                                         const std::optional<output_t>& file,
1322
                                         text_format_t tf)
636✔
1323
    : sg_context(context), sg_active(!name.empty())
636✔
1324
{
1325
    if (name.empty()) {
636✔
1326
        return;
568✔
1327
    }
1328
    if (file) {
68✔
1329
        log_info("redirecting command output to: %s", name.c_str());
32✔
1330
    } else if (!context.ec_output_stack.empty()) {
36✔
1331
        tf = context.ec_output_stack.back().od_format;
36✔
1332
    }
1333
    context.ec_output_stack.emplace_back(std::move(name), file, tf);
68✔
1334
}
1335

1336
exec_context::output_guard::~output_guard()
636✔
1337
{
1338
    if (this->sg_active) {
636✔
1339
        this->sg_context.clear_output();
68✔
1340
        this->sg_context.ec_output_stack.pop_back();
68✔
1341
    }
1342
}
636✔
1343
exec_context::sql_callback_guard::sql_callback_guard(exec_context& context,
5✔
1344
                                                     sql_callback_t cb)
5✔
1345
    : scg_context(context), scg_old_callback(context.ec_sql_callback)
5✔
1346
{
1347
    context.ec_sql_callback = cb;
5✔
1348
}
5✔
1349
exec_context::sql_callback_guard::sql_callback_guard(sql_callback_guard&& other)
×
1350
    : scg_context(other.scg_context),
×
1351
      scg_old_callback(std::exchange(other.scg_old_callback, nullptr))
×
1352
{
1353
}
1354
exec_context::sql_callback_guard::~sql_callback_guard()
5✔
1355
{
1356
    if (this->scg_old_callback != nullptr) {
5✔
1357
        this->scg_context.ec_sql_callback = this->scg_old_callback;
5✔
1358
    }
1359
}
5✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc