summary refs log tree commit diff stats
path: root/lib/query.h
blob: 65b4e9d5d82a1617b9c87e2e617bcffb75a91d67 (plain) (blame)
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
#ifndef QUERY_H_7CC5284C
#define QUERY_H_7CC5284C

#include <vector>
#include <stdexcept>
#include <string>
#include <list>
#include <hkutil/database.h>
#include "statement.h"
#include "order.h"

namespace verbly {

  class database_error : public std::logic_error {
  public:

    database_error(
      std::string msg,
      std::string sqlMsg) :
        std::logic_error(msg + " (" + sqlMsg + ")")
    {
    }
  };

  template <typename Object>
  class query {
  public:

    query(
      const database& db,
      hatkirby::database& ppdb,
      filter queryFilter,
      order sortOrder,
      int limit) :
        db_(db),
        ppdb_(ppdb)
    {
      if ((sortOrder.getType() == order::type::field)
        && (sortOrder.getSortField().getObject() != Object::objectType))
      {
        throw std::invalid_argument(
          "Can only sort query by a field in the result table");
      }

      statement stmt(Object::objectType, std::move(queryFilter));

      queryString_ =
        stmt.getQueryString(Object::select, std::move(sortOrder), limit);

      bindings_ = stmt.getBindings();
    }

    std::vector<Object> all() const
    {
      std::vector<hatkirby::row> rows =
        ppdb_.queryAll(queryString_, bindings_);

      std::vector<Object> result;

      for (hatkirby::row& r : rows)
      {
        result.emplace_back(db_, std::move(r));
      }

      return result;
    }

    Object first() const
    {
      return { db_, ppdb_.queryFirst(queryString_, bindings_) };
    }

  private:

    const database& db_;
    hatkirby::database& ppdb_;

    std::string queryString_;
    std::list<hatkirby::binding> bindings_;
  };

};

#endif /* end of include guard: QUERY_H_7CC5284C */