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

tstack / lnav / 18686220951-2595

21 Oct 2025 01:52PM UTC coverage: 70.021% (+0.06%) from 69.965%
18686220951-2595

push

github

tstack
[tidy] start to replace strerror()

16 of 38 new or added lines in 11 files covered. (42.11%)

3 existing lines in 2 files now uncovered.

50860 of 72635 relevant lines covered (70.02%)

423564.58 hits per line

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

82.54
/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 "breadcrumb_curses.hh"
44
#include "config.h"
45
#include "curl_looper.hh"
46
#include "db_sub_source.hh"
47
#include "help_text_formatter.hh"
48
#include "lnav.hh"
49
#include "lnav.indexing.hh"
50
#include "lnav.prompt.hh"
51
#include "lnav_config.hh"
52
#include "lnav_util.hh"
53
#include "log_format_loader.hh"
54
#include "prql-modules.h"
55
#include "readline_highlighters.hh"
56
#include "service_tags.hh"
57
#include "shlex.hh"
58
#include "sql_help.hh"
59
#include "sql_util.hh"
60
#include "vtab_module.hh"
61

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

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

69
exec_context INIT_EXEC_CONTEXT;
70

71
static sig_atomic_t sql_counter = 0;
72

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

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

84
    if (ui_periodic_timer::singleton().time_to_update(sql_counter)) {
15✔
85
        auto* breadcrumb_view = injector::get<breadcrumb_curses*>();
9✔
86
        breadcrumb_view->set_enabled(false);
9✔
87
        lnav_data.ld_status[LNS_TOP].set_enabled(false);
9✔
88
        lnav_data.ld_view_stack.top() |
9✔
89
            [](auto* tc) { tc->set_enabled(false); };
5✔
90
        ssize_t total = lnav_data.ld_log_source.text_line_count();
9✔
91
        off_t off = lc.lc_curr_line;
9✔
92

93
        if (off >= 0 && off <= total) {
9✔
94
            lnav_data.ld_bottom_source.update_loading(off, total);
9✔
95
            lnav_data.ld_status[LNS_BOTTOM].set_needs_update();
9✔
96
        }
97
        lnav::prompt::get().p_editor.clear_alt_value();
9✔
98
        auto refresh_res
99
            = lnav_data.ld_status_refresher(lnav::func::op_type::blocking);
9✔
100
        if (refresh_res == lnav::progress_result_t::interrupt) {
9✔
101
            return 1;
×
102
        }
103
    }
104

105
    return 0;
15✔
106
}
107

108
void
109
sql_progress_finished()
1,679✔
110
{
111
    if (sql_counter == 0) {
1,679✔
112
        return;
1,670✔
113
    }
114

115
    sql_counter = 0;
9✔
116

117
    if (lnav_data.ld_window == nullptr) {
9✔
118
        return;
×
119
    }
120

121
    auto* breadcrumb_view = injector::get<breadcrumb_curses*>();
9✔
122
    breadcrumb_view->set_enabled(true);
9✔
123
    lnav_data.ld_status[LNS_TOP].set_enabled(true);
9✔
124
    lnav_data.ld_view_stack.top() | [](auto* tc) { tc->set_enabled(true); };
14✔
125
    lnav_data.ld_bottom_source.update_loading(0, 0);
9✔
126
    lnav_data.ld_status[LNS_BOTTOM].set_needs_update();
9✔
127
    lnav_data.ld_status_refresher(lnav::func::op_type::blocking);
9✔
128
    lnav_data.ld_views[LNV_DB].redo_search();
9✔
129
}
130

131
static Result<std::string, lnav::console::user_message> execute_from_file(
132
    exec_context& ec,
133
    const std::string& src,
134
    int line_number,
135
    const std::string& cmdline);
136

137
Result<std::string, lnav::console::user_message>
138
execute_command(exec_context& ec, const std::string& cmdline)
710✔
139
{
140
    static auto op = lnav_operation{__FUNCTION__};
710✔
141

142
    auto op_guard = lnav_opid_guard::internal(op);
710✔
143
    std::vector<std::string> args;
710✔
144

145
    log_info("Executing command: %s", cmdline.c_str());
710✔
146

147
    split_ws(cmdline, args);
710✔
148

149
    if (!args.empty()) {
710✔
150
        readline_context::command_map_t::iterator iter;
710✔
151

152
        if ((iter = lnav_commands.find(args[0])) == lnav_commands.end()) {
710✔
153
            return ec.make_error("unknown command - {}", args[0]);
×
154
        }
155

156
        ec.ec_current_help = &iter->second->c_help;
710✔
157
        try {
158
            auto retval = iter->second->c_func(ec, cmdline, args);
710✔
159
            if (retval.isErr()) {
710✔
160
                auto um = retval.unwrapErr();
43✔
161

162
                ec.add_error_context(um);
43✔
163
                ec.ec_current_help = nullptr;
43✔
164
                return Err(um);
43✔
165
            }
43✔
166
            ec.ec_current_help = nullptr;
667✔
167

168
            return retval;
667✔
169
        } catch (const std::exception& e) {
710✔
170
            auto um = lnav::console::user_message::error(
×
171
                          attr_line_t("unexpected error while executing: ")
×
172
                              .append(lnav::roles::quoted_code(cmdline)))
×
173
                          .with_reason(e.what());
×
174
            return Err(um);
×
175
        }
×
176
    }
177

178
    return ec.make_error("no command to execute");
×
179
}
710✔
180

181
static Result<std::map<std::string, scoped_value_t>,
182
              lnav::console::user_message>
