xaizek / uncov (License: AGPLv3+) (since 2018-12-07)
Uncov(er) is a tool that collects and processes code coverage reports.
<root> / src / DB.hpp (529d97efa190b98c478a29e67480bfc83748417d) (13KiB) (mode 100644) [raw]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
// Copyright (C) 2016 xaizek <xaizek@posteo.net>
//
// This file is part of uncov.
//
// uncov is free software: you can redistribute it and/or modify
// it under the terms of version 3 of the GNU Affero General Public License as
// published by the Free Software Foundation.
//
// uncov is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov.  If not, see <http://www.gnu.org/licenses/>.

#ifndef UNCOV_DB_HPP_
#define UNCOV_DB_HPP_

/**
 * @file DB.hpp
 *
 * @brief This unit provides basic facilities for interacting with a database.
 *
 * At the moment SQLite is the only supported database.
 */

#include <boost/range.hpp>
#include <boost/variant.hpp>

#include <cstdint>

#include <functional>
#include <iterator>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

#include "utils/integer_seq.hpp"

struct sqlite3;
struct sqlite3_stmt;

class Binding;
class Transaction;

/**
 * @brief Represents databaes connection.
 */
class DB
{
    class Row;
    class SingleRow;
    class RowIterator;
    class RowsData;
    class Rows;

    //! Type of smart handle to database statement, which is RAII-friendly.
    using stmtPtr = std::unique_ptr<sqlite3_stmt,
                                    std::function<void(sqlite3_stmt *)>>;
    //! Iterator facade base for the Rows class.
    using RowsBase = boost::iterator_range<RowIterator>;

public:
    /**
     * @brief Opens a database.
     *
     * @param path Path to the database.
     *
     * @throws std::runtime_error if database connection can't be opened.
     */
    explicit DB(const std::string &path);

    /**
     * @brief Closes database connection.
     */
    ~DB();

public:
    /**
     * @brief Performs a statement and discards result.
     *
     * @param stmt  Statement to be performed.
     * @param binds Bindings to be applied.
     *
     * @throws std::runtime_error on failure to make a statement or apply binds.
     */
    void execute(const std::string &stmt,
                 const std::vector<Binding> &binds = {});

    /**
     * @brief Queries single row as a result of performing a statement.
     *
     * @param stmt  Statement to be performed.
     * @param binds Bindings to be applied.
     *
     * @returns An object representing row, which is convertible to a tuple.
     *
     * @throws std::runtime_error on failure to make a statement or apply binds.
     */
    SingleRow queryOne(const std::string &stmt,
                       const std::vector<Binding> &binds = {});

    /**
     * @brief Queries multiple rows as a result of performing a statement.
     *
     * @param stmt  Statement to be performed.
     * @param binds Bindings to be applied.
     *
     * @returns Range-friendly object that generates tuples.
     *
     * @throws std::runtime_error on failure to make a statement or apply binds.
     */
    Rows queryAll(const std::string &stmt,
                  const std::vector<Binding> &binds = {});

    /**
     * @brief Retrieves id of the last inserted row.
     *
     * @returns The id.
     */
    std::int64_t getLastRowId();

    /**
     * @brief Starts a transaction.
     *
     * Usage:
     * @code
     * Transaction transaction = db.makeTransaction();
     * // db.execute(...);
     * // db.execute(...);
     * transaction.commit();
     * @endcode
     *
     * @returns RAII transaction object.
     */
    Transaction makeTransaction();

private:
    /**
     * @brief Builds a prepared statement.
     *
     * @param stmt  Statement to be performed.
     * @param binds Bindings to be applied.
     *
     * @returns Smart pointer to just created prepared statement.
     *
     * @throws std::runtime_error on failure to make a statement or apply binds.
     */
    stmtPtr prepare(const std::string &stmt, const std::vector<Binding> &binds);

private:
    sqlite3 *conn; //!< Connection to the database.
};

/**
 * @brief Wrapper for a single database row.
 */
