Akonadi

dbaccess.cpp
1/*
2 SPDX-FileCopyrightText: 2009 Volker Krause <vkrause@kde.org>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5*/
6
7#include "dbaccess.h"
8
9#include <Akonadi/ServerManager>
10
11#include <QSettings>
12#include <QSqlDatabase>
13#include <QSqlError>
14#include <QSqlQuery>
15
16#include <KMessageBox>
17
18using namespace Akonadi;
19
20class DbAccessPrivate
21{
22public:
23 DbAccessPrivate()
24 {
25 init();
26 }
27
28 void init()
29 {
30 const QString serverConfigFile = ServerManager::serverConfigFilePath(ServerManager::ReadWrite);
31 QSettings settings(serverConfigFile, QSettings::IniFormat);
32
33 const QString driver = settings.value(QStringLiteral("General/Driver"), QStringLiteral("QMYSQL")).toString();
34 database = QSqlDatabase::addDatabase(driver);
35 settings.beginGroup(driver);
36 database.setHostName(settings.value(QStringLiteral("Host"), QString()).toString());
37 database.setDatabaseName(settings.value(QStringLiteral("Name"), QStringLiteral("akonadi")).toString());
38 database.setUserName(settings.value(QStringLiteral("User"), QString()).toString());
39 database.setPassword(settings.value(QStringLiteral("Password"), QString()).toString());
40 database.setConnectOptions(settings.value(QStringLiteral("Options"), QString()).toString());
41 if (!database.open()) {
42 KMessageBox::error(nullptr, QStringLiteral("Failed to connect to database: %1").arg(database.lastError().text()));
43 }
44 }
45
46 QSqlDatabase database;
47};
48
49Q_GLOBAL_STATIC(DbAccessPrivate, sInstance)
50QSqlDatabase DbAccess::database()
51{
52 // hack to detect database gone away error
53 QSqlQuery query(sInstance->database);
54 // prepare or exec of "SELECT 1" will only fail when we are not connected to database
55 if (!query.prepare(QStringLiteral("SELECT 1")) || !query.exec()) {
56 sInstance->database.close();
57 QSqlDatabase::removeDatabase(sInstance->database.connectionName());
58 sInstance->init();
59 }
60 return sInstance->database;
61}
Helper integration between Akonadi and Qt.
char * toString(const EngineQuery &query)
KSERVICE_EXPORT KService::List query(FilterFunc filterFunc)
void error(QWidget *parent, const QString &text, const QString &title, const KGuiItem &buttonOk, Options options=Notify)
QSqlDatabase addDatabase(QSqlDriver *driver, const QString &connectionName)
QSqlError lastError() const const
void removeDatabase(const QString &connectionName)
void setConnectOptions(const QString &options)
void setDatabaseName(const QString &name)
void setHostName(const QString &host)
void setPassword(const QString &password)
void setUserName(const QString &name)
QString text() const const
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Mon Nov 4 2024 16:31:59 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.