183
bind_sql_parameters(exec_context& ec, sqlite3_stmt* stmt)
1,672✔
184
{
185
    std::map<std::string, scoped_value_t> retval;
1,672✔
186
    auto param_count = sqlite3_bind_parameter_count(stmt);
1,672✔
187
    for (int lpc = 0; lpc < param_count; lpc++) {
1,870✔
188
        std::map<std::string, std::string>::iterator ov_iter;
199✔
189
        const auto* name = sqlite3_bind_parameter_name(stmt, lpc + 1);
199✔
190
        if (name == nullptr) {
199✔
191
            auto um
192
                = lnav::console::user_message::error("invalid SQL statement")
2✔
193
                      .with_reason(
2✔
194
                          "using a question-mark (?) for bound variables "
195
                          "is not supported, only named bound parameters "
196
                          "are supported")
197
                      .with_help(
2✔
198
                          "named parameters start with a dollar-sign "
199
                          "($) or colon (:) followed by the variable name")
200
                      .move();
1✔
201
            ec.add_error_context(um);
1✔
202

203
            return Err(um);
1✔
204
        }
1✔
205

206
        if (name[0] == '$') {
198✔
207
            const auto& lvars = ec.ec_local_vars.top();
169✔
208
            const auto& gvars = ec.ec_global_vars;
169✔
209
            std::map<std::string, scoped_value_t>::const_iterator local_var,
169✔
210
                global_var;
169✔
211
            const char* env_value;
212

213
            if (lnav_data.ld_window) {
169✔
214
                char buf[32];
215
                unsigned int lines, cols;
216

217
                ncplane_dim_yx(lnav_data.ld_window, &lines, &cols);
36✔
218
                if (strcmp(name, "$LINES") == 0) {
36✔
219
                    snprintf(buf, sizeof(buf), "%d", lines);
×
220
                    sqlite3_bind_text(stmt, lpc + 1, buf, -1, SQLITE_TRANSIENT);
×
221
                } else if (strcmp(name, "$COLS") == 0) {
36✔
222
                    snprintf(buf, sizeof(buf), "%d", cols);
×
223
                    sqlite3_bind_text(stmt, lpc + 1, buf, -1, SQLITE_TRANSIENT);
×
224
                }
225
            }
226

227
            if ((local_var = lvars.find(&name[1])) != lvars.end()) {
507✔
228
                mapbox::util::apply_visitor(
138✔
229
                    sqlitepp::bind_visitor(stmt, lpc + 1), local_var->second);
138✔
230
                retval[name] = local_var->second;
414✔
231
            } else if ((global_var = gvars.find(&name[1])) != gvars.end()) {
93✔
232
                mapbox::util::apply_visitor(
12✔
233
                    sqlitepp::bind_visitor(stmt, lpc + 1), global_var->second);
12✔
234
                retval[name] = global_var->second;
36✔
235
            } else if ((env_value = getenv(&name[1])) != nullptr) {
19✔
236
                sqlite3_bind_text(stmt, lpc + 1, env_value, -1, SQLITE_STATIC);
3✔
237
                retval[name] = string_fragment::from_c_str(env_value);
9✔
238
            }
239
        } else if (name[0] == ':' && ec.ec_line_values != nullptr) {
29✔
240
            for (auto& lv : ec.ec_line_values->lvv_values) {
159✔
241
                if (lv.lv_meta.lvm_name != &name[1]) {
130✔
242
                    continue;
101✔
243
                }
244
                switch (lv.lv_meta.lvm_kind) {
29✔
245
                    case value_kind_t::VALUE_BOOLEAN:
×
246
                        sqlite3_bind_int64(stmt, lpc + 1, lv.lv_value.i);
×
247
                        retval[name] = fmt::to_string(lv.lv_value.i);
×
248
                        break;
×
249
                    case value_kind_t::VALUE_FLOAT:
×
250
                        sqlite3_bind_double(stmt, lpc + 1, lv.lv_value.d);
×
251
                        retval[name] = fmt::to_string(lv.lv_value.d);
×
252
                        break;
×
253
                    case value_kind_t::VALUE_INTEGER:
×
254
                        sqlite3_bind_int64(stmt, lpc + 1, lv.lv_value.i);
×
255
                        retval[name] = fmt::to_string(lv.lv_value.i);
×
256
                        break;
×
257
                    case value_kind_t::VALUE_NULL:
×
258
                        sqlite3_bind_null(stmt, lpc + 1);
×
259
                        retval[name] = string_fragment::from_c_str(
×
260
                            db_label_source::NULL_STR);
×
261
                        break;
×
262
                    default:
29✔
263
                        sqlite3_bind_text(stmt,
29✔
264
                                          lpc + 1,
265
                                          lv.text_value(),
266
                                          lv.text_length(),
29✔
267
                                          SQLITE_TRANSIENT);
268
                        retval[name] = lv.to_string();
87✔
269
                        break;
29✔
270
                }
271
            }
272
        } else {
29✔
273
            sqlite3_bind_null(stmt, lpc + 1);
×
274
            log_warning("Could not bind variable: %s", name);
×
275
            retval[name]
×
276
                = string_fragment::from_c_str(db_label_source::NULL_STR);
×
277
        }
278
    }
279

280
    return Ok(retval);
1,671✔
281
}
1,672✔
282

283
static void
284
execute_search(const std::string& search_cmd)
7✔
285
{
286
    textview_curses* tc = get_textview_for_mode(lnav_data.ld_mode);
7✔
287
    auto search_term = string_fragment(search_cmd)
7✔
288
                           .find_right_boundary(0, string_fragment::tag1{'\n'})
7✔
289
                           .to_string();
7✔
290
    tc->execute_search(search_term);
7✔
291
}
7✔
292

