diff options
author | louiz <louiz@louiz.org> | 2017-06-14 11:11:17 +0200 |
---|---|---|
committer | louiz <louiz@louiz.org> | 2017-06-14 11:11:17 +0200 |
commit | 5ba66c33519567f9f4e806a9ab41c3c94d93237f (patch) | |
tree | 4b51bece4f4dec660e0c48297404a5da51aee4ec /src/database/table.hpp | |
parent | ceb496369f834ffa055eb5b7ffc273b2a21f9b9a (diff) | |
parent | 2677ac42e8d2e1cf162fec773a9acb453bef8b9b (diff) | |
download | biboumi-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/table.hpp')
-rw-r--r-- | src/database/table.hpp | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/src/database/table.hpp b/src/database/table.hpp new file mode 100644 index 0000000..163b97f --- /dev/null +++ b/src/database/table.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include <database/select_query.hpp> +#include <database/type_to_sql.hpp> +#include <logger/logger.hpp> +#include <database/row.hpp> + +#include <algorithm> +#include <string> + +template <typename... T> +class Table +{ + static_assert(sizeof...(T) > 0, "Table cannot be empty"); + using ColumnTypes = std::tuple<T...>; + + public: + using RowType = Row<T...>; + + Table(std::string name): + name(std::move(name)) + {} + + void create(sqlite3* db) + { + std::string res{"CREATE TABLE IF NOT EXISTS "}; + res += this->name; + res += " (\n"; + this->add_column_create<0>(res); + res += ")"; + + log_debug(res); + + char* error; + const auto result = sqlite3_exec(db, res.data(), nullptr, nullptr, &error); + log_debug("result: ", +result); + if (result != SQLITE_OK) + { + log_error("Error executing query: ", error); + sqlite3_free(error); + } + } + + RowType row() + { + return {this->name}; + } + + SelectQuery<T...> select() + { + SelectQuery<T...> select(this->name); + return select; + } + + const std::string& get_name() const + { + return this->name; + } + + private: + template <std::size_t N> + typename std::enable_if<N < sizeof...(T), void>::type + add_column_create(std::string& str) + { + using ColumnType = typename std::remove_reference<decltype(std::get<N>(std::declval<ColumnTypes>()))>::type; + using RealType = typename ColumnType::real_type; + str += ColumnType::name; + str += " "; + str += TypeToSQLType<RealType>::type; + str += " "s + ColumnType::options; + if (N != sizeof...(T) - 1) + str += ","; + str += "\n"; + + add_column_create<N+1>(str); + } + + template <std::size_t N> + typename std::enable_if<N == sizeof...(T), void>::type + add_column_create(std::string&) + { } + + const std::string name; +}; |