xref: /freebsd/contrib/kyua/cli/cmd_db_exec.cpp (revision e17f5b1d307b7b8910d67883e57a9604305906d5)
1 // Copyright 2011 The Kyua Authors.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 //   notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright
11 //   notice, this list of conditions and the following disclaimer in the
12 //   documentation and/or other materials provided with the distribution.
13 // * Neither the name of Google Inc. nor the names of its contributors
14 //   may be used to endorse or promote products derived from this software
15 //   without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 
29 #include "cli/cmd_db_exec.hpp"
30 
31 #include <algorithm>
32 #include <cstdlib>
33 #include <iterator>
34 #include <sstream>
35 #include <string>
36 
37 #include "cli/common.ipp"
38 #include "store/exceptions.hpp"
39 #include "store/layout.hpp"
40 #include "store/read_backend.hpp"
41 #include "utils/cmdline/options.hpp"
42 #include "utils/cmdline/parser.ipp"
43 #include "utils/cmdline/ui.hpp"
44 #include "utils/defs.hpp"
45 #include "utils/format/macros.hpp"
46 #include "utils/fs/path.hpp"
47 #include "utils/sanity.hpp"
48 #include "utils/sqlite/database.hpp"
49 #include "utils/sqlite/exceptions.hpp"
50 #include "utils/sqlite/statement.hpp"
51 
52 namespace cmdline = utils::cmdline;
53 namespace config = utils::config;
54 namespace fs = utils::fs;
55 namespace layout = store::layout;
56 namespace sqlite = utils::sqlite;
57 
58 using cli::cmd_db_exec;
59 
60 
61 namespace {
62 
63 
64 /// Concatenates a vector into a string using ' ' as a separator.
65 ///
66 /// \param args The objects to join.  This cannot be empty.
67 ///
68 /// \return The concatenation of all the objects in the set.
69 static std::string
70 flatten_args(const cmdline::args_vector& args)
71 {
72     std::ostringstream output;
73     std::copy(args.begin(), args.end(),
74               std::ostream_iterator< std::string >(output, " "));
75 
76     std::string result = output.str();
77     result.erase(result.end() - 1);
78     return result;
79 }
80 
81 
82 }  // anonymous namespace
83 
84 
85 /// Formats a particular cell of a statement result.
86 ///
87 /// \param stmt The statement whose cell to format.
88 /// \param index The index of the cell to format.
89 ///
90 /// \return A textual representation of the cell.
91 std::string
92 cli::format_cell(sqlite::statement& stmt, const int index)
93 {
94     switch (stmt.column_type(index)) {
95     case sqlite::type_blob: {
96         const sqlite::blob blob = stmt.column_blob(index);
97         return F("BLOB of %s bytes") % blob.size;
98     }
99 
100     case sqlite::type_float:
101         return F("%s") % stmt.column_double(index);
102 
103     case sqlite::type_integer:
104         return F("%s") % stmt.column_int64(index);
105 
106     case sqlite::type_null:
107         return "NULL";
108 
109     case sqlite::type_text:
110         return stmt.column_text(index);
111     }
112 
113     UNREACHABLE;
114 }
115 
116 
117 /// Formats the column names of a statement for output as CSV.
118 ///
119 /// \param stmt The statement whose columns to format.
120 ///
121 /// \return A comma-separated list of column names.
122 std::string
123 cli::format_headers(sqlite::statement& stmt)
124 {
125     std::string output;
126     int i = 0;
127     for (; i < stmt.column_count() - 1; ++i)
128         output += stmt.column_name(i) + ',';
129     output += stmt.column_name(i);
130     return output;
131 }
132 
133 
134 /// Formats a row of a statement for output as CSV.
135 ///
136 /// \param stmt The statement whose current row to format.
137 ///
138 /// \return A comma-separated list of values.
139 std::string
140 cli::format_row(sqlite::statement& stmt)
141 {
142     std::string output;
143     int i = 0;
144     for (; i < stmt.column_count() - 1; ++i)
145         output += cli::format_cell(stmt, i) + ',';
146     output += cli::format_cell(stmt, i);
147     return output;
148 }
149 
150 
151 /// Default constructor for cmd_db_exec.
152 cmd_db_exec::cmd_db_exec(void) : cli_command(
153     "db-exec", "sql_statement", 1, -1,
154     "Executes an arbitrary SQL statement in a results file and prints "
155     "the resulting table")
156 {
157     add_option(results_file_open_option);
158     add_option(cmdline::bool_option("no-headers", "Do not show headers in the "
159                                     "output table"));
160 }
161 
162 
163 /// Entry point for the "db-exec" subcommand.
164 ///
165 /// \param ui Object to interact with the I/O of the program.
166 /// \param cmdline Representation of the command line to the subcommand.
167 ///
168 /// \return 0 if everything is OK, 1 if the statement is invalid or if there is
169 /// any other problem.
170 int
171 cmd_db_exec::run(cmdline::ui* ui, const cmdline::parsed_cmdline& cmdline,
172                  const config::tree& /* user_config */)
173 {
174     try {
175         const fs::path results_file = layout::find_results(
176             results_file_open(cmdline));
177 
178         // TODO(jmmv): Shouldn't be using store::detail here...
179         sqlite::database db = store::detail::open_and_setup(
180             results_file, sqlite::open_readwrite);
181         sqlite::statement stmt = db.create_statement(
182             flatten_args(cmdline.arguments()));
183 
184         if (stmt.step()) {
185             if (!cmdline.has_option("no-headers"))
186                 ui->out(cli::format_headers(stmt));
187             do
188                 ui->out(cli::format_row(stmt));
189             while (stmt.step());
190         }
191 
192         return EXIT_SUCCESS;
193     } catch (const sqlite::error& e) {
194         cmdline::print_error(ui, F("SQLite error: %s.") % e.what());
195         return EXIT_FAILURE;
196     } catch (const store::error& e) {
197         cmdline::print_error(ui, F("%s.") % e.what());
198         return EXIT_FAILURE;
199     }
200 }
201