293
Result<std::string, lnav::console::user_message>
294
execute_sql(exec_context& ec, const std::string& sql, std::string& alt_msg)
1,687✔
295
{
296
    static auto op = lnav_operation{__FUNCTION__};
1,687✔
297

298
    auto op_guard = lnav_opid_guard::internal(op);
1,687✔
299
    auto_mem<sqlite3_stmt> stmt(sqlite3_finalize);
1,687✔
300
    timeval start_tv, end_tv;
301
    std::string stmt_str = trim(sql);
1,687✔
302
    std::string retval;
1,687✔
303
    int retcode = SQLITE_OK;
1,687✔
304

305
    if (lnav::sql::is_prql(stmt_str)) {
1,687✔
306
        log_info("compiling PRQL: %s", stmt_str.c_str());
42✔
307

308
#if HAVE_RUST_DEPS
309
        extern rust::Vec<lnav_rs_ext::SourceTreeElement> sqlite_extension_prql;
310
        auto opts = lnav_rs_ext::Options{true, "sql.sqlite", true};
42✔
311

312
        auto tree = sqlite_extension_prql;
42✔
313
        for (const auto& mod : lnav_prql_modules) {
126✔
314
            log_debug("lnav_rs_ext adding mod %s", mod.get_name());
84✔
315
            tree.emplace_back(lnav_rs_ext::SourceTreeElement{
168✔
316
                mod.get_name().data(),
84✔
317
                mod.to_string_fragment_producer()->to_string(),
168✔
318
            });
319
        }
320
        tree.emplace_back(lnav_rs_ext::SourceTreeElement{"", stmt_str});
42✔
321
        log_debug("BEGIN compiling tree");
42✔
322
        auto cr = lnav_rs_ext::compile_tree(tree, opts);
42✔
323
        log_debug("END compiling tree");
42✔
324

325
        for (const auto& msg : cr.messages) {
42✔
326
            if (msg.kind != lnav_rs_ext::MessageKind::Error) {
1✔
327
                continue;
×
328
            }
329

330
            auto stmt_al = attr_line_t(stmt_str);
1✔
331
            readline_sql_highlighter(stmt_al, lnav::sql::dialect::prql, 0);
1✔
332
            auto um
333
                = lnav::console::user_message::error(
×
334
                      attr_line_t("unable to compile PRQL: ").append(stmt_al))
2✔
335
                      .with_reason(
1✔
336
                          attr_line_t::from_ansi_str((std::string) msg.reason));
2✔
337
            if (!msg.display.empty()) {
1✔
338
                um.with_note(
1✔
339
                    attr_line_t::from_ansi_str((std::string) msg.display));
2✔
340
            }
341
            for (const auto& hint : msg.hints) {
1✔
342
                um.with_help(attr_line_t::from_ansi_str((std::string) hint));
×
343
                break;
×
344
            }
345
            return Err(um);
1✔
346
        }
1✔
347
        log_debug("done!");
41✔
348
        stmt_str = (std::string) cr.output;
41✔
349
#else
350
        auto um = lnav::console::user_message::error(
351
            attr_line_t("PRQL is not supported in this build"));
352
        return Err(um);
353
#endif
354
    }
44✔
355

356
    log_info("Executing SQL: %s", stmt_str.c_str());
1,686✔
357

358
    auto old_mode = lnav_data.ld_mode;
1,686✔
359
    lnav_data.ld_mode = ln_mode_t::BUSY;
1,686✔
360
    auto mode_fin = finally([old_mode]() { lnav_data.ld_mode = old_mode; });
1,686✔
361
    lnav_data.ld_bottom_source.grep_error("");
1,686✔
362
    lnav_data.ld_status[LNS_BOTTOM].set_needs_update();
1,686✔
363

364
    if (startswith(stmt_str, ".")) {
1,686✔
365
        std::vector<std::string> args;
7✔
366
        split_ws(stmt_str, args);
7✔
367

368
        const auto* sql_cmd_map
369
            = injector::get<readline_context::command_map_t*,
370
                            sql_cmd_map_tag>();
7✔
371
        auto cmd_iter = sql_cmd_map->find(args[0]);
7✔
372

373
        if (cmd_iter != sql_cmd_map->end()) {
7✔
374
            ec.ec_current_help = &cmd_iter->second->c_help;
7✔
375
            auto retval = cmd_iter->second->c_func(ec, stmt_str, args);
7✔
376
            ec.ec_current_help = nullptr;
7✔
377

378
            return retval;
7✔
379
        }
7✔
380
    }
7✔
381

382
    ec.ec_accumulator->clear();
1,679✔
383

384
    require(!ec.ec_source.empty());
1,679✔
385
    const auto& source = ec.ec_source.back();
1,679✔
386
    sql_progress_guard progress_guard(sql_progress,
387
                                      sql_progress_finished,
388
                                      source.s_location,
389
                                      source.s_content);
1,679✔
390
    gettimeofday(&start_tv, nullptr);
1,679✔
391

392
    const auto* curr_stmt = stmt_str.c_str();
1,679✔
393
    auto last_is_readonly = false;
1,679✔
394
    while (curr_stmt != nullptr) {
3,295✔
395
        const char* tail = nullptr;
3,295✔
396
        while (isspace(*curr_stmt)) {
3,295✔
397
            curr_stmt += 1;
×
398
        }
399
        retcode = sqlite3_prepare_v2(
3,295✔
400
            lnav_data.ld_db.in(), curr_stmt, -1, stmt.out(), &tail);
401
        if (retcode != SQLITE_OK) {
3,295✔
402
            const char* errmsg = sqlite3_errmsg(lnav_data.ld_db);
7✔
403

404
            alt_msg = "";
7✔
405

406
            auto um = lnav::console::user_message::error(
14✔
407
                          "failed to compile SQL statement")
408
                          .with_reason(errmsg)
14✔
409
                          .with_snippets(ec.ec_source)
14✔
410
                          .move();
7✔
411

412
            auto annotated_sql = annotate_sql_with_error(
413
                lnav_data.ld_db.in(), curr_stmt, tail);
7✔
414
            auto loc = um.um_snippets.back().s_location;
7✔
415
            if (curr_stmt == stmt_str.c_str()) {
7✔
416
                um.um_snippets.pop_back();
7✔
417
            } else {
418
                auto tail_iter = stmt_str.begin();
×
419

420
                std::advance(tail_iter, (curr_stmt - stmt_str.c_str()));
×
421
                loc.sl_line_number
×
422
                    += std::count(stmt_str.begin(), tail_iter, '\n');
×
423
            }
424

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

427
            return Err(um);
7✔
428
        }
7✔
429
        if (stmt == nullptr) {
3,288✔
430
            retcode = SQLITE_DONE;
1,616✔
431
            break;
1,616✔
432
        }
433
#ifdef HAVE_SQLITE3_STMT_READONLY
434
        last_is_readonly = sqlite3_stmt_readonly(stmt.in());
1,672✔
435
        if (ec.is_read_only() && !last_is_readonly) {
1,672✔
436
            return ec.make_error(
437
                "modifying statements are not allowed in this context: {}",
438
                sql);
×
439
        }
440
#endif
441
        bool done = false;
1,672✔
442

443
        auto bound_values = TRY(bind_sql_parameters(ec, stmt.in()));
1,672✔
444
        if (last_is_readonly) {
1,671✔
445
            ec.ec_sql_callback(ec, stmt.in());
1,535✔
446
        }
447
        while (!done) {
5,987✔
448
            retcode = sqlite3_step(stmt.in());
4,371✔
449

450
            switch (retcode) {
4,371✔
451
                case SQLITE_OK:
1,616✔
452
                case SQLITE_DONE: {
453
                    auto changes = sqlite3_changes(lnav_data.ld_db.in());
1,616✔
454

455
                    log_info("sqlite3_changes() -> %d", changes);
1,616✔
456
                    done = true;
1,616✔
457
                    break;
1,616✔
458
                }
459

460
                case SQLITE_ROW:
2,700✔
461
                    ec.ec_sql_callback(ec, stmt.in());
2,700✔
462
                    break;
2,700✔
463

464
                default: {
55✔
465
                    attr_line_t bound_note;
55✔
466

467
                    if (!bound_values.empty()) {
55✔
468
                        bound_note.append(
3✔
469
                            "the bound parameters are set as follows:\n");
470
                        for (const auto& bval : bound_values) {
11✔
471
                            auto val_as_str = fmt::to_string(bval.second);
8✔
472
                            auto sql_type = bval.second.match(
8✔
473
                                [](const std::string&) { return SQLITE_TEXT; },
5✔
474
                                [](const string_fragment&) {
×
475
                                    return SQLITE_TEXT;
×
476
                                },
477
                                [](bool) { return SQLITE_INTEGER; },
×
478
                                [](int64_t) { return SQLITE_INTEGER; },
1✔
479
                                [](null_value_t) { return SQLITE_NULL; },
1✔
480
                                [](double) { return SQLITE_FLOAT; });
1✔
481
                            auto scrubbed_val = scrub_ws(val_as_str.c_str());
8✔
482
                            truncate_to(scrubbed_val, 40);
8✔
483
                            bound_note.append("  ")
8✔
484
                                .append(lnav::roles::variable(bval.first))
16✔
485
                                .append(":")
8✔
486
                                .append(sqlite3_type_to_string(sql_type))
8✔
487
                                .append(" = ")
8✔
488
                                .append_quoted(scrubbed_val)
16✔
489
                                .append("\n");
8✔
490
                        }
8✔
491
                    }
492

493
                    log_error("sqlite3_step error code: %d", retcode);
55✔
494
                    auto um = sqlite3_error_to_user_message(lnav_data.ld_db)
110✔
495
                                  .with_note(bound_note)
55✔
496
                                  .move();
55✔
497

498
                    if (!ec.get_provenance<exec_context::keyboard_input>()) {
55✔
499
                        um.with_context_snippets(ec.ec_source)
110✔
500
                            .remove_internal_snippets();
55✔
501
                    }
502

503
                    return Err(um);
55✔
504
                }
55✔
505
            }
506
        }
507

508
        curr_stmt = tail;
1,616✔
509
    }
1,671✔
510

511
    if (last_is_readonly && !ec.ec_label_source_stack.empty()) {
1,616✔
512
        auto& dls = *ec.ec_label_source_stack.back();
1,510✔
513
        dls.dls_query_end = std::chrono::steady_clock::now();
1,510✔
514

515
        size_t memory_usage = 0, total_size = 0, cached_chunks = 0;
1,510✔
516
        for (auto cc = dls.dls_cell_container.cc_first.get(); cc != nullptr;
3,021✔
517
             cc = cc->cc_next.get())
1,511✔
518
        {
519
            total_size += cc->cc_capacity;
1,511✔
520
            if (cc->cc_data) {
1,511✔
521
                cached_chunks += 1;
1,510✔
522
                memory_usage += cc->cc_capacity;
1,510✔
523
            } else {
524
                memory_usage += cc->cc_compressed_size;
1✔
525
            }
526
        }
527
        log_debug(
1,510✔
528
            "cell memory footprint: total=%zu; actual=%zu; cached-chunks=%zu",
529
            total_size,
530
            memory_usage,
531
            cached_chunks);
532
    }
533
    gettimeofday(&end_tv, nullptr);
1,616✔
534
    lnav_data.ld_mode = old_mode;
1,616✔
535
    if (retcode == SQLITE_DONE) {
1,616✔
536
        if (lnav_data.ld_log_source.is_line_meta_changed()) {
1,616✔
537
            lnav_data.ld_log_source.text_filters_changed();
13✔
538
            lnav_data.ld_views[LNV_LOG].reload_data();
13✔
539
        }
540
        lnav_data.ld_filter_view.reload_data();
1,616✔
541
        lnav_data.ld_files_view.reload_data();
1,616✔
542

543
        lnav_data.ld_active_files.fc_files
544
            | lnav::itertools::for_each(&logfile::dump_stats);
1,616✔
545
        if (ec.ec_sql_callback != sql_callback) {
1,616✔
546
            retval = ec.ec_accumulator->get_string();
64✔
547
        } else {
548
            auto& dls = *(ec.ec_label_source_stack.back());
1,552✔
549
            if (!dls.dls_row_cursors.empty()) {
1,552✔
550
                lnav_data.ld_views[LNV_DB].reload_data();
1,439✔
551
                lnav_data.ld_views[LNV_DB].set_selection(0_vl);
1,439✔
552
                lnav_data.ld_views[LNV_DB].set_left(0);
1,439✔
553
                if (lnav_data.ld_flags & LNF_HEADLESS) {
1,439✔
554
                    if (ec.ec_local_vars.size() == 1) {
953✔
555
                        ensure_view(&lnav_data.ld_views[LNV_DB]);
863✔
556
                    }
557

558
                    retval = "";
953✔
559
                    alt_msg = "";
953✔
560
                } else if (dls.dls_row_cursors.size() == 1) {
486✔
561
                    retval = dls.get_row_as_string(0_vl);
438✔
562
                } else {
563
                    int row_count = dls.dls_row_cursors.size();
48✔
564
                    char row_count_buf[128];
565
                    timeval diff_tv;
566

567
                    timersub(&end_tv, &start_tv, &diff_tv);
48✔
568
                    snprintf(row_count_buf,
48✔
569
                             sizeof(row_count_buf),
570
                             ANSI_BOLD("%'d") " row%s matched in " ANSI_BOLD(
571
                                 "%ld.%03ld") " seconds",
572
                             row_count,
573
                             row_count == 1 ? "" : "s",
574
                             diff_tv.tv_sec,
575
                             std::max((long) diff_tv.tv_usec / 1000, 1L));
48✔
576
                    retval = row_count_buf;
48✔
577
                    if (dls.has_log_time_column()) {
48✔
578
                        alt_msg
579
                            = HELP_MSG_1(Q,
2✔
580
                                         "to switch back to the previous view "
581
                                         "at the matching 'log_time' value");
582
                    } else {
583
                        alt_msg = "";
46✔
584
                    }
585
                }
586
            }
587
#ifdef HAVE_SQLITE3_STMT_READONLY
588
            else if (last_is_readonly)
113✔
589
            {
590
                retval = "info: No rows matched";
25✔
591
                alt_msg = "";
25✔
592

593
                if (lnav_data.ld_flags & LNF_HEADLESS) {
25✔
594
                    if (ec.ec_local_vars.size() == 1) {
25✔
595
                        lnav_data.ld_views[LNV_DB].reload_data();
14✔
596
                        ensure_view(&lnav_data.ld_views[LNV_DB]);
14✔
597
                    }
598
                }
599
            }
600
#endif
601
        }
602
    }
603

604
    return Ok(retval);
1,616✔
605
}
1,687✔
606

