3e9de416904eae9f26752bebe25f553127047037
[quassel.git] / src / core / sqlitestorage.h
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #pragma once
22
23 #include <memory>
24
25 #include <QReadWriteLock>
26 #include <QSqlDatabase>
27
28 #include "abstractsqlstorage.h"
29
30 class QSqlQuery;
31
32 class SqliteStorage : public AbstractSqlStorage
33 {
34     Q_OBJECT
35
36 public:
37     SqliteStorage(QObject* parent = nullptr);
38
39     std::unique_ptr<AbstractSqlMigrationReader> createMigrationReader() override;
40
41 public slots:
42     /* General */
43
44     bool isAvailable() const override;
45     QString backendId() const override;
46     QString displayName() const override;
47     QVariantList setupData() const override { return {}; }
48     QString description() const override;
49
50     // TODO: Add functions for configuring the backlog handling, i.e. defining auto-cleanup settings etc
51
52     /* User handling */
53     UserId addUser(const QString& user, const QString& password, const QString& authenticator = "Database") override;
54     bool updateUser(UserId user, const QString& password) override;
55     void renameUser(UserId user, const QString& newName) override;
56     UserId validateUser(const QString& user, const QString& password) override;
57     UserId getUserId(const QString& username) override;
58     QString getUserAuthenticator(const UserId userid) override;
59     UserId internalUser() override;
60     void delUser(UserId user) override;
61     void setUserSetting(UserId userId, const QString& settingName, const QVariant& data) override;
62     QVariant getUserSetting(UserId userId, const QString& settingName, const QVariant& defaultData = QVariant()) override;
63     void setCoreState(const QVariantList& data) override;
64     QVariantList getCoreState(const QVariantList& data) override;
65
66     /* Identity handling */
67     IdentityId createIdentity(UserId user, CoreIdentity& identity) override;
68     bool updateIdentity(UserId user, const CoreIdentity& identity) override;
69     void removeIdentity(UserId user, IdentityId identityId) override;
70     std::vector<CoreIdentity> identities(UserId user) override;
71
72     /* Network handling */
73     NetworkId createNetwork(UserId user, const NetworkInfo& info) override;
74     bool updateNetwork(UserId user, const NetworkInfo& info) override;
75     bool removeNetwork(UserId user, const NetworkId& networkId) override;
76     std::vector<NetworkInfo> networks(UserId user) override;
77     std::vector<NetworkId> connectedNetworks(UserId user) override;
78     void setNetworkConnected(UserId user, const NetworkId& networkId, bool isConnected) override;
79
80     /* persistent channels */
81     QHash<QString, QString> persistentChannels(UserId user, const NetworkId& networkId) override;
82     void setChannelPersistent(UserId user, const NetworkId& networkId, const QString& channel, bool isJoined) override;
83     void setPersistentChannelKey(UserId user, const NetworkId& networkId, const QString& channel, const QString& key) override;
84
85     /* persistent user states */
86     QString awayMessage(UserId user, NetworkId networkId) override;
87     void setAwayMessage(UserId user, NetworkId networkId, const QString& awayMsg) override;
88     QString userModes(UserId user, NetworkId networkId) override;
89     void setUserModes(UserId user, NetworkId networkId, const QString& userModes) override;
90
91     /* Buffer handling */
92     BufferInfo bufferInfo(UserId user, const NetworkId& networkId, BufferInfo::Type type, const QString& buffer = "", bool create = true) override;
93     BufferInfo getBufferInfo(UserId user, const BufferId& bufferId) override;
94     std::vector<BufferInfo> requestBuffers(UserId user) override;
95     std::vector<BufferId> requestBufferIdsForNetwork(UserId user, NetworkId networkId) override;
96     bool removeBuffer(const UserId& user, const BufferId& bufferId) override;
97     bool renameBuffer(const UserId& user, const BufferId& bufferId, const QString& newName) override;
98     bool mergeBuffersPermanently(const UserId& user, const BufferId& bufferId1, const BufferId& bufferId2) override;
99     QHash<BufferId, MsgId> bufferLastMsgIds(UserId user) override;
100     void setBufferLastSeenMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override;
101     QHash<BufferId, MsgId> bufferLastSeenMsgIds(UserId user) override;
102     void setBufferMarkerLineMsg(UserId user, const BufferId& bufferId, const MsgId& msgId) override;
103     QHash<BufferId, MsgId> bufferMarkerLineMsgIds(UserId user) override;
104     void setBufferActivity(UserId id, BufferId bufferId, Message::Types type) override;
105     QHash<BufferId, Message::Types> bufferActivities(UserId id) override;
106     Message::Types bufferActivity(BufferId bufferId, MsgId lastSeenMsgId) override;
107     void setHighlightCount(UserId id, BufferId bufferId, int count) override;
108     QHash<BufferId, int> highlightCounts(UserId id) override;
109     int highlightCount(BufferId bufferId, MsgId lastSeenMsgId) override;
110     QHash<QString, QByteArray> bufferCiphers(UserId user, const NetworkId& networkId) override;
111     void setBufferCipher(UserId user, const NetworkId& networkId, const QString& bufferName, const QByteArray& cipher) override;
112
113     /* Message handling */
114     bool logMessage(Message& msg) override;
115     bool logMessages(MessageList& msgs) override;
116     std::vector<Message> requestMsgs(UserId user, BufferId bufferId, MsgId first = -1, MsgId last = -1, int limit = -1) override;
117     std::vector<Message> requestMsgsFiltered(UserId user,
118                                              BufferId bufferId,
119                                              MsgId first = -1,
120                                              MsgId last = -1,
121                                              int limit = -1,
122                                              Message::Types type = Message::Types{-1},
123                                              Message::Flags flags = Message::Flags{-1}) override;
124     std::vector<Message> requestAllMsgs(UserId user, MsgId first = -1, MsgId last = -1, int limit = -1) override;
125     std::vector<Message> requestAllMsgsFiltered(UserId user,
126                                                 MsgId first = -1,
127                                                 MsgId last = -1,
128                                                 int limit = -1,
129                                                 Message::Types type = Message::Types{-1},
130                                                 Message::Flags flags = Message::Flags{-1}) override;
131
132     /* Sysident handling */
133     QMap<UserId, QString> getAllAuthUserNames() override;
134
135 protected:
136     void setConnectionProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment) override
137     {
138         Q_UNUSED(properties);
139         Q_UNUSED(environment);
140         Q_UNUSED(loadFromEnvironment);
141     }
142     // SQLite does not have any connection properties to set
143     QString driverName() override { return "QSQLITE"; }
144     QString databaseName() override { return backlogFile(); }
145     int installedSchemaVersion() override;
146     bool updateSchemaVersion(int newVersion, bool clearUpgradeStep) override;
147     bool setupSchemaVersion(int version) override;
148
149     /**
150      * Gets the last successful schema upgrade step, or an empty string if no upgrade is in progress
151      *
152      * @return Filename of last successful schema upgrade query, or empty string if not upgrading
153      */
154     QString schemaVersionUpgradeStep() override;
155
156     /**
157      * Sets the last successful schema upgrade step
158      *
159      * @param upgradeQuery  The filename of the last successful schema upgrade query
160      * @return True if successfully set, otherwise false
161      */
162     virtual bool setSchemaVersionUpgradeStep(QString upgradeQuery) override;
163
164     bool safeExec(QSqlQuery& query, int retryCount = 0);
165
166 private:
167     static QString backlogFile();
168     void bindNetworkInfo(QSqlQuery& query, const NetworkInfo& info);
169     void bindServerInfo(QSqlQuery& query, const Network::Server& server);
170
171     inline void lockForRead() { _dbLock.lockForRead(); }
172     inline void lockForWrite() { _dbLock.lockForWrite(); }
173     inline void unlock() { _dbLock.unlock(); }
174     QReadWriteLock _dbLock;
175     static int _maxRetryCount;
176 };
177
178 // ========================================
179 //  SqliteMigration
180 // ========================================
181 class SqliteMigrationReader : public SqliteStorage, public AbstractSqlMigrationReader
182 {
183     Q_OBJECT
184
185 public:
186     SqliteMigrationReader();
187
188     bool readMo(QuasselUserMO& user) override;
189     bool readMo(SenderMO& sender) override;
190     bool readMo(IdentityMO& identity) override;
191     bool readMo(IdentityNickMO& identityNick) override;
192     bool readMo(NetworkMO& network) override;
193     bool readMo(BufferMO& buffer) override;
194     bool readMo(BacklogMO& backlog) override;
195     bool readMo(IrcServerMO& ircserver) override;
196     bool readMo(UserSettingMO& userSetting) override;
197     bool readMo(CoreStateMO& coreState) override;
198
199     bool prepareQuery(MigrationObject mo) override;
200
201     qint64 stepSize() { return 50000; }
202
203 protected:
204     bool transaction() override { return logDb().transaction(); }
205     void rollback() override { logDb().rollback(); }
206     bool commit() override { return logDb().commit(); }
207
208 private:
209     void setMaxId(MigrationObject mo);
210     qint64 _maxId{0};
211 };
212
213 inline std::unique_ptr<AbstractSqlMigrationReader> SqliteStorage::createMigrationReader()
214 {
215     return std::unique_ptr<AbstractSqlMigrationReader>{new SqliteMigrationReader()};
216 }