LeechCraft 0.6.70-16373-g319c272718
Modular cross-platform feature rich live environment.
Loading...
Searching...
No Matches
dblock.cpp
Go to the documentation of this file.
1/**********************************************************************
2 * LeechCraft - modular cross-platform feature rich internet client.
3 * Copyright (C) 2006-2014 Georg Rudoy
4 *
5 * Distributed under the Boost Software License, Version 1.0.
6 * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
7 **********************************************************************/
8
9#include "dblock.h"
10#include <stdexcept>
11#include <QSqlDatabase>
12#include <QSqlError>
13#include <QSqlQuery>
14#include <QMutexLocker>
15#include <QVariant>
16#include <QtDebug>
17
18namespace LC::Util
19{
20 QSet<QString> DBLock::LockedBases_;
21
22 QMutex DBLock::LockedMutex_;
23
24 DBLock::DBLock (QSqlDatabase& database)
25 : Database_ { database }
26 {
27 }
28
30 {
31 if (!Initialized_)
32 return;
33
34 if (Good_ ?
35 !Database_.commit () :
36 !Database_.rollback ())
37 DumpError (Database_.lastError ());
38
39 {
40 QMutexLocker locker (&LockedMutex_);
41 LockedBases_.remove (Database_.connectionName ());
42 }
43 }
44
46 {
47 {
48 QMutexLocker locker (&LockedMutex_);
49 const auto& conn = Database_.connectionName ();
50 if (LockedBases_.contains (conn))
51 return;
52 LockedBases_ << conn;
53 }
54
55 if (!Database_.transaction ())
56 {
57 DumpError (Database_.lastError ());
58 throw std::runtime_error ("Could not start transaction");
59 }
60 Initialized_ = true;
61 }
62
64 {
65 Good_ = true;
66 }
67
68 void DBLock::DumpError (const QSqlError& lastError)
69 {
70 qCritical () << lastError.text () << "|"
71 << lastError.type ()
72 << lastError.nativeErrorCode ();
73 }
74
75 void DBLock::DumpError (const QSqlQuery& lastQuery)
76 {
77 qCritical () << "query:" << lastQuery.lastQuery ().simplified ();
78 DumpError (lastQuery.lastError ());
79
80 const auto& boundValues = lastQuery.boundValues ();
81 qCritical () << "bound keys:" << boundValues.size () << boundValues.keys ();
82 qCritical () << "bound values:" << boundValues;
83 }
84
85 void DBLock::Execute (QSqlQuery& query)
86 {
87 if (query.exec ())
88 return;
89
90 DumpError (query);
91 throw std::runtime_error ("Query execution failed.");
92 }
93}
DBLock(const DBLock &)=delete
static UTIL_DB_API void Execute(QSqlQuery &query)
Tries to execute the given query.
Definition dblock.cpp:85
UTIL_DB_API void Init()
Initializes the transaction.
Definition dblock.cpp:45
UTIL_DB_API ~DBLock()
Destructor.
Definition dblock.cpp:29
UTIL_DB_API void Good()
Notifies the lock about successful higher-level operations.
Definition dblock.cpp:63
static UTIL_DB_API void DumpError(const QSqlError &error)
Dumps the error to the qWarning() stream.
Definition dblock.cpp:68