LeechCraft  0.6.70-15082-g543737046d
Modular cross-platform feature rich live environment.
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 
18 namespace 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 
29  DBLock::~DBLock ()
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 
45  void DBLock::Init ()
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 
63  void DBLock::Good ()
64  {
65  Good_ = true;
66  }
67 
68  void DBLock::DumpError (const QSqlError& lastError)
69  {
70  qWarning () << lastError.text () << "|"
71  << lastError.type ();
72  }
73 
74  void DBLock::DumpError (const QSqlQuery& lastQuery)
75  {
76  qWarning () << "query:" << lastQuery.lastQuery ();
77  DumpError (lastQuery.lastError ());
78  qWarning () << "bound values:" << lastQuery.boundValues ();
79  }
80 
81  void DBLock::Execute (QSqlQuery& query)
82  {
83  if (query.exec ())
84  return;
85 
86  DumpError (query);
87  throw std::runtime_error ("Query execution failed.");
88  }
89 }
LC::Util
Definition: icoreproxy.h:33
dblock.h
LC::Util::DBLock::DBLock
DBLock(const DBLock &)=delete