~singpolyma/biboumi

ref: 50cadf3dac0d56ef8181d1800cc30f8dcb749141 biboumi/src/database/row.hpp -rw-r--r-- 1.9 KiB
50cadf3d — louiz’ Implement our own database ORM, and update the whole code to use it 5 years ago
                                                                                
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
#pragma once

#include <database/insert_query.hpp>
#include <logger/logger.hpp>

#include <type_traits>

#include <sqlite3.h>

template <typename ColumnType, typename... T>
typename std::enable_if<!std::is_same<std::decay_t<ColumnType>, Id>::value, void>::type
update_id(std::tuple<T...>&, sqlite3*)
{}

template <typename ColumnType, typename... T>
typename std::enable_if<std::is_same<std::decay_t<ColumnType>, Id>::value, void>::type
update_id(std::tuple<T...>& columns, sqlite3* db)
{
  auto&& column = std::get<ColumnType>(columns);
  log_debug("Found an autoincrement col.");
  auto res = sqlite3_last_insert_rowid(db);
  log_debug("Value is now: ", res);
  column.value = res;
}

template <std::size_t N, typename... T>
typename std::enable_if<N < sizeof...(T), void>::type
update_autoincrement_id(std::tuple<T...>& columns, sqlite3* db)
{
  using ColumnType = typename std::remove_reference<decltype(std::get<N>(columns))>::type;
  update_id<ColumnType>(columns, db);
  update_autoincrement_id<N+1>(columns, db);
}

template <std::size_t N, typename... T>
typename std::enable_if<N == sizeof...(T), void>::type
update_autoincrement_id(std::tuple<T...>&, sqlite3*)
{}

template <typename... T>
struct Row
{
    Row(std::string name):
    table_name(std::move(name))
    {}

    template <typename Type>
    auto& col()
    {
      auto&& col = std::get<Type>(this->columns);
      return col.value;
    }

    template <typename Type>
    const auto& col() const
    {
      auto&& col = std::get<Type>(this->columns);
      return col.value;
    }

    void save(sqlite3* db)
    {
      InsertQuery query(this->table_name);
      query.insert_col_names(this->columns);
      query.insert_values(this->columns);
      log_debug(query.body);

      query.execute(this->columns, db);

      update_autoincrement_id<0>(this->columns, db);
    }

    std::tuple<T...> columns;
    std::string table_name;
};