607
Result<void, lnav::console::user_message>
608
multiline_executor::handle_command(const std::string& cmdline)
252✔
609
{
610
    this->me_last_result = TRY(execute_from_file(this->me_exec_context,
252✔
611
                                                 this->p_source,
612
                                                 this->p_starting_line_number,
613
                                                 cmdline));
614

615
    return Ok();
248✔
616
}
617

618
static Result<std::string, lnav::console::user_message>
619
execute_file_contents(exec_context& ec, const std::filesystem::path& path)
40✔
620
{
621
    static const std::filesystem::path stdin_path("-");
40✔
622
    static const std::filesystem::path dev_stdin_path("/dev/stdin");
40✔
623

624
    FILE* file;
625

626
    if (path == stdin_path || path == dev_stdin_path) {
40✔
627
        if (isatty(STDIN_FILENO)) {
3✔
628
            return ec.make_error("stdin has already been consumed");
×
629
        }
630
        file = stdin;
3✔
631
    } else if ((file = fopen(path.c_str(), "re")) == nullptr) {
37✔
632
        return ec.make_error("unable to open file");
×
633
    }
634

635
    std::string out_name;
40✔
636

637
    auto_mem<char> line;
40✔
638
    size_t line_max_size;
639
    ssize_t line_size;
640
    multiline_executor me(ec, path.string());
40✔
641

642
    ec.ec_local_vars.top()["0"] = path.string();
120✔
643
    ec.ec_path_stack.emplace_back(path.parent_path());
40✔
644
    exec_context::output_guard og(ec);
80✔
645
    while ((line_size = getline(line.out(), &line_max_size, file)) != -1) {
920✔
646
        TRY(me.push_back(string_fragment::from_bytes(line.in(), line_size)));
884✔
647
    }
648

649
    TRY(me.final());
36✔
650
    auto retval = std::move(me.me_last_result);
36✔
651

652
    if (file == stdin) {
36✔
653
        if (isatty(STDOUT_FILENO)) {
3✔
654
            log_perror(dup2(STDOUT_FILENO, STDIN_FILENO));
×
655
        }
656
    } else {
657
        fclose(file);
33✔
658
    }
659
    ec.ec_path_stack.pop_back();
36✔
660

661
    return Ok(retval);
36✔
662
}
40✔
663

