~singpolyma/biboumi

ref: d7427fc9ca4c06fda458e4951559f57163d90b94 biboumi/src/database/row.hpp -rw-r--r-- 2.0 KiB
d7427fc9 — louiz’ Re-connect to postgresql when the connection is lost 4 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
76
77
78
79
80
#pragma once

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

#include <utils/is_one_of.hpp>

#include <type_traits>

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

  template <typename Type>
  typename Type::real_type& 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;
  }

  template <bool Coucou=true>
  void save(std::unique_ptr<DatabaseEngine>& db, typename std::enable_if<!is_one_of<Id, T...> && Coucou>::type* = nullptr)
  {
    this->insert(*db);
  }

  template <bool Coucou=true>
  void save(std::unique_ptr<DatabaseEngine>& db, typename std::enable_if<is_one_of<Id, T...> && Coucou>::type* = nullptr)
  {
    const Id& id = std::get<Id>(this->columns);
    if (id.value == Id::unset_value)
      {
        this->insert(*db);
        if (db->last_inserted_rowid >= 0)
          std::get<Id>(this->columns).value = static_cast<Id::real_type>(db->last_inserted_rowid);
      }
    else
      this->update(*db);
  }

 private:
  template <bool Coucou=true>
  void insert(DatabaseEngine& db, typename std::enable_if<is_one_of<Id, T...> && Coucou>::type* = nullptr)
  {
    InsertQuery query(this->table_name, this->columns);
    // Ugly workaround for non portable stuff
    query.body += db.get_returning_id_sql_string(Id::name);
    query.execute(db, this->columns);
  }

  template <bool Coucou=true>
  void insert(DatabaseEngine& db, typename std::enable_if<!is_one_of<Id, T...> && Coucou>::type* = nullptr)
  {
    InsertQuery query(this->table_name, this->columns);
    query.execute(db, this->columns);
  }

  void update(DatabaseEngine& db)
  {
    UpdateQuery query(this->table_name, this->columns);

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

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

};