You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

100 rivejä
3.0 KiB

  1. #pragma once
  2. #include "data_context.h"
  3. #include "../classes/schema/schema.inl"
  4. namespace cpphibernate {
  5. namespace mariadb {
  6. /* data_context */
  7. template<typename T_dataset>
  8. data_context::data_context(
  9. const schema_t& p_schema,
  10. ::cppmariadb::connection& p_connection,
  11. T_dataset& p_dataset)
  12. : base_context (p_schema, p_connection)
  13. , _dataset_id (0)
  14. , _dataset (nullptr)
  15. , _table (nullptr)
  16. { set(p_dataset); }
  17. template<typename T_dataset>
  18. decltype(auto) data_context::get() const
  19. {
  20. using dataset_type = mp::decay_t<T_dataset>;
  21. /* check if tha context has a dataset assigned (should never fail) */
  22. if (!_dataset)
  23. throw exception("no data assigned!");
  24. auto dataset_id = get_type_id(hana::type_c<dataset_type>);
  25. /* if the dataset IDs does not match, search in the base tables for a matching ID */
  26. if (dataset_id != _dataset_id)
  27. {
  28. /* get the table of the stored dataset */
  29. if (!_table)
  30. _table = &schema.table(_dataset_id);
  31. /* check if the table matches the stored dataset (should never happen) */
  32. else if (_table->dataset_id != _dataset_id)
  33. throw exception("invalid table!");
  34. /* walk through base tables until we have found a matching ID */
  35. auto table = _table;
  36. while(table && table->dataset_id != dataset_id)
  37. table = table->base_table;
  38. /* check if we have found a suitable table, if not throw an exception */
  39. if (!table)
  40. {
  41. throw exception(cppcore::type_helper<dataset_type>::name() +
  42. " is not a derived type of dataset with id " + std::to_string(_dataset_id));
  43. }
  44. }
  45. /* return the dataset */
  46. return *static_cast<dataset_type*>(_dataset);
  47. }
  48. template<typename T_dataset>
  49. void data_context::set(T_dataset& dataset)
  50. {
  51. _dataset_id = get_type_id(hana::type_c<mp::decay_t<T_dataset>>);
  52. _dataset = &dataset;
  53. _table = nullptr;
  54. }
  55. namespace __impl
  56. {
  57. /* change_context_builder */
  58. template<typename X, typename>
  59. struct change_context_builder
  60. {
  61. template<typename... T_args>
  62. static constexpr decltype(auto) apply(T_args&&...)
  63. { static_assert(sizeof...(T_args) == -1, "Invalid parameters for change_context(...)!"); }
  64. };
  65. template<typename T_context, typename T_dataset>
  66. struct change_context_builder<
  67. mp::list<T_context, T_dataset>,
  68. mp::enable_if_t<
  69. mp::is_base_of_v<data_context, mp::decay_t<T_context>>>>
  70. {
  71. static constexpr decltype(auto) apply(const T_context& context, T_dataset& dataset)
  72. {
  73. auto new_context = context;
  74. new_context.set(dataset);
  75. return new_context;
  76. }
  77. };
  78. }
  79. } }