File indexing completed on 2025-01-05 04:46:55
0001 /* 0002 SPDX-FileCopyrightText: 2007 Volker Krause <vkrause@kde.org> 0003 0004 SPDX-License-Identifier: LGPL-2.0-or-later 0005 */ 0006 0007 #ifndef AKONADI_COUNTQUERYBUILDER_H 0008 #define AKONADI_COUNTQUERYBUILDER_H 0009 0010 #include "akonadiserver_debug.h" 0011 #include "storage/datastore.h" 0012 #include "storage/querybuilder.h" 0013 0014 #include <QSqlError> 0015 0016 namespace Akonadi 0017 { 0018 namespace Server 0019 { 0020 /** 0021 Helper class for creating queries to count elements in a database. 0022 */ 0023 class CountQueryBuilder : public QueryBuilder 0024 { 0025 public: 0026 enum CountMode { 0027 All, 0028 Distinct, 0029 }; 0030 0031 /** 0032 Creates a new query builder that counts all entries in @p table. 0033 */ 0034 explicit inline CountQueryBuilder(const QString &table) 0035 : CountQueryBuilder(DataStore::self(), table) 0036 { 0037 } 0038 0039 inline CountQueryBuilder(DataStore *store, const QString &table) 0040 : QueryBuilder(store, table, Select) 0041 { 0042 addColumn(QStringLiteral("count(*)")); 0043 } 0044 0045 /** 0046 * Creates a new query builder that counts entries in @p column of @p table. 0047 * If @p mode is set to @c Distinct, duplicate entries in that column are ignored. 0048 */ 0049 inline CountQueryBuilder(const QString &table, const QString &column, CountMode mode) 0050 : CountQueryBuilder(DataStore::self(), table, column, mode) 0051 { 0052 } 0053 0054 inline CountQueryBuilder(DataStore *store, const QString &table, const QString &column, CountMode mode) 0055 : QueryBuilder(store, table, Select) 0056 { 0057 Q_ASSERT(!table.isEmpty()); 0058 Q_ASSERT(!column.isEmpty()); 0059 QString s = QStringLiteral("count("); 0060 if (mode == Distinct) { 0061 s += QLatin1StringView("DISTINCT "); 0062 } 0063 s += column; 0064 s += QLatin1Char(')'); 0065 addColumn(s); 0066 } 0067 0068 /** 0069 Returns the result of this query. 0070 @returns -1 on error. 0071 */ 0072 inline int result() 0073 { 0074 if (!query().next()) { 0075 qCDebug(AKONADISERVER_LOG) << "Error during retrieving result of query:" << query().lastError().text(); 0076 return -1; 0077 } 0078 const auto result = query().value(0).toInt(); 0079 query().finish(); 0080 return result; 0081 } 0082 }; 0083 0084 } // namespace Server 0085 } // namespace Akonadi 0086 0087 #endif