aboutsummaryrefslogtreecommitdiff
#pragma once

#include <functional>
#include <string>
#include <cstdint>

#include "types.hh"

class sqlite3;
class sqlite3_stmt;

namespace nix {

/* RAII wrapper to close a SQLite database automatically. */
struct SQLite
{
    sqlite3 * db;
    SQLite() { db = 0; }
    ~SQLite();
    operator sqlite3 * () { return db; }
};

/* RAII wrapper to create and destroy SQLite prepared statements. */
struct SQLiteStmt
{
    sqlite3 * db = 0;
    sqlite3_stmt * stmt = 0;
    SQLiteStmt() { }
    void create(sqlite3 * db, const std::string & s);
    ~SQLiteStmt();
    operator sqlite3_stmt * () { return stmt; }

    /* Helper for binding / executing statements. */
    class Use
    {
        friend struct SQLiteStmt;
    private:
        SQLiteStmt & stmt;
        unsigned int curArg = 1;
        Use(SQLiteStmt & stmt);

    public:

        ~Use();

        /* Bind the next parameter. */
        Use & operator () (const std::string & value, bool notNull = true);
        Use & operator () (int64_t value, bool notNull = true);
        Use & bind(); // null

        int step();

        /* Execute a statement that does not return rows. */
        void exec();

        /* For statements that return 0 or more rows. Returns true iff
           a row is available. */
        bool next();

        std::string getStr(int col);
        int64_t getInt(int col);
    };

    Use use()
    {
        return Use(*this);
    }
};

/* RAII helper that ensures transactions are aborted unless explicitly
   committed. */
struct SQLiteTxn
{
    bool active = false;
    sqlite3 * db;

    SQLiteTxn(sqlite3 * db);

    void commit();

    ~SQLiteTxn();
};


MakeError(SQLiteError, Error);
MakeError(SQLiteBusy, SQLiteError);

[[noreturn]] void throwSQLiteError(sqlite3 * db, const format & f);

/* Convenience function for retrying a SQLite transaction when the
   database is busy. */
template<typename T>
T retrySQLite(std::function<T()> fun)
{
    while (true) {
        try {
            return fun();
        } catch (SQLiteBusy & e) {
        }
    }
}

}
>gnu: bootloader: Deprecate "device" field in favor of "target"....Andy Wingo 2017-05-16bootloader: Add extlinux support....Mathieu Othacehe 2017-05-04tests: Use 'fold-module-public-variables' for discovery....Ludovic Courtès 2017-05-03Add (guix discovery)....Ludovic Courtès 2017-04-01tests: Introduce 'simple-operating-system' and use it....Ludovic Courtès 2016-07-12services: <shepherd-service> no longer has an 'imported-modules' field....Ludovic Courtès 2016-06-27tests: 'marionette-service-type' nows takes a <marionette-configuration>....Ludovic Courtès 2016-06-20tests: Add a mechanism to describe and discover system tests....Ludovic Courtès 2016-06-20tests: Add system installation test....Ludovic Courtès 2016-06-20tests: Fix list of exports in (gnu tests)....Ludovic Courtès 2016-05-04Add (gnu tests) and (gnu build marionette)....Ludovic Courtès