class DB::Row
{
    /**
     * @brief Type marker for overload resolution.
     *
     * @tparam T Marked type.
     */
    template <typename T> struct Marker {};

public:
    /**
     * @brief Initializes row from database statement.
     *
     * @param ps @copybrief ps
     */
    Row(sqlite3_stmt *ps) : ps(ps)
    {
    }

public:
    /**
     * @brief Retrieves contents of the row as a tuple.
     *
     * @tparam Types Column types.
     *
     * @returns Row columns.
     *
     * @throws std::runtime_error if tuple size or types don't match.
     */
    template <typename... Types>
    operator std::tuple<Types...>()
    {
        const int nCols = getColumnCount();
        if (nCols != sizeof...(Types)) {
            throw std::runtime_error {
                "Expected " + std::to_string(nCols) + " columns, got " +
                std::to_string(sizeof...(Types))
            };
        }

        return makeTuple<Types...>(index_sequence_for<Types...>());
    }

private:
    /**
     * @brief Does the actual job of converting columns into a tuple.
     *
     * @tparam Types Column types.
     * @tparam Is    Index sequence that numbers columns.
     *
     * @param is "Container" for integer sequence.
     *
     * @returns Row columns.
     *
     * @throws std::runtime_error if tuple types don't match.
     */
    template <typename... Types, std::size_t... Is>
    std::tuple<Types...> makeTuple(integer_sequence<Is...> is)
    {
        static_cast<void>(is);
        return std::make_tuple(makeTupleItem(Is, Marker<Types>())...);
    }

    /**
     * @brief Retrieves number of columns in the row.
     *
     * @returns The number.
     */
    int getColumnCount() const;

    /**
     * @brief Reads contents of a column as a string.
     *
     * @param idx    Index of the column.
     * @param marker Overload resolution marker.
     *
     * @returns The string.
     */
    std::string makeTupleItem(std::size_t idx, Marker<std::string> marker);

    /**
     * @brief Reads contents of a column as an integer.
     *
     * @param idx    Index of the column.
     * @param marker Overload resolution marker.
     *
     * @returns The integer.
     */
    int makeTupleItem(std::size_t idx, Marker<int> marker);

    /**
     * @brief Reads contents of a column as a vector of integers.
     *
     * @param idx    Index of the column.
     * @param marker Overload resolution marker.
     *
     * @returns The vector of integers.
     */
    std::vector<int> makeTupleItem(std::size_t idx,
                                   Marker<std::vector<int>> marker);

private:
    sqlite3_stmt *ps; //!< Handle to the database statement.
};

/**
 * @brief A wrapper for reading single row from database statement.
 */
class DB::SingleRow : public Row
{
public:
    /**
     * @brief Takes ownership of the argument and reads single row.
     *
     * @param ps @copybrief ps
     */
    explicit SingleRow(stmtPtr ps);

private:
    stmtPtr ps; //!< Smart handle to database statement.
};

/**
 * @brief Table row iterator implementation.
 */
class DB::RowIterator
  : public boost::iterator_facade<RowIterator, Row, std::input_iterator_tag>
{
    friend class boost::iterator_core_access;

public:
    /**
     * @brief Initializes empty row iterator (end-iterator).
     */
    RowIterator() : ps(nullptr), row(ps)
    {
    }

    /**
     * @brief Initializes non-empty row iterator (begin-iterator).
     *
     * @param ps @copybrief ps
     */
    RowIterator(sqlite3_stmt *ps) : ps(ps), row(ps)
    {
        increment();
    }

private:
    /**
     * @brief Advances iterator position to the next row.
     */
    void increment();

    /**
     * @brief Compares the iterator against another one for equality.
     *
     * @param rhs Iterator to compare against.
     *
     * @returns @c true when equal, @c false otherwise.
     */
    bool equal(const RowIterator &rhs) const
    {
        return ps == rhs.ps;
    }

    /**
     * @brief Dereferences iterator.
     *
     * @returns Row object that allows accessing columns.
     */
    Row & dereference() const
    {
        return row;
    }

private:
    sqlite3_stmt *ps; //!< Handle to the database statement.
    mutable Row row;  //!< Row iterator object.
};

/**
 * @brief Data class for base-from-member idiom for Rows.
 */
class DB::RowsData
{
protected:
    /**
     * @brief Just moves argument into a member.
     *
     * @param ps @copybrief ps
     */
    RowsData(stmtPtr ps) : ps(std::move(ps))
    {
    }

protected:
    stmtPtr ps; //!< Smart handle to database statement.
};

