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 ***************************************************************************/
27 #include <QSqlDatabase>
35 class AbstractSqlMigrationReader;
36 class AbstractSqlMigrationWriter;
38 class AbstractSqlStorage : public Storage
43 AbstractSqlStorage(QObject* parent = nullptr);
44 ~AbstractSqlStorage() override;
46 virtual std::unique_ptr<AbstractSqlMigrationReader> createMigrationReader() { return {}; }
47 virtual std::unique_ptr<AbstractSqlMigrationWriter> createMigrationWriter() { return {}; }
50 * An SQL query with associated resource filename
52 struct SqlQueryResource {
53 QString queryString; ///< SQL query string
54 QString queryFilename; ///< Path to the resource file providing this query
56 SqlQueryResource(const QString& queryString, const QString& queryFilename)
57 : queryString(std::move(queryString)),
58 queryFilename(std::move(queryFilename)) {}
62 State init(const QVariantMap& settings = QVariantMap(),
63 const QProcessEnvironment& environment = {},
64 bool loadFromEnvironment = false) override;
65 bool setup(const QVariantMap& settings = QVariantMap(),
66 const QProcessEnvironment& environment = {},
67 bool loadFromEnvironment = false) override;
70 inline void sync() override{};
75 * Fetch an SQL query string by name and optional schema version
77 * Loads the named SQL query from the built-in SQL resource collection, returning it as a
78 * string. If a version is specified, it'll be loaded from the schema version-specific folder
81 * @see schemaVersion()
83 * @param[in] queryName File name of the SQL query, minus the .sql extension
86 * SQL schema version; if 0, fetches from current version, otherwise loads from the specified
87 * schema version instead of the current schema files.
89 * @return String with the requested SQL query, ready for parameter substitution
91 QString queryString(const QString& queryName, int version = 0);
94 * Gets the collection of SQL setup queries and filenames to create a new database
96 * @return List of SQL query strings and filenames
98 QList<SqlQueryResource> setupQueries();
101 * Gets the collection of SQL upgrade queries and filenames for a given schema version
103 * @param ver SQL schema version
104 * @return List of SQL query strings and filenames
106 QList<SqlQueryResource> upgradeQueries(int ver);
109 bool watchQuery(QSqlQuery& query);
112 virtual int installedSchemaVersion() { return -1; };
115 * Update the stored schema version number, optionally clearing the record of mid-schema steps
117 * @param newVersion New schema version number
118 * @param clearUpgradeStep If true, clear the record of any in-progress schema upgrades
121 virtual bool updateSchemaVersion(int newVersion, bool clearUpgradeStep = true) = 0;
123 virtual bool setupSchemaVersion(int version) = 0;
126 * Gets the last successful schema upgrade step, or an empty string if no upgrade is in progress
128 * @return Filename of last successful schema upgrade query, or empty string if not upgrading
130 virtual QString schemaVersionUpgradeStep();
133 * Sets the last successful schema upgrade step
135 * @param upgradeQuery The filename of the last successful schema upgrade query
136 * @return True if successfully set, otherwise false
138 virtual bool setSchemaVersionUpgradeStep(QString upgradeQuery) = 0;
140 virtual void setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) = 0;
141 virtual QString driverName() = 0;
142 inline virtual QString hostName() { return QString(); }
143 inline virtual int port() { return -1; }
144 virtual QString databaseName() = 0;
145 inline virtual QString userName() { return QString(); }
146 inline virtual QString password() { return QString(); }
148 //! Initialize db specific features on connect
149 /** This is called every time a connection to a specific SQL backend is established
150 * the default implementation does nothing.
152 * When reimplementing this method, don't use logDB() inside this function as
153 * this would cause as we're just about to initialize that DB connection.
155 inline virtual bool initDbSession(QSqlDatabase& /* db */) { return true; }
158 void connectionDestroyed();
161 void addConnectionToPool();
162 void dbConnect(QSqlDatabase& db);
164 int _schemaVersion{0};
167 static int _nextConnectionId;
168 QMutex _connectionPoolMutex;
169 // we let a Connection Object manage each actual db connection
170 // those objects reside in the thread the connection belongs to
171 // which allows us thread safe termination of a connection
173 QHash<QThread*, Connection*> _connectionPool;
182 friend uint qHash(const SenderData& key);
183 friend bool operator==(const SenderData& a, const SenderData& b);
186 // ========================================
187 // AbstractSqlStorage::Connection
188 // ========================================
189 class AbstractSqlStorage::Connection : public QObject
194 Connection(const QString& name, QObject* parent = nullptr);
195 ~Connection() override;
197 inline QLatin1String name() const { return QLatin1String(_name); }
203 // ========================================
204 // AbstractSqlMigrator
205 // ========================================
206 class AbstractSqlMigrator
216 QString authenticator;
231 QString identityname;
234 bool awayNickEnabled;
236 bool awayReasonEnabled;
237 bool autoAwayEnabled;
239 QString autoAwayReason;
240 bool autoAwayReasonEnabled;
241 bool detachAwayEnabled;
242 QString detachAwayReason;
243 bool detachAwayReasonEnabled;
252 struct IdentityNickMO
255 IdentityId identityId;
264 QString autoidentifyservice;
265 QString autoidentifypassword;
267 QString saslpassword;
269 QString encodingcodec;
270 QString decodingcodec;
273 QString attachperform;
274 QString detachperform;
276 IdentityId identityid;
277 int messagerateburstsize;
278 int messageratedelay;
279 int autoreconnectinterval;
280 int autoreconnectretries;
282 bool userandomserver;
283 bool useautoidentify;
285 bool useautoreconnect;
286 bool unlimitedconnectretries;
287 bool usecustommessagerate;
288 bool unlimitedmessagerate;
302 qint64 lastseenmsgid;
303 qint64 markerlinemsgid;
314 QDateTime time; // has to be in UTC!
319 QString senderprefixes;
332 bool sslverify; /// If true, validate SSL certificates
346 QByteArray settingvalue;
369 virtual ~AbstractSqlMigrator() = default;
371 static QString migrationObject(MigrationObject moType);
374 void newQuery(const QString& query, QSqlDatabase db);
375 virtual void resetQuery();
376 virtual bool prepareQuery(MigrationObject mo) = 0;
378 inline bool next() { return _query->next(); }
379 inline QVariant value(int index) { return _query->value(index); }
380 inline void bindValue(const QString& placeholder, const QVariant& val) { _query->bindValue(placeholder, val); }
381 inline void bindValue(int pos, const QVariant& val) { _query->bindValue(pos, val); }
383 inline QSqlError lastError() { return _query ? _query->lastError() : QSqlError(); }
385 inline QString executedQuery() { return _query ? _query->executedQuery() : QString(); }
386 inline QVariantList boundValues();
388 virtual bool transaction() = 0;
389 virtual void rollback() = 0;
390 virtual bool commit() = 0;
393 QSqlQuery* _query{nullptr};
396 class AbstractSqlMigrationReader : public AbstractSqlMigrator
399 AbstractSqlMigrationReader();
401 virtual bool readMo(QuasselUserMO& user) = 0;
402 virtual bool readMo(IdentityMO& identity) = 0;
403 virtual bool readMo(IdentityNickMO& identityNick) = 0;
404 virtual bool readMo(NetworkMO& network) = 0;
405 virtual bool readMo(BufferMO& buffer) = 0;
406 virtual bool readMo(SenderMO& sender) = 0;
407 virtual bool readMo(BacklogMO& backlog) = 0;
408 virtual bool readMo(IrcServerMO& ircserver) = 0;
409 virtual bool readMo(UserSettingMO& userSetting) = 0;
410 virtual bool readMo(CoreStateMO& coreState) = 0;
412 bool migrateTo(AbstractSqlMigrationWriter* writer);
415 void abortMigration(const QString& errorMsg = QString());
416 bool finalizeMigration();
419 bool transferMo(MigrationObject moType, T& mo);
421 AbstractSqlMigrationWriter* _writer{nullptr};
424 class AbstractSqlMigrationWriter : public AbstractSqlMigrator
427 virtual bool writeMo(const QuasselUserMO& user) = 0;
428 virtual bool writeMo(const IdentityMO& identity) = 0;
429 virtual bool writeMo(const IdentityNickMO& identityNick) = 0;
430 virtual bool writeMo(const NetworkMO& network) = 0;
431 virtual bool writeMo(const BufferMO& buffer) = 0;
432 virtual bool writeMo(const SenderMO& sender) = 0;
433 virtual bool writeMo(const BacklogMO& backlog) = 0;
434 virtual bool writeMo(const IrcServerMO& ircserver) = 0;
435 virtual bool writeMo(const UserSettingMO& userSetting) = 0;
436 virtual bool writeMo(const CoreStateMO& coreState) = 0;
438 inline bool migrateFrom(AbstractSqlMigrationReader* reader) { return reader->migrateTo(this); }
440 // called after migration process
441 virtual inline bool postProcess() { return true; }
442 friend class AbstractSqlMigrationReader;