Akonadi

countquerybuilder.h
1 /*
2  SPDX-FileCopyrightText: 2007 Volker Krause <[email protected]>
3 
4  SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6 
7 #ifndef AKONADI_COUNTQUERYBUILDER_H
8 #define AKONADI_COUNTQUERYBUILDER_H
9 
10 #include "akonadiserver_debug.h"
11 #include "storage/querybuilder.h"
12 
13 #include <QSqlError>
14 
15 namespace Akonadi
16 {
17 namespace Server
18 {
19 /**
20  Helper class for creating queries to count elements in a database.
21 */
23 {
24 public:
25  enum CountMode {
26  All,
27  Distinct,
28  };
29 
30  /**
31  Creates a new query builder that counts all entries in @p table.
32  */
33  explicit inline CountQueryBuilder(const QString &table)
34  : QueryBuilder(table, Select)
35  {
36  addColumn(QStringLiteral("count(*)"));
37  }
38 
39  /**
40  * Creates a new query builder that counts entries in @p column of @p table.
41  * If @p mode is set to @c Distinct, duplicate entries in that column are ignored.
42  */
43  inline CountQueryBuilder(const QString &table, const QString &column, CountMode mode)
44  : QueryBuilder(table, Select)
45  {
46  Q_ASSERT(!table.isEmpty());
47  Q_ASSERT(!column.isEmpty());
48  QString s = QStringLiteral("count(");
49  if (mode == Distinct) {
50  s += QLatin1String("DISTINCT ");
51  }
52  s += column;
53  s += QLatin1Char(')');
54  addColumn(s);
55  }
56 
57  /**
58  Returns the result of this query.
59  @returns -1 on error.
60  */
61  inline int result()
62  {
63  if (!query().next()) {
64  qCDebug(AKONADISERVER_LOG) << "Error during retrieving result of query:" << query().lastError().text();
65  return -1;
66  }
67  const auto result = query().value(0).toInt();
68  query().finish();
69  return result;
70  }
71 };
72 
73 } // namespace Server
74 } // namespace Akonadi
75 
76 #endif
CountQueryBuilder(const QString &table)
Creates a new query builder that counts all entries in table.
QVariant value(int index) const const
int result()
Returns the result of this query.
Helper class for creating queries to count elements in a database.
bool isEmpty() const const
void finish()
int toInt(bool *ok) const const
void addColumn(const QString &col)
Adds the given column to a select query.
QSqlError lastError() const const
QString text() const const
CountQueryBuilder(const QString &table, const QString &column, CountMode mode)
Creates a new query builder that counts entries in column of table.
QSqlQuery & query()
Returns the query, only valid after exec().
Helper class to construct arbitrary SQL queries.
Definition: querybuilder.h:31
Helper integration between Akonadi and Qt.
This file is part of the KDE documentation.
Documentation copyright © 1996-2022 The KDE developers.
Generated on Thu Jun 30 2022 03:51:45 by doxygen 1.8.17 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.