1 /***************************************************************************
2 * Copyright (C) 2005-2019 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
28 #include <QSqlDatabase>
32 class AbstractSqlMigrationReader;
33 class AbstractSqlMigrationWriter;
35 class AbstractSqlStorage : public Storage
40 AbstractSqlStorage(QObject *parent = 0);
41 virtual ~AbstractSqlStorage();
43 virtual std::unique_ptr<AbstractSqlMigrationReader> createMigrationReader() { return {}; }
44 virtual std::unique_ptr<AbstractSqlMigrationWriter> createMigrationWriter() { return {}; }
47 * An SQL query with associated resource filename
49 struct SqlQueryResource {
50 QString queryString; ///< SQL query string
51 QString queryFilename; ///< Path to the resource file providing this query
53 SqlQueryResource(const QString& queryString, const QString& queryFilename)
54 : queryString(std::move(queryString)),
55 queryFilename(std::move(queryFilename)) {}
59 virtual State init(const QVariantMap &settings = QVariantMap(),
60 const QProcessEnvironment &environment = {},
61 bool loadFromEnvironment = false);
62 virtual bool setup(const QVariantMap &settings = QVariantMap(),
63 const QProcessEnvironment &environment = {},
64 bool loadFromEnvironment = false);
67 inline virtual void sync() {};
72 * Fetch an SQL query string by name and optional schema version
74 * Loads the named SQL query from the built-in SQL resource collection, returning it as a
75 * string. If a version is specified, it'll be loaded from the schema version-specific folder
78 * @see schemaVersion()
80 * @param[in] queryName File name of the SQL query, minus the .sql extension
83 * SQL schema version; if 0, fetches from current version, otherwise loads from the specified
84 * schema version instead of the current schema files.
86 * @return String with the requested SQL query, ready for parameter substitution
88 QString queryString(const QString &queryName, int version = 0);
91 * Gets the collection of SQL setup queries and filenames to create a new database
93 * @return List of SQL query strings and filenames
95 QList<SqlQueryResource> setupQueries();
98 * Gets the collection of SQL upgrade queries and filenames for a given schema version
100 * @param ver SQL schema version
101 * @return List of SQL query strings and filenames
103 QList<SqlQueryResource> upgradeQueries(int ver);
106 bool watchQuery(QSqlQuery &query);
109 virtual int installedSchemaVersion() { return -1; };
112 * Update the stored schema version number, optionally clearing the record of mid-schema steps
114 * @param newVersion New schema version number
115 * @param clearUpgradeStep If true, clear the record of any in-progress schema upgrades
118 virtual bool updateSchemaVersion(int newVersion, bool clearUpgradeStep = true) = 0;
120 virtual bool setupSchemaVersion(int version) = 0;
123 * Gets the last successful schema upgrade step, or an empty string if no upgrade is in progress
125 * @return Filename of last successful schema upgrade query, or empty string if not upgrading
127 virtual QString schemaVersionUpgradeStep();
130 * Sets the last successful schema upgrade step
132 * @param upgradeQuery The filename of the last successful schema upgrade query
133 * @return True if successfully set, otherwise false
135 virtual bool setSchemaVersionUpgradeStep(QString upgradeQuery) = 0;
136 virtual void setConnectionProperties(const QVariantMap &properties,
137 const QProcessEnvironment &environment,
138 bool loadFromEnvironment) = 0;
139 virtual QString driverName() = 0;
140 inline virtual QString hostName() { return QString(); }
141 inline virtual int port() { return -1; }
142 virtual QString databaseName() = 0;
143 inline virtual QString userName() { return QString(); }
144 inline virtual QString password() { return QString(); }
146 //! Initialize db specific features on connect
147 /** This is called every time a connection to a specific SQL backend is established
148 * the default implementation does nothing.
150 * When reimplementing this method, don't use logDB() inside this function as
151 * this would cause as we're just about to initialize that DB connection.
153 inline virtual bool initDbSession(QSqlDatabase & /* db */) { return true; }
156 void connectionDestroyed();
159 void addConnectionToPool();
160 void dbConnect(QSqlDatabase &db);
165 static int _nextConnectionId;
166 QMutex _connectionPoolMutex;
167 // we let a Connection Object manage each actual db connection
168 // those objects reside in the thread the connection belongs to
169 // which allows us thread safe termination of a connection
171 QHash<QThread *, Connection *> _connectionPool;
179 friend uint qHash(const SenderData &key);
180 friend bool operator==(const SenderData &a, const SenderData &b);
183 // ========================================
184 // AbstractSqlStorage::Connection
185 // ========================================
186 class AbstractSqlStorage::Connection : public QObject
191 Connection(const QString &name, QObject *parent = 0);
194 inline QLatin1String name() const { return QLatin1String(_name); }
201 // ========================================
202 // AbstractSqlMigrator
203 // ========================================
204 class AbstractSqlMigrator
208 struct QuasselUserMO {
213 QString authenticator;
221 SenderMO() : senderId(0) {}
227 QString identityname;
230 bool awayNickEnabled;
232 bool awayReasonEnabled;
233 bool autoAwayEnabled;
235 QString autoAwayReason;
236 bool autoAwayReasonEnabled;
237 bool detachAwayEnabled;
238 QString detachAwayReason;
239 bool detachAwayReasonEnabled;
248 struct IdentityNickMO {
250 IdentityId identityId;
258 QString autoidentifyservice;
259 QString autoidentifypassword;
261 QString saslpassword;
263 QString encodingcodec;
264 QString decodingcodec;
267 QString attachperform;
268 QString detachperform;
270 IdentityId identityid;
271 int messagerateburstsize;
272 int messageratedelay;
273 int autoreconnectinterval;
274 int autoreconnectretries;
276 bool userandomserver;
277 bool useautoidentify;
279 bool useautoreconnect;
280 bool unlimitedconnectretries;
281 bool usecustommessagerate;
282 bool unlimitedmessagerate;
295 qint64 lastseenmsgid;
296 qint64 markerlinemsgid;
306 QDateTime time; // has to be in UTC!
311 QString senderprefixes;
323 bool sslverify; /// If true, validate SSL certificates
333 struct UserSettingMO {
336 QByteArray settingvalue;
344 enum MigrationObject {
357 AbstractSqlMigrator();
358 virtual ~AbstractSqlMigrator() {}
360 static QString migrationObject(MigrationObject moType);
363 void newQuery(const QString &query, QSqlDatabase db);
364 virtual void resetQuery();
365 virtual bool prepareQuery(MigrationObject mo) = 0;
367 inline bool next() { return _query->next(); }
368 inline QVariant value(int index) { return _query->value(index); }
369 inline void bindValue(const QString &placeholder, const QVariant &val) { _query->bindValue(placeholder, val); }
370 inline void bindValue(int pos, const QVariant &val) { _query->bindValue(pos, val); }
372 inline QSqlError lastError() { return _query ? _query->lastError() : QSqlError(); }
374 inline QString executedQuery() { return _query ? _query->executedQuery() : QString(); }
375 inline QVariantList boundValues();
377 virtual bool transaction() = 0;
378 virtual void rollback() = 0;
379 virtual bool commit() = 0;
386 class AbstractSqlMigrationReader : public AbstractSqlMigrator
389 AbstractSqlMigrationReader();
391 virtual bool readMo(QuasselUserMO &user) = 0;
392 virtual bool readMo(IdentityMO &identity) = 0;
393 virtual bool readMo(IdentityNickMO &identityNick) = 0;
394 virtual bool readMo(NetworkMO &network) = 0;
395 virtual bool readMo(BufferMO &buffer) = 0;
396 virtual bool readMo(SenderMO &sender) = 0;
397 virtual bool readMo(BacklogMO &backlog) = 0;
398 virtual bool readMo(IrcServerMO &ircserver) = 0;
399 virtual bool readMo(UserSettingMO &userSetting) = 0;
400 virtual bool readMo(CoreStateMO &coreState) = 0;
402 bool migrateTo(AbstractSqlMigrationWriter *writer);
405 void abortMigration(const QString &errorMsg = QString());
406 bool finalizeMigration();
408 template<typename T> bool transferMo(MigrationObject moType, T &mo);
410 AbstractSqlMigrationWriter *_writer;
414 class AbstractSqlMigrationWriter : public AbstractSqlMigrator
417 virtual bool writeMo(const QuasselUserMO &user) = 0;
418 virtual bool writeMo(const IdentityMO &identity) = 0;
419 virtual bool writeMo(const IdentityNickMO &identityNick) = 0;
420 virtual bool writeMo(const NetworkMO &network) = 0;
421 virtual bool writeMo(const BufferMO &buffer) = 0;
422 virtual bool writeMo(const SenderMO &sender) = 0;
423 virtual bool writeMo(const BacklogMO &backlog) = 0;
424 virtual bool writeMo(const IrcServerMO &ircserver) = 0;
425 virtual bool writeMo(const UserSettingMO &userSetting) = 0;
426 virtual bool writeMo(const CoreStateMO &coreState) = 0;
428 inline bool migrateFrom(AbstractSqlMigrationReader *reader) { return reader->migrateTo(this); }
430 // called after migration process
431 virtual inline bool postProcess() { return true; }
432 friend class AbstractSqlMigrationReader;