summaryrefslogtreecommitdiff
path: root/src/database/row.hpp
diff options
context:
space:
mode:
authorlouiz <louiz@louiz.org>2017-06-14 11:11:17 +0200
committerlouiz <louiz@louiz.org>2017-06-14 11:11:17 +0200
commit5ba66c33519567f9f4e806a9ab41c3c94d93237f (patch)
tree4b51bece4f4dec660e0c48297404a5da51aee4ec /src/database/row.hpp
parentceb496369f834ffa055eb5b7ffc273b2a21f9b9a (diff)
parent2677ac42e8d2e1cf162fec773a9acb453bef8b9b (diff)
downloadbiboumi-5ba66c33519567f9f4e806a9ab41c3c94d93237f.tar.gz
biboumi-5ba66c33519567f9f4e806a9ab41c3c94d93237f.tar.bz2
biboumi-5ba66c33519567f9f4e806a9ab41c3c94d93237f.tar.xz
biboumi-5ba66c33519567f9f4e806a9ab41c3c94d93237f.zip
Merge branch 'orm' into 'master'
Pure c++ sqlite3 ORM Closes #3271 See merge request !11
Diffstat (limited to 'src/database/row.hpp')
-rw-r--r--src/database/row.hpp75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/database/row.hpp b/src/database/row.hpp
new file mode 100644
index 0000000..b6887cb
--- /dev/null
+++ b/src/database/row.hpp
@@ -0,0 +1,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 = static_cast<Id::real_type>(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;
+};