count_query.hpp 755 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#pragma once

#include <database/query.hpp>
#include <database/table.hpp>

#include <string>

#include <sqlite3.h>

struct CountQuery: public Query
{
    CountQuery(std::string name):
        Query("SELECT count(*) FROM ")
    {
      this->body += std::move(name);
    }

18
    int64_t execute(sqlite3* db)
19 20
    {
      auto statement = this->prepare(db);
21
      int64_t res = 0;
22 23
      if (sqlite3_step(statement.get()) == SQLITE_ROW)
        res = sqlite3_column_int64(statement.get(), 0);
24 25 26 27 28
      else
        {
          log_error("Count request didn’t return a result");
          return 0;
        }
29
      if (sqlite3_step(statement.get()) != SQLITE_DONE)
30 31 32 33 34
        log_warning("Count request returned more than one result.");

      return res;
    }
};