QxSession.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /****************************************************************************
  2. **
  3. ** https://www.qxorm.com/
  4. ** Copyright (C) 2013 Lionel Marty (contact@qxorm.com)
  5. **
  6. ** This file is part of the QxOrm library
  7. **
  8. ** This software is provided 'as-is', without any express or implied
  9. ** warranty. In no event will the authors be held liable for any
  10. ** damages arising from the use of this software
  11. **
  12. ** Commercial Usage
  13. ** Licensees holding valid commercial QxOrm licenses may use this file in
  14. ** accordance with the commercial license agreement provided with the
  15. ** Software or, alternatively, in accordance with the terms contained in
  16. ** a written agreement between you and Lionel Marty
  17. **
  18. ** GNU General Public License Usage
  19. ** Alternatively, this file may be used under the terms of the GNU
  20. ** General Public License version 3.0 as published by the Free Software
  21. ** Foundation and appearing in the file 'license.gpl3.txt' included in the
  22. ** packaging of this file. Please review the following information to
  23. ** ensure the GNU General Public License version 3.0 requirements will be
  24. ** met : http://www.gnu.org/copyleft/gpl.html
  25. **
  26. ** If you are unsure which license is appropriate for your use, or
  27. ** if you have questions regarding the use of this file, please contact :
  28. ** contact@qxorm.com
  29. **
  30. ****************************************************************************/
  31. #ifndef _QX_DAO_SESSION_H_
  32. #define _QX_DAO_SESSION_H_
  33. #ifdef _MSC_VER
  34. #pragma once
  35. #endif
  36. /*!
  37. * \file QxSession.h
  38. * \author Lionel Marty
  39. * \ingroup QxDao
  40. * \brief Define a session to manage automatically database transactions (using C++ RAII)
  41. */
  42. #include <QtSql/qsqldatabase.h>
  43. #include <QtSql/qsqlquery.h>
  44. #include <QtSql/qsqlerror.h>
  45. #include <QtSql/qsqldriver.h>
  46. #include <QtCore/qlist.h>
  47. #include <QxCommon/QxBool.h>
  48. #include <QxDao/QxDao.h>
  49. #include <QxDao/QxSqlQuery.h>
  50. #include <QxDao/QxSqlError.h>
  51. #include <QxRegister/QxClass.h>
  52. namespace qx {
  53. /*!
  54. * \ingroup QxDao
  55. * \brief qx::QxSession : define a session to manage automatically database transactions (using C++ RAII)
  56. *
  57. * A database <b>transaction</b> is a sequence of operations performed as a single logical unit of work.
  58. * If no errors occurred during the execution of the transaction then the system <b>commits</b> the transaction.
  59. * If an error occurs during the transaction, or if the user specifies a <b>rollback</b> operation, the data manipulations within the transaction are not persisted to the database.
  60. *
  61. * The <i>qx::QxSession</i> class of QxOrm library is designed to manage automatically database transactions (using <i>C++ RAII</i>) :
  62. * \code
  63. { // Start a scope where a new session is instantiated
  64. // Create a session : a valid database connexion by thread is automatically assigned to the session and a transaction is opened
  65. qx::QxSession session;
  66. // Execute some operations with database (using += operator of qx::QxSession class and session database connexion)
  67. session += qx::dao::insert(my_object, session.database());
  68. session += qx::dao::update(my_object, session.database());
  69. session += qx::dao::fetch_by_id(my_object, session.database());
  70. session += qx::dao::delete_by_id(my_object, session.database());
  71. // If the session is not valid (so an error occured) => display first error
  72. if (! session.isValid()) { qDebug("[QxOrm] session error : '%s'", qPrintable(session.firstError().text())); }
  73. } // End of scope : session is destroyed (transaction => automatically commit or rollback if there is an error)
  74. * \endcode
  75. *
  76. * <i>Note :</i> a session can throw a <i>qx::dao::sql_error</i> exception when a SQL error occured (by default, there is no exception).
  77. * You can setup this feature using :
  78. * - <i>qx::QxSession</i> constructor (for a specific session) ;
  79. * - <i>qx::QxSqlDatabase::getSingleton()->setSessionThrowable(bool b)</i> parameter (for all sessions).
  80. *
  81. * <i>Other note :</i> don't forget to pass the session database connexion to each <i>qx::dao::xxx</i> functions (using <i>session.database()</i> method).
  82. * Moreover, you can manage your own database connexion (from a connexion pool for example) using constructor of <i>qx::QxSession</i> class.
  83. *
  84. * <i>qx::QxSession</i> class provides also persistent methods (CRUD) to make easier to write C++ code.
  85. * Here is the same example using methods of <i>qx::QxSession</i> class instead of functions into namespace <i>qx::dao</i> :
  86. * \code
  87. { // Start a scope where a new session is instantiated
  88. // Create a session : a valid database connexion by thread is automatically assigned to the session and a transaction is opened
  89. qx::QxSession session;
  90. // Execute some operations with database
  91. session.insert(my_object);
  92. session.update(my_object);
  93. session.fetchById(my_object);
  94. session.deleteById(my_object);
  95. // If the session is not valid (so an error occured) => display first error
  96. if (! session.isValid()) { qDebug("[QxOrm] session error : '%s'", qPrintable(session.firstError().text())); }
  97. } // End of scope : session is destroyed (transaction => automatically commit or rollback if there is an error)
  98. * \endcode
  99. */
  100. class QX_DLL_EXPORT QxSession
  101. {
  102. private:
  103. struct QxSessionImpl;
  104. std::shared_ptr<QxSessionImpl> m_pImpl; //!< Private implementation idiom (use std::shared_ptr instead of std::unique_ptr because of incomplete type)
  105. public:
  106. QxSession();
  107. QxSession(const QSqlDatabase & database);
  108. QxSession(const QSqlDatabase & database, bool bOpenTransaction);
  109. QxSession(const QSqlDatabase & database, bool bOpenTransaction, bool bThrowable);
  110. virtual ~QxSession();
  111. bool isThrowable() const;
  112. bool isOpened() const;
  113. bool isValid() const;
  114. QSqlError firstError() const;
  115. QSqlError lastError() const;
  116. QList<QSqlError> allErrors() const;
  117. const QSqlDatabase * database() const;
  118. QSqlDatabase * database();
  119. bool open();
  120. bool close();
  121. bool commit();
  122. bool rollback();
  123. QxSession & operator+= (const QSqlError & err);
  124. static QxSession * getActiveSession(QSqlDatabase * db);
  125. void ignoreSoftDelete(bool bIgnoreSoftDelete = true, const QStringList & classesToIgnore = QStringList());
  126. bool checkIgnoreSoftDelete(const QString & classKey) const;
  127. QString getIgnoreSoftDeleteHash() const;
  128. template <class T>
  129. long count(const qx::QxSqlQuery & query = qx::QxSqlQuery())
  130. { return qx::dao::count<T>(query, this->database()); }
  131. template <class T>
  132. QSqlError count(long & lCount, const qx::QxSqlQuery & query = qx::QxSqlQuery())
  133. { return qx::dao::count<T>(lCount, query, this->database()); }
  134. template <class T>
  135. T * fetchById(const QVariant & id, const QStringList & columns = QStringList(), const QStringList & relation = QStringList())
  136. {
  137. IxDataMemberX * pDataMemberX = QxClass<T>::getSingleton()->getDataMemberX();
  138. IxDataMember * pDataMemberId = (pDataMemberX ? pDataMemberX->getId_WithDaoStrategy() : NULL);
  139. if (! pDataMemberId) { qAssert(false); return NULL; }
  140. T * t = new T(); QSqlError err;
  141. pDataMemberId->fromVariant(t, id, -1, qx::cvt::context::e_database);
  142. if (relation.count() == 0) { err = qx::dao::fetch_by_id((* t), this->database(), columns); }
  143. else { err = qx::dao::fetch_by_id_with_relation(relation, (* t), this->database()); }
  144. if (err.isValid()) { delete t; t = NULL; (* this) += err; }
  145. return t;
  146. }
  147. template <class T>
  148. QSqlError fetchById(T & t, const QStringList & columns = QStringList(), const QStringList & relation = QStringList())
  149. {
  150. QSqlError err;
  151. if (relation.count() == 0) { err = qx::dao::fetch_by_id(t, this->database(), columns); }
  152. else { err = qx::dao::fetch_by_id_with_relation(relation, t, this->database()); }
  153. if (err.isValid()) { (* this) += err; }
  154. return err;
  155. }
  156. template <class T>
  157. QSqlError fetchAll(T & t, const QStringList & columns = QStringList(), const QStringList & relation = QStringList())
  158. {
  159. QSqlError err;
  160. if (relation.count() == 0) { err = qx::dao::fetch_all(t, this->database(), columns); }
  161. else { err = qx::dao::fetch_all_with_relation(relation, t, this->database()); }
  162. if (err.isValid()) { (* this) += err; }
  163. return err;
  164. }
  165. template <class T>
  166. QSqlError fetchByQuery(const qx::QxSqlQuery & query, T & t, const QStringList & columns = QStringList(), const QStringList & relation = QStringList())
  167. {
  168. QSqlError err;
  169. if (relation.count() == 0) { err = qx::dao::fetch_by_query(query, t, this->database(), columns); }
  170. else { err = qx::dao::fetch_by_query_with_relation(relation, query, t, this->database()); }
  171. if (err.isValid()) { (* this) += err; }
  172. return err;
  173. }
  174. template <class T>
  175. QSqlError insert(T & t, const QStringList & relation = QStringList())
  176. {
  177. QSqlError err;
  178. if (relation.count() == 0) { err = qx::dao::insert(t, this->database()); }
  179. else { err = qx::dao::insert_with_relation(relation, t, this->database()); }
  180. if (err.isValid()) { (* this) += err; }
  181. return err;
  182. }
  183. template <class T>
  184. QSqlError update(T & t, const qx::QxSqlQuery & query = qx::QxSqlQuery(), const QStringList & columns = QStringList(), const QStringList & relation = QStringList())
  185. {
  186. QSqlError err;
  187. if (relation.count() == 0) { err = qx::dao::update_by_query(query, t, this->database(), columns); }
  188. else { err = qx::dao::update_by_query_with_relation(relation, query, t, this->database()); }
  189. if (err.isValid()) { (* this) += err; }
  190. return err;
  191. }
  192. template <class T>
  193. QSqlError save(T & t, const QStringList & relation = QStringList())
  194. {
  195. QSqlError err;
  196. if (relation.count() == 0) { err = qx::dao::save(t, this->database()); }
  197. else { err = qx::dao::save_with_relation(relation, t, this->database()); }
  198. if (err.isValid()) { (* this) += err; }
  199. return err;
  200. }
  201. template <class T>
  202. QSqlError deleteById(const QVariant & id)
  203. {
  204. IxDataMemberX * pDataMemberX = QxClass<T>::getSingleton()->getDataMemberX();
  205. IxDataMember * pDataMemberId = (pDataMemberX ? pDataMemberX->getId_WithDaoStrategy() : NULL);
  206. if (! pDataMemberId) { qAssert(false); return QSqlError(); }
  207. std::shared_ptr<T> t = std::make_shared<T>();
  208. pDataMemberId->fromVariant(t.get(), id, -1, qx::cvt::context::e_database);
  209. QSqlError err = qx::dao::delete_by_id((* t), this->database());
  210. if (err.isValid()) { (* this) += err; }
  211. return err;
  212. }
  213. template <class T>
  214. QSqlError deleteById(T & t)
  215. {
  216. QSqlError err = qx::dao::delete_by_id(t, this->database());
  217. if (err.isValid()) { (* this) += err; }
  218. return err;
  219. }
  220. template <class T>
  221. QSqlError deleteAll()
  222. {
  223. QSqlError err = qx::dao::delete_all<T>(this->database());
  224. if (err.isValid()) { (* this) += err; }
  225. return err;
  226. }
  227. template <class T>
  228. QSqlError deleteByQuery(const qx::QxSqlQuery & query)
  229. {
  230. QSqlError err = qx::dao::delete_by_query<T>(query, this->database());
  231. if (err.isValid()) { (* this) += err; }
  232. return err;
  233. }
  234. template <class T>
  235. QSqlError destroyById(const QVariant & id)
  236. {
  237. IxDataMemberX * pDataMemberX = QxClass<T>::getSingleton()->getDataMemberX();
  238. IxDataMember * pDataMemberId = (pDataMemberX ? pDataMemberX->getId_WithDaoStrategy() : NULL);
  239. if (! pDataMemberId) { qAssert(false); return QSqlError(); }
  240. std::shared_ptr<T> t = std::make_shared<T>();
  241. pDataMemberId->fromVariant(t.get(), id, -1, qx::cvt::context::e_database);
  242. QSqlError err = qx::dao::destroy_by_id((* t), this->database());
  243. if (err.isValid()) { (* this) += err; }
  244. return err;
  245. }
  246. template <class T>
  247. QSqlError destroyById(T & t)
  248. {
  249. QSqlError err = qx::dao::destroy_by_id(t, this->database());
  250. if (err.isValid()) { (* this) += err; }
  251. return err;
  252. }
  253. template <class T>
  254. QSqlError destroyAll()
  255. {
  256. QSqlError err = qx::dao::destroy_all<T>(this->database());
  257. if (err.isValid()) { (* this) += err; }
  258. return err;
  259. }
  260. template <class T>
  261. QSqlError destroyByQuery(const qx::QxSqlQuery & query)
  262. {
  263. QSqlError err = qx::dao::destroy_by_query<T>(query, this->database());
  264. if (err.isValid()) { (* this) += err; }
  265. return err;
  266. }
  267. template <class T>
  268. QSqlError executeQuery(qx::QxSqlQuery & query, T & t)
  269. {
  270. QSqlError err = qx::dao::execute_query<T>(query, t, this->database());
  271. if (err.isValid()) { (* this) += err; }
  272. return err;
  273. }
  274. QSqlError callQuery(qx::QxSqlQuery & query)
  275. {
  276. QSqlError err = qx::dao::call_query(query, this->database());
  277. if (err.isValid()) { (* this) += err; }
  278. return err;
  279. }
  280. template <class T>
  281. qx_bool exist(T & t)
  282. { return qx::dao::exist(t, this->database()); }
  283. private:
  284. QxSession(const QxSession & other) { Q_UNUSED(other); }
  285. QxSession & operator=(const QxSession & other) { Q_UNUSED(other); return (* this); }
  286. };
  287. } // namespace qx
  288. #endif // _QX_DAO_SESSION_H_