1// Copyright 2011 Google Inc.
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/backend.hpp"
39#include "utils/defs.hpp"
40#include "utils/format/macros.hpp"
41#include "utils/sanity.hpp"
42#include "utils/sqlite/database.hpp"
43#include "utils/sqlite/exceptions.hpp"
44#include "utils/sqlite/statement.hpp"
45
46namespace cmdline = utils::cmdline;
47namespace config = utils::config;
48namespace sqlite = utils::sqlite;
49
50using cli::cmd_db_exec;
51
52
53namespace {
54
55
56/// Concatenates a vector into a string using ' ' as a separator.
57///
58/// \param args The objects to join.  This cannot be empty.
59///
60/// \return The concatenation of all the objects in the set.
61static std::string
62flatten_args(const cmdline::args_vector& args)
63{
64    std::ostringstream output;
65    std::copy(args.begin(), args.end(),
66              std::ostream_iterator< std::string >(output, " "));
67
68    std::string result = output.str();
69    result.erase(result.end() - 1);
70    return result;
71}
72
73
74}  // anonymous namespace
75
76
77/// Formats a particular cell of a statement result.
78///
79/// \param stmt The statement whose cell to format.
80/// \param index The index of the cell to format.
81///
82/// \return A textual representation of the cell.
83std::string
84cli::format_cell(sqlite::statement& stmt, const int index)
85{
86    switch (stmt.column_type(index)) {
87    case sqlite::type_blob: {
88        const sqlite::blob blob = stmt.column_blob(index);
89        return F("BLOB of %s bytes") % blob.size;
90    }
91
92    case sqlite::type_float:
93        return F("%s") % stmt.column_double(index);
94
95    case sqlite::type_integer:
96        return F("%s") % stmt.column_int64(index);
97
98    case sqlite::type_null:
99        return "NULL";
100
101    case sqlite::type_text:
102        return stmt.column_text(index);
103    }
104
105    UNREACHABLE;
106}
107
108
109/// Formats the column names of a statement for output as CSV.
110///
111/// \param stmt The statement whose columns to format.
112///
113/// \return A comma-separated list of column names.
114std::string
115cli::format_headers(sqlite::statement& stmt)
116{
117    std::string output;
118    int i = 0;
119    for (; i < stmt.column_count() - 1; ++i)
120        output += stmt.column_name(i) + ',';
121    output += stmt.column_name(i);
122    return output;
123}
124
125
126/// Formats a row of a statement for output as CSV.
127///
128/// \param stmt The statement whose current row to format.
129///
130/// \return A comma-separated list of values.
131std::string
132cli::format_row(sqlite::statement& stmt)
133{
134    std::string output;
135    int i = 0;
136    for (; i < stmt.column_count() - 1; ++i)
137        output += cli::format_cell(stmt, i) + ',';
138    output += cli::format_cell(stmt, i);
139    return output;
140}
141
142
143/// Default constructor for cmd_db_exec.
144cmd_db_exec::cmd_db_exec(void) : cli_command(
145    "db-exec", "sql_statement", 1, -1,
146    "Executes an arbitrary SQL statement in the store database and prints "
147    "the resulting table")
148{
149    add_option(store_option);
150    add_option(cmdline::bool_option("no-headers", "Do not show headers in the "
151                                    "output table"));
152}
153
154
155/// Entry point for the "db-exec" subcommand.
156///
157/// \param ui Object to interact with the I/O of the program.
158/// \param cmdline Representation of the command line to the subcommand.
159/// \param unused_user_config The runtime configuration of the program.
160///
161/// \return 0 if everything is OK, 1 if the statement is invalid or if there is
162/// any other problem.
163int
164cmd_db_exec::run(cmdline::ui* ui, const cmdline::parsed_cmdline& cmdline,
165                 const config::tree& UTILS_UNUSED_PARAM(user_config))
166{
167    try {
168        store::backend backend = store::backend::open_rw(
169            cli::store_path(cmdline));
170        sqlite::statement stmt = backend.database().create_statement(
171            flatten_args(cmdline.arguments()));
172
173        if (stmt.step()) {
174            if (!cmdline.has_option("no-headers"))
175                ui->out(cli::format_headers(stmt));
176            do
177                ui->out(cli::format_row(stmt));
178            while (stmt.step());
179        }
180
181        return EXIT_SUCCESS;
182    } catch (const sqlite::error& e) {
183        cmdline::print_error(ui, F("SQLite error: %s") % e.what());
184        return EXIT_FAILURE;
185    }
186}
187