File indexing completed on 2025-01-05 04:46:57

0001 /*
0002     SPDX-FileCopyrightText: 2019 David Faure <faure@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #pragma once
0008 
0009 #include "dbexception.h"
0010 
0011 namespace Akonadi
0012 {
0013 namespace Server
0014 {
0015 /**
0016   This class catches DbDeadlockException (as emitted by QueryBuilder)
0017   and retries execution of the method when it happens, as required by
0018   SQL databases.
0019 */
0020 class DbDeadlockCatcher
0021 {
0022 public:
0023     template<typename Func>
0024     explicit DbDeadlockCatcher(Func &&func)
0025     {
0026         callFunc(func, 0);
0027     }
0028 
0029 private:
0030     static const int MaxRecursion = 5;
0031     template<typename Func>
0032     void callFunc(Func &&func, int recursionCounter)
0033     {
0034         try {
0035             func();
0036         } catch (const DbDeadlockException &) {
0037             if (recursionCounter == MaxRecursion) {
0038                 throw;
0039             } else {
0040                 callFunc(func, ++recursionCounter); // recurse
0041             }
0042         }
0043     }
0044 };
0045 
0046 } // namespace Server
0047 } // namespace Akonadi