664
Result<std::string, lnav::console::user_message>
665
execute_file(exec_context& ec, const std::string& path_and_args)
45✔
666
{
667
    static const intern_string_t SRC = intern_string::lookup("cmdline");
103✔
668
    static auto op = lnav_operation{__FUNCTION__};
45✔
669

670
    auto op_guard = lnav_opid_guard::internal(op);
45✔
671

672
    std::string retval, msg;
45✔
673
    shlex lexer(path_and_args);
45✔
674

675
    log_info("Executing file: %s", path_and_args.c_str());
45✔
676

677
    auto split_args_res = lexer.split(scoped_resolver{&ec.ec_local_vars.top()});
45✔
678
    if (split_args_res.isErr()) {
45✔
679
        auto split_err = split_args_res.unwrapErr();
×
680
        auto um = lnav::console::user_message::error(
×
681
                      "unable to parse script command-line")
682
                      .with_reason(split_err.se_error.te_msg)
×
683
                      .with_snippet(lnav::console::snippet::from(
×
684
                          SRC, lexer.to_attr_line(split_err.se_error)))
×
685
                      .move();
×
686

687
        return Err(um);
×
688
    }
689
    auto split_args = split_args_res.unwrap();
45✔
690
    if (split_args.empty()) {
45✔
691
        return ec.make_error("no script specified");
×
692
    }
693

694
    ec.ec_local_vars.emplace();
45✔
695

696
    auto script_name = split_args[0].se_value;
45✔
697
    auto& vars = ec.ec_local_vars.top();
45✔
698
    std::string star, open_error = "file not found";
90✔
699

700
    add_ansi_vars(vars);
45✔
701

702
    vars["#"] = fmt::to_string(split_args.size() - 1);
135✔
703
    for (size_t lpc = 0; lpc < split_args.size(); lpc++) {
134✔
704
        vars[fmt::to_string(lpc)] = split_args[lpc].se_value;
89✔
705
    }
706
    for (size_t lpc = 1; lpc < split_args.size(); lpc++) {
89✔
707
        if (lpc > 1) {
44✔
708
            star.append(" ");
21✔
709
        }
710
        star.append(split_args[lpc].se_value);
44✔
711
    }
712
    vars["__all__"] = star;
45✔
713

714
    std::vector<script_metadata> paths_to_exec;
45✔
715

716
    auto scripts = find_format_scripts(lnav_data.ld_config_paths);
45✔
717
    auto iter = scripts.as_scripts.find(script_name);
45✔
718
    if (iter != scripts.as_scripts.end()) {
45✔
719
        paths_to_exec = iter->second;
30✔
720
    }
721
    if (lnav::filesystem::is_url(script_name)) {
45✔
722
        auto_mem<CURLU> cu(curl_url_cleanup);
×
723
        cu = curl_url();
×
724
        auto set_rc = curl_url_set(cu, CURLUPART_URL, script_name.c_str(), 0);
×
725
        if (set_rc == CURLUE_OK) {
×
726
            auto_mem<char> scheme_part(curl_free);
×
727
            auto get_rc
728
                = curl_url_get(cu, CURLUPART_SCHEME, scheme_part.out(), 0);
×
729
            if (get_rc == CURLUE_OK
×
730
                && string_fragment::from_c_str(scheme_part.in()) == "file")
×
731
            {
732
                auto_mem<char> path_part;
×
733
                auto get_rc
734
                    = curl_url_get(cu, CURLUPART_PATH, path_part.out(), 0);
×
735
                if (get_rc == CURLUE_OK) {
×
736
                    auto rp_res = lnav::filesystem::realpath(path_part.in());
×
737
                    if (rp_res.isOk()) {
×
738
                        struct script_metadata meta;
×
739

740
                        meta.sm_path = rp_res.unwrap();
×
741
                        extract_metadata_from_file(meta);
×
742
                        paths_to_exec.push_back(meta);
×
743
                    }
744
                }
745
            }
746
        }
747
    }
748
    if (script_name == "-" || script_name == "/dev/stdin") {
45✔
749
        paths_to_exec.push_back({script_name, "", "", ""});
3✔
750
    } else if (access(script_name.c_str(), R_OK) == 0) {
42✔
751
        struct script_metadata meta;
7✔
752
        auto rp_res = lnav::filesystem::realpath(script_name);
7✔
753

754
        if (rp_res.isErr()) {
7✔
755
            log_error("unable to get realpath() of %s -- %s",
×
756
                      script_name.c_str(),
757
                      rp_res.unwrapErr().c_str());
758
            meta.sm_path = script_name;
×
759
        } else {
760
            meta.sm_path = rp_res.unwrap();
7✔
761
        }
762
        extract_metadata_from_file(meta);
7✔
763
        paths_to_exec.push_back(meta);
7✔
764
    } else if (errno != ENOENT) {
42✔
NEW
765
        open_error = lnav::from_errno().message();
×
766
    } else {
767
        auto script_path = std::filesystem::path(script_name);
35✔
768

769
        if (!script_path.is_absolute()) {
35✔
770
            script_path = ec.ec_path_stack.back() / script_path;
35✔
771
        }
772

773
        if (std::filesystem::is_regular_file(script_path)) {
35✔
774
            script_metadata meta;
×
775

776
            meta.sm_path = script_path;
×
777
            extract_metadata_from_file(meta);
×
778
            paths_to_exec.push_back(meta);
×
779
        } else if (errno != ENOENT) {
35✔
NEW
780
            open_error = lnav::from_errno().message();
×
781
        }
782
    }
35✔
783

784
    if (!paths_to_exec.empty()) {
45✔
785
        for (auto& path_iter : paths_to_exec) {
76✔
786
            if (!ec.ec_output_stack.empty()) {
40✔
787
                ec.ec_output_stack.back().od_format
40✔
788
                    = path_iter.sm_output_format;
40✔
789
                log_info("%s: setting out format for '%s' to %d",
40✔
790
                         script_name.c_str(),
791
                         ec.ec_output_stack.back().od_name.c_str(),
792
                         ec.ec_output_stack.back().od_format);
793
            }
794
            retval = TRY(execute_file_contents(ec, path_iter.sm_path));
40✔
795
        }
796
    }
797
    ec.ec_local_vars.pop();
41✔
798

799
    if (paths_to_exec.empty()) {
41✔
800
        return ec.make_error(
801
            "unknown script -- {} -- {}", script_name, open_error);
5✔
802
    }
803

804
    return Ok(retval);
36✔
805
}
60✔
806

807
Result<std::string, lnav::console::user_message>
808
execute_from_file(exec_context& ec,
252✔
809
                  const std::string& src,
810
                  int line_number,
811
                  const std::string& cmdline)
812
{
813
    std::string retval, alt_msg;
252✔
814
    auto _sg
815
        = ec.enter_source(intern_string::lookup(src), line_number, cmdline);
252✔
816

817
    lnav_data.ld_view_stack.top() | [&ec](auto* tc) {
252✔
818
        ec.ec_top_line = tc->get_selection().value_or(0_vl);
228✔
819
    };
228✔
820
    switch (cmdline[0]) {
252✔
821
        case ':':
107✔
822
            retval = TRY(execute_command(ec, cmdline.substr(1)));
107✔
823
            break;
107✔
824
        case '/':
1✔
825
            execute_search(cmdline.substr(1));
1✔
826
            break;
1✔
827
        case ';': {
142✔
828
            if (!ec.ec_msg_callback_stack.empty()) {
142✔
829
                auto src_slash = src.rfind('/');
138✔
830
                auto cmd_al
831
                    = attr_line_t(cmdline.substr(0, cmdline.find('\n')));
138✔
832
                readline_lnav_highlighter(cmd_al, std::nullopt);
138✔
833
                const auto um = lnav::console::user_message::info(
138✔
834
                                    attr_line_t("Executing command at ")
138✔
835
                                        .append(lnav::roles::file(
138✔
836
                                            src_slash != std::string::npos
837
                                                ? src.substr(src_slash + 1)
276✔
838
                                                : src))
839
                                        .append(":")
138✔
840
                                        .append(lnav::roles::number(
276✔
841
                                            fmt::to_string(line_number)))
276✔
842
                                        .append(" \u2014 ")
138✔
843
                                        .append(cmd_al))
138✔
844
                                    .move();
138✔
845
                ec.ec_msg_callback_stack.back()(um);
138✔
846
            }
138✔
847

848
            setup_logline_table(ec);
142✔
849
            retval = TRY(execute_sql(ec, cmdline.substr(1), alt_msg));
142✔
850
            break;
138✔
851
        }
852
        case '|':
2✔
853
            retval = TRY(execute_file(ec, cmdline.substr(1)));
2✔
854
            break;
2✔
855
        default:
×
856
            retval = TRY(execute_command(ec, cmdline));
×
857
            break;
×
858
    }
859

860
    log_info(
248✔
861
        "%s:%d:execute result -- %s", src.c_str(), line_number, retval.c_str());
862

863
    return Ok(retval);
248✔
864
}
252✔
865

