#ifndef QUERY_SESSION_HPP #define QUERY_SESSION_HPP #include "matador/sql/connection.hpp" #include "matador/sql/connection_pool.hpp" #include "matador/sql/entity.hpp" #include "matador/sql/entity_query_builder.hpp" #include "matador/sql/statement.hpp" #include "matador/sql/schema.hpp" #include namespace matador::sql { class dialect; class session { public: explicit session(connection_pool &pool); template void attach(const std::string &table_name); void create_schema(); template entity insert(Type *obj); template< class Type, typename... Args > entity insert(Args&&... args) { return insert(new Type(std::forward(args)...)); } template std::optional> find(const PrimaryKeyType &pk) { auto c = pool_.acquire(); if (!c.valid()) { throw std::logic_error("no database connection available"); } auto info = schema_->info(); if (!info) { return {}; } entity_query_builder eqb(*schema_); auto data = eqb.build(pk); auto q = c->query(*schema_) .select(data->columns) .from(data->root_table_name); for (auto &jd : data->joins) { q.join_left(jd.join_table) .on(std::move(jd.condition)); } auto e = q .where(std::move(data->where_clause)) .template fetch_one(); if (!e) { return std::nullopt; } return entity{ e.release() }; } template void drop_table(); void drop_table(const std::string &table_name); [[nodiscard]] query_result fetch(const query_context &q) const; // [[nodiscard]] query_result fetch(const std::string &sql) const; [[nodiscard]] size_t execute(const std::string &sql) const; statement prepare(query_context q) const; std::vector describe_table(const std::string &table_name) const; bool table_exists(const std::string &table_name) const; const class dialect& dialect() const; private: friend class query_select_finish; [[nodiscard]] std::unique_ptr fetch(const std::string &sql) const; private: connection_pool &pool_; const class dialect &dialect_; std::unique_ptr schema_; mutable std::unordered_map prototypes_; }; template void session::attach(const std::string &table_name) { schema_->attach(table_name); } template entity session::insert(Type *obj) { auto c = pool_.acquire(); auto info = schema_->info(); if (!info) { return {}; } c->query(*schema_) .insert() .into(info->name, column_generator::generate(*schema_)) .values(*obj) .execute(); return entity{obj}; } template void session::drop_table() { auto info = schema_->info(); if (info) { return drop_table(info.name); } } } #endif //QUERY_SESSION_HPP