123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511 |
- #ifndef EASYQTSQL_TRANSACTION_H
- #define EASYQTSQL_TRANSACTION_H
- /*
- * The MIT License (MIT)
- * Copyright 2018 Alexey Kramin
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- */
- #ifndef EASY_QT_SQL_MAIN
- #include <QtSql>
- #include "EasyQtSql_DBException.h"
- #include "EasyQtSql_NonQueryResult.h"
- #include "EasyQtSql_InsertQuery.h"
- #include "EasyQtSql_DeleteQuery.h"
- #include "EasyQtSql_UpdateQuery.h"
- #include "EasyQtSql_PreparedQuery.h"
- #endif
- #include "EasyQtSql_Util.h"
- /*!
- \brief QSqlDatabase wrapper.
- \code
- void test()
- {
- QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
- db.setDatabaseName(":memory:");
- try
- {
- Database sdb(db);
- sdb.execNonQuery("CREATE TABLE table (a int, b int, c int, d text)");
- }
- catch (const DBException &e)
- {
- //you can handle all the errors at one point
- qDebug() << e.lastError << e.lastQuery;
- }
- }
- \endcode
- */
- class Database
- {
- Q_DISABLE_COPY(Database)
- public:
- /*!
- * \param db QSqlDatabase to use
- *
- * Creates an Database object, tries to open <em>db</em> connection if not opened.
- *
- * \throws DBException
- */
- explicit Database (const QSqlDatabase &db = QSqlDatabase())
- {
- m_db = db.isValid() ? db : QSqlDatabase::database();
- if (!m_db.isOpen())
- {
- if (!m_db.open())
- {
- #ifdef DB_EXCEPTIONS_ENABLED
- throw DBException(m_db);
- #endif
- }
- }
- }
- Database(Database&& other)
- {
- m_db = other.m_db;
- other.m_db = QSqlDatabase();
- }
- Database& operator=(Database&& other)
- {
- if (this == &other) return *this;
- m_db = other.m_db;
- other.m_db = QSqlDatabase();
- return *this;
- }
- /*!
- * \brief Returns information about the last error that occurred on the underlying database.
- */
- QSqlError lastError() const
- {
- return m_db.lastError();
- }
- /*!
- \brief Executes non-query SQL statement (DELETE, INSERT, UPDATE, CREATE, ALTER, etc.)
- \param query SQL statement string
- \throws DBException
- */
- NonQueryResult execNonQuery(const QString &sql) const
- {
- QSqlQuery q = m_db.exec(sql);
- #ifdef DB_EXCEPTIONS_ENABLED
- QSqlError lastError = q.lastError();
- if (lastError.isValid())
- throw DBException(q);
- #endif
- return NonQueryResult(q);
- }
- /*!
- \brief Executes SELECT query
- \param query SQL statement string
- \throws DBException
- */
- QueryResult execQuery(const QString &sql) const
- {
- QSqlQuery q = m_db.exec(sql);
- #ifdef DB_EXCEPTIONS_ENABLED
- QSqlError lastError = q.lastError();
- if (lastError.isValid())
- throw DBException(q);
- #endif
- return QueryResult(q);
- }
- /*!
- \brief Creates INSERT query wrapper
- \param table Table to insert into with list of columns
- */
- InsertQuery insertInto(const QString &table) const
- {
- InsertQuery query(table, m_db);
- return query;
- }
- /*!
- \brief Creates DELETE query wrapper
- \param table Table to delete from
- */
- DeleteQuery deleteFrom(const QString &table) const
- {
- DeleteQuery query(table, m_db);
- return query;
- }
- /*!
- \brief Creates UPDATE query wrapper
- \param table Table to update
- */
- UpdateQuery update(const QString &table) const
- {
- UpdateQuery query(table, m_db);
- return query;
- }
- /*!
- \brief Prepares SQL statement
- \param sql SQL statement string
- \param forwardOnly Configure underlying QSqlQuery as forwardOnly
- */
- PreparedQuery prepare(const QString &sql, bool forwardOnly = true) const
- {
- PreparedQuery query(sql, m_db, forwardOnly);
- return query;
- }
- /*!
- * \brief Returns a reference to the wrapped QSqlDatabase object
- */
- QSqlDatabase &qSqlDatabase()
- {
- return m_db;
- }
- /*!
- \brief Executes <em>query</em> and applies function <em>f</em> to each result row.
- \param query SQL query string (SELECT statement)
- \param f Function (lambda) to apply to
- \returns num rows handled with function <em>f</em>
- \code
- Database db;
- db.each("SELECT * FROM table", [](const QueryResult &res)
- {
- qDebug() << res.toMap();
- });
- \endcode
- */
- template<typename Func>
- int each (const QString &query, Func&& f) const
- {
- QueryResult res = execQuery(query);
- return Util::each(res, f);
- }
- /*!
- \brief Executes <em>query</em> and applies function <em>f</em> to the first result row.
- \param query SQL query string (SELECT statement)
- \param f Function (lambda) to apply to
- \returns num rows handled with function <em>f</em>
- \code
- Database db;
- db.first("SELECT * FROM table", [](const QueryResult &res)
- {
- qDebug() << res.toMap();
- });
- \endcode
- */
- template<typename Func>
- int first (const QString &query, Func&& f) const
- {
- QueryResult res = execQuery(query);
- return Util::first(res, f);
- }
- /*!
- \brief Executes <em>query</em> and applies function <em>f</em> to <em>count</em> result rows starting from index <em>start</em>.
- \param query SQL query string (SELECT statement)
- \param start Start index
- \param count Row count to handle
- \param f Function (lambda) to apply to
- \returns num rows handled with function <em>f</em>
- \code
- Database db;
- db.range("SELECT * FROM table", 3, 10, [](const QueryResult &res)
- {
- qDebug() << res.toMap();
- });
- \endcode
- */
- template<typename Func>
- int range(const QString &query, int start, int count, Func&& f) const
- {
- QueryResult res = execQuery(query);
- return Util::range(res, start, count, f);
- }
- /*!
- \brief Executes <em>query</em> and applies function <em>f</em> to <em>topCount</em> result rows.
- \param query SQL query string (SELECT statement)
- \param topCount Row count to handle
- \param f Function (lambda) to apply to
- \returns num rows handled with function <em>f</em>
- \code
- Database db;
- db.top("SELECT * FROM table", 10, [](const QueryResult &res)
- {
- qDebug() << res.toMap();
- });
- \endcode
- */
- template<typename Func>
- int top(const QString &query, int topCount, Func&& f) const
- {
- QueryResult res = execQuery(query);
- return Util::top(res, topCount, f);
- }
- /*!
- \brief Executes <em>query</em> and returns scalar value converted to T.
- \param query SQL query string (SELECT statement)
- \sa QueryResult::scalar
- */
- template<typename T>
- T scalar(const QString &query) const
- {
- QueryResult res = execQuery(query);
- res.next();
- return res.scalar<T>();
- }
- /*!
- \brief Executes <em>query</em> and returns scalar value.
- \param query SQL query string (SELECT statement)
- \sa QueryResult::scalar
- */
- QVariant scalar(const QString &query) const
- {
- QueryResult res = execQuery(query);
- res.next();
- return res.scalar();
- }
- protected:
- QSqlDatabase m_db;
- };
- /*!
- \brief QSqlDatabase transaction wrapper.
- Features:
- - Automatic rollback of non-expclicitely commited transactions
- - Helper methods: Transaction::execNonQuery, Transaction::execQuery, Transaction::insertInto, Transaction::deleteFrom, Transaction::update, Transaction::prepare.
- \code
- void test()
- {
- QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
- db.setDatabaseName(":memory:");
- db.open();
- try
- {
- Transaction t(db);
- t.execNonQuery("CREATE TABLE table (a int, b int, c int, d text)");
- t.insertInto("table (a, b, c, d)")
- .values(1, 2, 3, "row1")
- .values(4, 5, 6, "row2")
- .values(7, 8, 9, "row3")
- .exec();
- PreparedQuery query = t.prepare("SELECT a, b, c, d FROM table");
- QueryResult res = query.exec();
- while (res.next())
- {
- QVariantMap map = res.toMap();
- qDebug() << map;
- }
- t.update("table")
- .set("a", 111)
- .set("b", 222)
- .where("c = ? OR c = ?", 3, 6);
- res = query.exec();
- while (res.next())
- {
- QVariantMap map = res.toMap();
- qDebug() << map;
- }
- t.commit(); //the transaction will be rolled back on exit from the scope (when calling the destructor) if you do not explicitly commit
- catch (const DBException &e)
- {
- //you can handle all the errors at one point
- //the transaction will be automatically rolled back on exception
- qDebug() << e.lastError << e.lastQuery;
- }
- }
- \endcode
- */
- class Transaction : public Database
- {
- Q_DISABLE_COPY(Transaction)
- public:
- explicit Transaction (const QSqlDatabase &db = QSqlDatabase())
- : Database(db)
- , m_commited(false)
- , m_started(false)
- {
- m_started = m_db.transaction();
- #ifdef DB_EXCEPTIONS_ENABLED
- if (!m_started)
- {
- throw DBException(m_db);
- }
- #endif
- }
- Transaction (Transaction&& other)
- : Database(std::move(other))
- {
- m_commited = other.m_commited;
- m_started = other.m_started;
- other.m_commited = false;
- other.m_started = false;
- }
- Transaction& operator=(Transaction&& other)
- {
- m_started = other.m_started;
- m_commited = other.m_commited;
- other.m_commited = false;
- other.m_started = false;
- return static_cast<Transaction&>(Database::operator=(std::move(other)));
- }
- ~Transaction()
- {
- if (m_db.isValid() && !m_commited)
- {
- m_db.rollback();
- }
- }
- /*!
- \brief Commits transaction
- The transaction will be rolled back on calling the destructor if not explicitly commited
- \throws DBException
- */
- bool commit()
- {
- if (m_db.isValid() && !m_commited)
- {
- m_commited = m_db.commit();
- #ifdef DB_EXCEPTIONS_ENABLED
- if (!m_commited)
- throw DBException(m_db);
- #endif
- }
- return m_commited;
- }
- /*!
- \brief Rolls back transaction
- */
- bool rollback()
- {
- bool res = false;
- if (m_db.isValid() && !m_commited)
- {
- res = m_db.rollback();
- m_commited = false;
- }
- return res;
- }
- /*!
- \brief Returns true if the transaction has been started successfully. Otherwise it returns false.
- */
- bool started() const
- {
- return m_started;
- }
- /*!
- \brief Returns true if the transaction has been commited successfully. Otherwise it returns false.
- */
- bool commited() const
- {
- return m_commited;
- }
- private:
- bool m_commited = false;
- bool m_started = false;
- };
- #endif // EASYQTSQL_TRANSACTION_H
|