866
Result<std::string, lnav::console::user_message>
867
execute_any(exec_context& ec, const std::string& cmdline_with_mode)
41✔
868
{
869
    if (cmdline_with_mode.empty()) {
41✔
870
        auto um = lnav::console::user_message::error("empty command")
×
871
                      .with_help(
×
872
                          "a command should start with ':', ';', '/', '|' and "
873
                          "followed by the operation to perform")
874
                      .move();
×
875
        if (!ec.ec_source.empty()) {
×
876
            um.with_snippet(ec.ec_source.back());
×
877
        }
878
        return Err(um);
×
879
    }
880

881
    std::string retval, alt_msg, cmdline = cmdline_with_mode.substr(1);
41✔
882
    auto _cleanup = finally([&ec] {
41✔
883
        if (ec.is_read_write() &&
48✔
884
            // only rebuild in a script or non-interactive mode so we don't
885
            // block the UI.
886
            lnav_data.ld_flags & LNF_HEADLESS)
7✔
887
        {
888
            rescan_files();
×
889
            wait_for_pipers(std::nullopt);
×
890
            rebuild_indexes_repeatedly();
×
891
        }
892
    });
82✔
893

894
    switch (cmdline_with_mode[0]) {
41✔
895
        case ':':
2✔
896
            retval = TRY(execute_command(ec, cmdline));
2✔
897
            break;
2✔
898
        case '/':
×
899
            execute_search(cmdline);
×
900
            break;
×
901
        case ';':
31✔
902
            setup_logline_table(ec);
31✔
903
            retval = TRY(execute_sql(ec, cmdline, alt_msg));
31✔
904
            break;
31✔
905
        case '|': {
8✔
906
            retval = TRY(execute_file(ec, cmdline));
8✔
907
            break;
8✔
908
        }
909
        default:
×
910
            retval = TRY(execute_command(ec, cmdline));
×
911
            break;
×
912
    }
913

914
    return Ok(retval);
41✔
915
}
41✔
916

917
void
918
execute_init_commands(
589✔
919
    exec_context& ec,
920
    std::vector<std::pair<Result<std::string, lnav::console::user_message>,
921
                          std::string>>& msgs)
922
{
923
    if (lnav_data.ld_cmd_init_done) {
589✔
924
        return;
×
925
    }
926

927
    std::string out_name;
589✔
928
    std::optional<exec_context::output_t> ec_out;
589✔
929
    auto_fd fd_copy;
589✔
930
    auto& dls = *(ec.ec_label_source_stack.back());
589✔
931
    int option_index = 1;
589✔
932

933
    {
934
        log_info("Executing initial commands");
589✔
935
        exec_context::output_guard og(ec, out_name, ec_out);
589✔
936

937
        for (auto& cmd : lnav_data.ld_commands) {
1,553✔
938
            static const auto COMMAND_OPTION_SRC
939
                = intern_string::lookup("command-option");
1,990✔
940

941
            std::string alt_msg;
964✔
942
            auto has_db_query = false;
964✔
943

944
            wait_for_children();
964✔
945

946
            lnav_data.ld_view_stack.top() | [&ec](auto* tc) {
964✔
947
                ec.ec_top_line = tc->get_selection().value_or(0_vl);
964✔
948
            };
964✔
949
            log_debug("init cmd: %s", cmd.c_str());
964✔
950
            {
951
                auto _sg
952
                    = ec.enter_source(COMMAND_OPTION_SRC, option_index++, cmd);
964✔
953
                switch (cmd.at(0)) {
964✔
954
                    case ':':
584✔
955
                        msgs.emplace_back(execute_command(ec, cmd.substr(1)),
584✔
956
                                          alt_msg);
957
                        break;
584✔
958
                    case '/':
6✔
959
                        execute_search(cmd.substr(1));
6✔
960
                        break;
6✔
961
                    case ';':
348✔
962
                        setup_logline_table(ec);
348✔
963
                        msgs.emplace_back(
348✔
964
                            execute_sql(ec, cmd.substr(1), alt_msg), alt_msg);
696✔
965
                        has_db_query = true;
348✔
966
                        break;
348✔
967
                    case '|':
26✔
968
                        msgs.emplace_back(execute_file(ec, cmd.substr(1)),
26✔
969
                                          alt_msg);
970
                        break;
26✔
971
                }
972

973
                rescan_files();
964✔
974
                auto deadline = ui_clock::now();
964✔
975
                if (lnav_data.ld_flags & LNF_HEADLESS) {
964✔
976
                    deadline += 5s;
963✔
977
                } else {
978
                    deadline += 500ms;
1✔
979
                }
980
                wait_for_pipers(deadline);
964✔
981
                rebuild_indexes_repeatedly();
964✔
982
            }
964✔
983
            if (has_db_query && !dls.dls_headers.empty()
348✔
984
                && lnav_data.ld_view_stack.size() == 1)
1,312✔
985
            {
986
                lnav_data.ld_views[LNV_DB].reload_data();
9✔
987
                ensure_view(LNV_DB);
9✔
988
            }
989
        }
964✔
990
    }
589✔
991
    lnav_data.ld_commands.clear();
589✔
992
    lnav_data.ld_cmd_init_done = true;
589✔
993
}
589✔
994