/**
 * @brief Iterator range for rows.
 */
class DB::Rows : private RowsData, public RowsBase
{
public:
    /**
     * @brief Initializes the range.
     *
     * @param ps Smart handle to database statement.
     */
    explicit Rows(stmtPtr ps)
        : RowsData(std::move(ps)),
          RowsBase(RowIterator(RowsData::ps.get()), RowIterator())
    {
    }
};

/**
 * @brief RAII class for managing transactions.
 *
 * Transaction is started in the constructor and automatically rolled back in
 * the destructor unless commit() was called.
 */
class Transaction
{
public:
    /**
     * Starts the transaction.
     *
     * @param conn @copybrief conn
     */
    Transaction(sqlite3 *conn);
    //! Not copyable.
    Transaction(const Transaction &rhs) = delete;
    //! Moveable.
    Transaction(Transaction &&rhs) = default;
    //! Not copy-assignable.
    Transaction & operator=(const Transaction &rhs) = delete;
    //! Move-assignable.
    Transaction & operator=(Transaction &&rhs) = default;
    /**
     * Rolls back the transaction if commit() wasn't called.
     */
    ~Transaction();

public:
    /**
     * @brief Commits the transaction.
     *
     * @throws std::logic_error if transaction has already been committed.
     * @throws std::runtime_error if transaction doesn't commit.
     */
    void commit();

private:
    sqlite3 *conn;  //!< Connection on which transaction is performed.
    bool committed; //!< Whether transaction has been committed.
};

/**
 * @brief A name-value pair that represents a binding for prepared statements.
 */
class Binding
{
    friend class BlankBinding;

    /**
     * @brief Initializes the binding.
     *
     * Only BlankBinding can do this.
     *
     * @param name  @copybrief name
     * @param value @copybrief value
     */
    Binding(std::string name,
            boost::variant<std::string, int, std::vector<int>> value)
        : name(std::move(name)), value(value)
    {
    }

public:
    /**
     * @brief Retrieves name of the binding.
     *
     * @returns The name.
     */
    const std::string & getName() const
    {
        return name;
    }

    /**
     * @brief Retrieves value of the binding.
     *
     * @returns The value.
     */
    const boost::variant<std::string, int, std::vector<int>> & getValue() const
    {
        return value;
    }

private:
    //! Name of the argument that is being bound.
    const std::string name;
    //! Value that is bound.
    const boost::variant<std::string, int, std::vector<int>> value;
};

/**
 * @brief A temporary object which is a result of user-defined literal _b.
 */
class BlankBinding
{
    friend BlankBinding operator ""_b(const char name[], std::size_t len);

    /**
     * @brief Initializes blank binding with a name.
     *
     * @param name @copybrief name
     */
    explicit BlankBinding(std::string name) : name(std::move(name))
    {
    }

public:
    /**
     * @brief Completes binding with a string.
     *
     * @param val Value for the binding.
     *
     * @returns Fully initialized binding.
     */
    Binding operator=(std::string val) &&
    {
        return Binding(name, std::move(val));
    }

    /**
     * @brief Completes binding with an integer.
     *
     * @param val Value for the binding.
     *
     * @returns Fully initialized binding.
     */
    Binding operator=(int val) &&
    {
        return Binding(name, val);
    }

    /**
     * @brief Completes binding with vector of integers.
     *
     * @param val Value for the binding.
     *
     * @returns Fully initialized binding.
     */
    Binding operator=(std::vector<int> val) &&
    {
        return Binding(name, std::move(val));
    }

private:
    const std::string name; //!< Name of the argument that is being bound.
};

/**
 * @brief Partially creates a binding that holds its name only.
 *
 * @param name Name of the binding.
 * @param len  Length of the name of the binding.
 *
 * @returns Half-formed binding which should be completed with assignment.
 */
inline BlankBinding
operator ""_b(const char name[], std::size_t len)
{
    return BlankBinding(std::string(name, len));
}

#endif // UNCOV_DB_HPP_
Hints

Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://code.reversed.top/user/xaizek/uncov

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@code.reversed.top/user/xaizek/uncov

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a pull request:
... clone the repository ...
... make some changes and some commits ...
git push origin master