995
int
996
sql_callback(exec_context& ec, sqlite3_stmt* stmt)
4,126✔
997
{
998
    auto& dls = *(ec.ec_label_source_stack.back());
4,126✔
999
    const int ncols = sqlite3_column_count(stmt);
4,126✔
1000

1001
    if (!sqlite3_stmt_busy(stmt)) {
4,126✔
1002
        dls.clear();
1,481✔
1003

1004
        for (int lpc = 0; lpc < ncols; lpc++) {
4,499✔
1005
            const int type = sqlite3_column_type(stmt, lpc);
3,018✔
1006
            std::string colname = sqlite3_column_name(stmt, lpc);
3,018✔
1007

1008
            dls.push_header(colname, type);
3,018✔
1009
        }
3,018✔
1010
        return 0;
1,481✔
1011
    }
1012

1013
    int retval = 0;
2,645✔
1014
    auto set_vars = dls.dls_row_cursors.empty();
2,645✔
1015

1016
    if (dls.dls_row_cursors.empty()) {
2,645✔
1017
        dls.dls_query_start = std::chrono::steady_clock::now();
1,431✔
1018
        for (int lpc = 0; lpc < ncols; lpc++) {
4,266✔
1019
            int type = sqlite3_column_type(stmt, lpc);
2,835✔
1020
            std::string colname = sqlite3_column_name(stmt, lpc);
2,835✔
1021

1022
            bool graphable = (type == SQLITE_INTEGER || type == SQLITE_FLOAT);
2,835✔
1023
            auto& hm = dls.dls_headers[lpc];
2,835✔
1024
            hm.hm_column_type = type;
2,835✔
1025
            if (lnav_data.ld_db_key_names.count(colname) > 0) {
2,835✔
1026
                hm.hm_graphable = false;
554✔
1027
            } else if (graphable) {
2,281✔
1028
                dls.set_col_as_graphable(lpc);
650✔
1029
            }
1030
        }
2,835✔
1031
    }
1032

1033
    dls.dls_row_cursors.emplace_back(dls.dls_cell_container.end_cursor());
2,645✔
1034
    dls.dls_push_column = 0;
2,645✔
1035
    for (int lpc = 0; lpc < ncols; lpc++) {
11,820✔
1036
        const auto value_type = sqlite3_column_type(stmt, lpc);
9,175✔
1037
        db_label_source::column_value_t value;
9,175✔
1038
        auto& hm = dls.dls_headers[lpc];
9,175✔
1039

1040
        switch (value_type) {
9,175✔
1041
            case SQLITE_INTEGER:
2,669✔
1042
                value = (int64_t) sqlite3_column_int64(stmt, lpc);
2,669✔
1043
                hm.hm_align = text_align_t::end;
2,669✔
1044
                break;
2,669✔
1045
            case SQLITE_FLOAT:
231✔
1046
                value = sqlite3_column_double(stmt, lpc);
231✔
1047
                hm.hm_align = text_align_t::end;
231✔
1048
                break;
231✔
1049
            case SQLITE_NULL:
2,188✔
1050
                value = null_value_t{};
2,188✔
1051
                break;
2,188✔
1052
            default: {
4,087✔
1053
                auto frag = string_fragment::from_bytes(
4,087✔
1054
                    sqlite3_column_text(stmt, lpc),
1055
                    sqlite3_column_bytes(stmt, lpc));
4,087✔
1056
                if (!frag.empty()) {
4,087✔
1057
                    if (isdigit(frag[0])) {
4,020✔
1058
                        hm.hm_align = text_align_t::end;
1,386✔
1059
                        if (!hm.hm_graphable.has_value()) {
1,386✔
1060
                            auto split_res = humanize::try_from<double>(frag);
246✔
1061
                            if (split_res.has_value()) {
246✔
1062
                                dls.set_col_as_graphable(lpc);
59✔
1063
                            } else {
1064
                                hm.hm_graphable = false;
187✔
1065
                            }
1066
                        }
1067
                    } else if (!hm.hm_graphable.has_value()) {
2,634✔
1068
                        hm.hm_graphable = false;
1,036✔
1069
                    }
1070
                }
1071
                value = frag;
4,087✔
1072
                break;
4,087✔
1073
            }
1074
        }
1075
        dls.push_column(value);
9,175✔
1076
        if ((hm.hm_column_type == SQLITE_TEXT
9,175✔
1077
             || hm.hm_column_type == SQLITE_NULL)
4,986✔
1078
            && hm.hm_sub_type == 0)
6,310✔
1079
        {
1080
            switch (value_type) {
6,196✔
1081
                case SQLITE_TEXT:
3,975✔
1082
                    auto* raw_value = sqlite3_column_value(stmt, lpc);
3,975✔
1083
                    hm.hm_column_type = SQLITE_TEXT;
3,975✔
1084
                    hm.hm_sub_type = sqlite3_value_subtype(raw_value);
3,975✔
1085
                    break;
3,975✔
1086
            }
1087
        }
1088
        if (set_vars && !ec.ec_local_vars.empty() && !ec.ec_dry_run) {
9,175✔
1089
            if (sql_ident_needs_quote(hm.hm_name.c_str())) {
2,835✔
1090
                continue;
1,151✔
1091
            }
1092
            auto& vars = ec.ec_local_vars.top();
1,684✔
1093

1094
            vars[hm.hm_name] = value.match(
3,368✔
1095
                [](const string_fragment& sf) {
×
1096
                    return scoped_value_t{sf.to_string()};
741✔
1097
                },
1098
                [](int64_t i) { return scoped_value_t{i}; },
477✔
1099
                [](double d) { return scoped_value_t{d}; },
15✔
1100
                [](null_value_t) { return scoped_value_t{null_value_t{}}; });
3,819✔
1101
        }
1102
    }
9,175✔
1103

1104
    return retval;
2,645✔
1105
}
1106

1107
int
1108
internal_sql_callback(exec_context& ec, sqlite3_stmt* stmt)
38✔
1109
{
1110
    if (!sqlite3_stmt_busy(stmt)) {
38✔
1111
        return 0;
23✔
1112
    }
1113

1114
    const int ncols = sqlite3_column_count(stmt);
15✔
1115

1116
    auto& vars = ec.ec_local_vars.top();
15✔
1117

1118
    for (int lpc = 0; lpc < ncols; lpc++) {
39✔
1119
        const char* column_name = sqlite3_column_name(stmt, lpc);
24✔
1120

1121
        if (sql_ident_needs_quote(column_name)) {
24✔
1122
            continue;
×
1123
        }
1124

1125
        auto value_type = sqlite3_column_type(stmt, lpc);
24✔
1126
        scoped_value_t value;
24✔
1127
        switch (value_type) {
24✔
1128
            case SQLITE_INTEGER:
4✔
1129
                value = (int64_t) sqlite3_column_int64(stmt, lpc);
4✔
1130
                break;
4✔
1131
            case SQLITE_FLOAT:
×
1132
                value = sqlite3_column_double(stmt, lpc);
×
1133
                break;
×
1134
            case SQLITE_NULL:
3✔
1135
                value = null_value_t{};
3✔
1136
                break;
3✔
1137
            default:
17✔
1138
                value
1139
                    = std::string((const char*) sqlite3_column_text(stmt, lpc),
34✔
1140
                                  sqlite3_column_bytes(stmt, lpc));
34✔
1141
                break;
17✔
1142
        }
1143
        vars[column_name] = value;
24✔
1144
    }
24✔
1145

1146
    return 0;
15✔
1147
}
1148

1149
std::future<std::string>
1150
pipe_callback(exec_context& ec, const std::string& cmdline, auto_fd& fd)
7✔
1151
{
1152
    static auto& prompt = lnav::prompt::get();
7✔
1153
    auto out = ec.get_output();
7✔
1154

1155
    if (out) {
7✔
1156
        FILE* file = *out;
7✔
1157

1158
        return std::async(std::launch::async, [fd = std::move(fd), file]() {
14✔
1159
            char buffer[1024];
1160
            ssize_t rc;
1161

1162
            if (file == stdout) {
7✔
1163
                lnav_data.ld_stdout_used = true;
7✔
1164
            }
1165

1166
            while ((rc = read(fd, buffer, sizeof(buffer))) > 0) {
14✔
1167
                fwrite(buffer, rc, 1, file);
7✔
1168
            }
1169

1170
            return std::string();
14✔
1171
        });
7✔
1172
    }
1173
    std::error_code errc;
×
1174
    std::filesystem::create_directories(lnav::paths::workdir(), errc);
×
1175
    auto open_temp_res = lnav::filesystem::open_temp_file(lnav::paths::workdir()
×
1176
                                                          / "exec.XXXXXX");
×
1177
    if (open_temp_res.isErr()) {
×
1178
        return lnav::futures::make_ready_future(
1179
            fmt::format(FMT_STRING("error: cannot open temp file -- {}"),
×
1180
                        open_temp_res.unwrapErr()));
×
1181
    }
1182

1183
    auto tmp_pair = open_temp_res.unwrap();
×
1184

1185
    auto reader = std::thread(
1186
        [in_fd = std::move(fd), out_fd = std::move(tmp_pair.second)]() {
×
1187
            char buffer[1024];
1188
            ssize_t rc;
1189

1190
            while ((rc = read(in_fd, buffer, sizeof(buffer))) > 0) {
×
1191
                write(out_fd, buffer, rc);
×
1192
            }
1193
        });
×
1194
    reader.detach();
×
1195

1196
    static int exec_count = 0;
1197
    auto desc
1198
        = fmt::format(FMT_STRING("exec-{}-output {}"), exec_count++, cmdline);
×
1199
    lnav_data.ld_active_files.fc_file_names[tmp_pair.first]
×
1200
        .with_filename(desc)
×
1201
        .with_include_in_session(false)
×
1202
        .with_detect_format(false)
×
1203
        .with_init_location(0_vl);
×
1204
    lnav_data.ld_files_to_front.emplace_back(desc);
×
1205
    prompt.p_editor.set_alt_value(HELP_MSG_1(X, "to close the file"));
×
1206

1207
    return lnav::futures::make_ready_future(std::string());
×
1208
}
1209

1210
void
1211
add_global_vars(exec_context& ec)
659✔
1212
{
1213
    for (const auto& iter : lnav_config.lc_global_vars) {
10,550✔
1214
        shlex subber(iter.second);
9,891✔
1215
        std::string str;
9,891✔
1216

1217
        if (!subber.eval(str, scoped_resolver{&ec.ec_global_vars})) {
9,891✔
1218
            log_error("Unable to evaluate global variable value: %s",
×
1219
                      iter.second.c_str());
1220
            continue;
×
1221
        }
1222

1223
        ec.ec_global_vars[iter.first] = str;
9,891✔
1224
    }
9,891✔
1225
}
659✔
1226

1227
void
1228
exec_context::set_output(const std::string& name,
587✔
1229
                         FILE* file,
1230
                         int (*closer)(FILE*))
1231
{
1232
    log_info("redirecting command output to: %s", name.c_str());
587✔
1233
    this->ec_output_stack.back().od_output | [](auto out) {
587✔
1234
        if (out.second != nullptr) {
×
1235
            out.second(out.first);
×
1236
        }
1237
    };
1238
    this->ec_output_stack.back()
587✔
1239
        = output_desc{name, std::make_pair(file, closer)};
1,174✔
1240
}
587✔
1241

1242
void
1243
exec_context::clear_output()
78✔
1244
{
1245
    log_info("redirecting command output to screen");
78✔
1246
    this->ec_output_stack.back().od_output | [](auto out) {
78✔
1247
        if (out.second != nullptr) {
38✔
1248
            out.second(out.first);
38✔
1249
        }
1250
    };
38✔
1251
    this->ec_output_stack.back().od_name = "default";
78✔
1252
    this->ec_output_stack.back().od_output = std::nullopt;
78✔
1253
}
78✔
1254

1255
exec_context::exec_context(logline_value_vector* line_values,
3,497✔
1256
                           sql_callback_t sql_callback,
1257
                           pipe_callback_t pipe_callback)
3,497✔
1258
    : ec_line_values(line_values),
3,497✔
1259
      ec_accumulator(std::make_unique<attr_line_t>()),
3,497✔
1260
      ec_sql_callback(sql_callback), ec_pipe_callback(pipe_callback)
6,994✔
1261
{
1262
    this->ec_local_vars.push(std::map<std::string, scoped_value_t>());
3,497✔
1263
    this->ec_path_stack.emplace_back(".");
3,497✔
1264
    this->ec_output_stack.emplace_back("screen", std::nullopt);
3,497✔
1265
}
3,497✔
1266

1267
Result<std::string, lnav::console::user_message>
1268
exec_context::execute(source_location loc, const std::string& cmdline)
2✔
1269
{
1270
    static auto& prompt = lnav::prompt::get();
2✔
1271
    static const auto& dls = lnav_data.ld_db_row_source;
1272

1273
    lnav::textinput::history::op_guard hist_guard;
2✔
1274
    auto sg = this->enter_source(loc, cmdline);
2✔
1275

1276
    auto before_dls_gen = dls.dls_generation;
2✔
1277
    if (this->get_provenance<mouse_input>() && !prompt.p_editor.is_enabled()) {
2✔
1278
        auto& hist = prompt.get_history_for(cmdline[0]);
×
1279
        hist_guard = hist.start_operation(cmdline.substr(1));
×
1280
    }
1281

1282
    auto exec_res = execute_any(*this, cmdline);
2✔
1283
    if (exec_res.isErr()) {
2✔
1284
        hist_guard.og_status = log_level_t::LEVEL_ERROR;
×
1285
        if (!this->ec_msg_callback_stack.empty()) {
×
1286
            this->ec_msg_callback_stack.back()(exec_res.unwrapErr());
×
1287
        }
1288
    } else {
1289
        if (before_dls_gen != dls.dls_generation
4✔
1290
            && dls.dls_row_cursors.size() > 1)
2✔
1291
        {
1292
            ensure_view(LNV_DB);
×
1293
        }
1294
    }
1295

1296
    return exec_res;
4✔
1297
}
2✔
1298

1299
void
1300
exec_context::add_error_context(lnav::console::user_message& um)
75✔
1301
{
1302
    switch (um.um_level) {
75✔
1303
        case lnav::console::user_message::level::raw:
×
1304
        case lnav::console::user_message::level::info:
1305
        case lnav::console::user_message::level::ok:
1306
            return;
×
1307
        default:
75✔
1308
            break;
75✔
1309
    }
1310

1311
    if (!this->get_provenance<keyboard_input>() && um.um_snippets.empty()) {
75✔
1312
        um.with_snippets(this->ec_source);
35✔
1313
        um.remove_internal_snippets();
35✔
1314
    }
1315

1316
    if (this->ec_current_help != nullptr && um.um_help.empty()) {
75✔
1317
        attr_line_t help;
32✔
1318

1319
        format_help_text_for_term(*this->ec_current_help,
32✔
1320
                                  70,
1321
                                  help,
1322
                                  help_text_content::synopsis_and_summary);
1323
        um.with_help(help);
32✔
1324
    }
32✔
1325
}
1326

1327
exec_context::sql_callback_guard
1328
exec_context::push_callback(sql_callback_t cb)
5✔
1329
{
1330
    return sql_callback_guard(*this, cb);
5✔
1331
}
1332

1333
exec_context::source_guard
1334
exec_context::enter_source(source_location loc, const std::string& content)
2,448✔
1335
{
1336
    attr_line_t content_al{content};
2,448✔
1337
    content_al.with_attr_for_all(VC_ROLE.value(role_t::VCR_QUOTED_CODE));
2,448✔
1338
    readline_lnav_highlighter(content_al, -1);
2,448✔
1339
    this->ec_source.emplace_back(lnav::console::snippet::from(loc, content_al));
2,448✔
1340
    return {this};
4,896✔
1341
}
2,448✔
1342

1343
exec_context::output_guard::output_guard(exec_context& context,
665✔
1344
                                         std::string name,
1345
                                         const std::optional<output_t>& file,
1346
                                         text_format_t tf)
665✔
1347
    : sg_context(context), sg_active(!name.empty())
665✔
1348
{
1349
    if (name.empty()) {
665✔
1350
        return;
589✔
1351
    }
1352
    if (file) {
76✔
1353
        log_info("redirecting command output to: %s", name.c_str());
36✔
1354
    } else if (!context.ec_output_stack.empty()) {
40✔
1355
        tf = context.ec_output_stack.back().od_format;
40✔
1356
    }
1357
    context.ec_output_stack.emplace_back(std::move(name), file, tf);
76✔
1358
}
1359

1360
exec_context::output_guard::~output_guard()
665✔
1361
{
1362
    if (this->sg_active) {
665✔
1363
        this->sg_context.clear_output();
76✔
1364
        this->sg_context.ec_output_stack.pop_back();
76✔
1365
    }
1366
}
665✔
1367
exec_context::sql_callback_guard::sql_callback_guard(exec_context& context,
5✔
1368
                                                     sql_callback_t cb)
5✔
1369
    : scg_context(context), scg_old_callback(context.ec_sql_callback)
5✔
1370
{
1371
    context.ec_sql_callback = cb;
5✔
1372
}
5✔
1373
exec_context::sql_callback_guard::sql_callback_guard(sql_callback_guard&& other)
×
1374
    : scg_context(other.scg_context),
×
1375
      scg_old_callback(std::exchange(other.scg_old_callback, nullptr))
×
1376
{
1377
}
1378
exec_context::sql_callback_guard::~sql_callback_guard()
5✔
1379
{
1380
    if (this->scg_old_callback != nullptr) {
5✔
1381
        this->scg_context.ec_sql_callback = this->scg_old_callback;
5✔
1382
    }
1383
}
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