QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
qgshistoryproviderregistry.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgshistoryproviderregistry.cpp
3 -------------------------
4 begin : April 2019
5 copyright : (C) 2019 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8/***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
18#include "qgshistoryprovider.h"
19#include "qgsapplication.h"
20#include "qgsruntimeprofiler.h"
21#include "qgslogger.h"
22#include "qgsxmlutils.h"
24#include "qgsprocessingutils.h"
25#include "qgshistoryentry.h"
27
28#include <QFile>
29#include <sqlite3.h>
30
31QgsHistoryProviderRegistry::QgsHistoryProviderRegistry( QObject *parent, bool useMemoryDatabase )
32 : QObject( parent )
33{
34 QgsScopedRuntimeProfile profile( tr( "Load history database" ) );
35 const QString historyFilename = userHistoryDbPath();
36
37 // create history db if it doesn't exist
38 QString error;
39 if ( useMemoryDatabase )
40 {
41 createDatabase( QStringLiteral( ":memory:" ), error );
42 }
43 else
44 {
45 if ( !QFile::exists( historyFilename ) )
46 {
47 createDatabase( historyFilename, error );
48 }
49 else
50 {
51 openDatabase( historyFilename, error );
52 }
53 }
54}
55
57{
58 qDeleteAll( mProviders );
59}
60
62{
65}
66
68{
69 if ( mProviders.contains( provider->id() ) )
70 return false;
71
72 mProviders.insert( provider->id(), provider );
73 return true;
74}
75
77{
78 return mProviders.value( id );
79}
80
82{
83 if ( !mProviders.contains( id ) )
84 return false;
85
86 delete mProviders.take( id );
87 return true;
88}
89
91{
92 return mProviders.keys();
93}
94
95long long QgsHistoryProviderRegistry::addEntry( const QString &providerId, const QVariantMap &entry, bool &ok, QgsHistoryProviderRegistry::HistoryEntryOptions options )
96{
97 return addEntry( QgsHistoryEntry( providerId, QDateTime::currentDateTime(), entry ), ok, options );
98}
99
101{
102 ok = true;
103 long long id = -1;
105 {
106 QDomDocument xmlDoc;
107 const QVariant cleanedMap = QgsProcessingUtils::removePointerValuesFromMap( entry.entry );
108 xmlDoc.appendChild( QgsXmlUtils::writeVariant( cleanedMap, xmlDoc ) );
109 const QString entryXml = xmlDoc.toString();
110 const QString dateTime = entry.timestamp.toString( QStringLiteral( "yyyy-MM-dd HH:mm:ss" ) );
111
112 QString query = qgs_sqlite3_mprintf( "INSERT INTO history VALUES (NULL, '%q', '%q', '%q');",
113 entry.providerId.toUtf8().constData(), entryXml.toUtf8().constData(), dateTime.toUtf8().constData() );
114 if ( !runEmptyQuery( query ) )
115 {
116 QgsDebugError( QStringLiteral( "Couldn't story history entry in database!" ) );
117 ok = false;
118 return -1;
119 }
120 id = static_cast< int >( sqlite3_last_insert_rowid( mLocalDB.get() ) );
121
122 QgsHistoryEntry addedEntry( entry );
123 addedEntry.id = id;
124
126 }
127
128 return id;
129}
130
131bool QgsHistoryProviderRegistry::addEntries( const QList<QgsHistoryEntry> &entries, HistoryEntryOptions options )
132{
133 bool ok = true;
135 {
136 runEmptyQuery( QStringLiteral( "BEGIN TRANSACTION;" ) );
137 for ( const QgsHistoryEntry &entry : entries )
138 addEntry( entry, ok, options );
139 runEmptyQuery( QStringLiteral( "COMMIT TRANSACTION;" ) );
140 }
141
142 return ok;
143}
144
146{
147 ok = false;
148 switch ( backend )
149 {
151 {
152 if ( !mLocalDB )
153 {
154 QgsDebugError( QStringLiteral( "Cannot open database to query history entries" ) );
155 return QgsHistoryEntry( QVariantMap() );
156 }
157
158 QString sql = QStringLiteral( "SELECT provider_id, xml, timestamp FROM history WHERE id=%1" ).arg( id );
159
160 int nErr;
161 sqlite3_statement_unique_ptr statement = mLocalDB.prepare( sql, nErr );
162
163 if ( nErr == SQLITE_OK && sqlite3_step( statement.get() ) == SQLITE_ROW )
164 {
165 QDomDocument doc;
166 if ( !doc.setContent( statement.columnAsText( 1 ) ) )
167 {
168 QgsDebugError( QStringLiteral( "Cannot read history entry" ) );
169 return QgsHistoryEntry( QVariantMap() );
170 }
171
172 ok = true;
174 statement.columnAsText( 0 ),
175 QDateTime::fromString( statement.columnAsText( 2 ), QStringLiteral( "yyyy-MM-dd HH:mm:ss" ) ),
176 QgsXmlUtils::readVariant( doc.documentElement() ).toMap()
177 );
178 res.id = id;
179 return res;
180 }
181
182 QgsDebugError( QStringLiteral( "Cannot find history item with matching ID" ) );
183 return QgsHistoryEntry( QVariantMap() );
184 }
185 }
187}
188
189bool QgsHistoryProviderRegistry::updateEntry( long long id, const QVariantMap &entry, Qgis::HistoryProviderBackend backend )
190{
191 switch ( backend )
192 {
194 {
195 const QVariantMap cleanedMap = QgsProcessingUtils::removePointerValuesFromMap( entry );
196 QDomDocument xmlDoc;
197 xmlDoc.appendChild( QgsXmlUtils::writeVariant( cleanedMap, xmlDoc ) );
198 const QString entryXml = xmlDoc.toString();
199
200 QString query = qgs_sqlite3_mprintf( "UPDATE history SET xml='%q' WHERE id = %d;",
201 entryXml.toUtf8().constData(), id );
202 if ( !runEmptyQuery( query ) )
203 {
204 QgsDebugError( QStringLiteral( "Couldn't update history entry in database!" ) );
205 return false;
206 }
207
209 return true;
210 }
211 }
213}
214
215QList<QgsHistoryEntry> QgsHistoryProviderRegistry::queryEntries( const QDateTime &start, const QDateTime &end, const QString &providerId, Qgis::HistoryProviderBackends backends ) const
216{
217 QList<QgsHistoryEntry> entries;
219 {
220 if ( !mLocalDB )
221 {
222 QgsDebugError( QStringLiteral( "Cannot open database to query history entries" ) );
223 return {};
224 }
225
226 QString sql = QStringLiteral( "SELECT id, provider_id, xml, timestamp FROM history" );
227 QStringList whereClauses;
228 if ( !providerId.isEmpty() )
229 {
230 whereClauses.append( QStringLiteral( "provider_id='%1'" ).arg( providerId ) );
231 }
232 if ( start.isValid() )
233 {
234 whereClauses.append( QStringLiteral( "timestamp>='%1'" ).arg( start.toString( QStringLiteral( "yyyy-MM-dd HH:mm:ss" ) ) ) );
235 }
236 if ( end.isValid() )
237 {
238 whereClauses.append( QStringLiteral( "timestamp<='%1'" ).arg( end.toString( QStringLiteral( "yyyy-MM-dd HH:mm:ss" ) ) ) );
239 }
240
241 if ( !whereClauses.empty() )
242 sql += QStringLiteral( " WHERE (" ) + whereClauses.join( QLatin1String( ") AND (" ) ) + ')';
243
244 int nErr;
245 sqlite3_statement_unique_ptr statement = mLocalDB.prepare( sql, nErr );
246
247 while ( nErr == SQLITE_OK && sqlite3_step( statement.get() ) == SQLITE_ROW )
248 {
249 QDomDocument doc;
250 if ( !doc.setContent( statement.columnAsText( 2 ) ) )
251 {
252 QgsDebugError( QStringLiteral( "Cannot read history entry" ) );
253 continue;
254 }
255
257 statement.columnAsText( 1 ),
258 QDateTime::fromString( statement.columnAsText( 3 ), QStringLiteral( "yyyy-MM-dd HH:mm:ss" ) ),
259 QgsXmlUtils::readVariant( doc.documentElement() ).toMap()
260 );
261 entry.id = statement.columnAsInt64( 0 );
262
263 entries.append( entry );
264 }
265 }
266
267 return entries;
268}
269
271{
272 return QgsApplication::qgisSettingsDirPath() + QStringLiteral( "user-history.db" );
273}
274
276{
277 switch ( backend )
278 {
280 {
281 if ( providerId.isEmpty() )
282 runEmptyQuery( QStringLiteral( "DELETE from history;" ) );
283 else
284 runEmptyQuery( QStringLiteral( "DELETE from history WHERE provider_id='%1'" )
285 .arg( providerId ) );
286 break;
287 }
288 }
289 emit historyCleared( backend, providerId );
290 return true;
291}
292
293bool QgsHistoryProviderRegistry::createDatabase( const QString &filename, QString &error )
294{
295 error.clear();
296 if ( !openDatabase( filename, error ) )
297 {
298 QgsDebugError( error );
299 return false;
300 }
301
302 createTables();
303
304 return true;
305}
306
307bool QgsHistoryProviderRegistry::openDatabase( const QString &filename, QString &error )
308{
309 int rc = mLocalDB.open( filename );
310 if ( rc )
311 {
312 error = tr( "Couldn't open the history database: %1" ).arg( mLocalDB.errorMessage() );
313 return false;
314 }
315
316 return true;
317}
318
319void QgsHistoryProviderRegistry::createTables()
320{
321 QString query = qgs_sqlite3_mprintf( "CREATE TABLE history("\
322 "id INTEGER PRIMARY KEY,"\
323 "provider_id TEXT,"\
324 "xml TEXT,"\
325 "timestamp DATETIME);" \
326 "CREATE INDEX provider_index ON history(provider_id);"\
327 "CREATE INDEX timestamp_index ON history(timestamp);"
328 );
329
330 runEmptyQuery( query );
331}
332
333bool QgsHistoryProviderRegistry::runEmptyQuery( const QString &query )
334{
335 if ( !mLocalDB )
336 return false;
337
338 char *zErr = nullptr;
339 int nErr = sqlite3_exec( mLocalDB.get(), query.toUtf8().constData(), nullptr, nullptr, &zErr );
340
341 if ( nErr != SQLITE_OK )
342 {
343 QgsDebugError( zErr );
344 sqlite3_free( zErr );
345 }
346
347 return nErr == SQLITE_OK;
348}
349
HistoryProviderBackend
History provider backends.
Definition: qgis.h:2842
@ LocalProfile
Local profile.
QFlags< HistoryProviderBackend > HistoryProviderBackends
Definition: qgis.h:2847
Abstract base class for objects which track user history (i.e.
virtual QString id() const =0
Returns the provider's unique id, which is used to associate existing history entries with the provid...
static QString qgisSettingsDirPath()
Returns the path to the settings directory in user's home dir.
History provider for operations database queries.
Encapsulates a history entry.
QDateTime timestamp
Entry timestamp.
QString providerId
Associated history provider ID.
long long id
Entry ID.
QVariantMap entry
Entry details.
Contains options for storing history entries.
Qgis::HistoryProviderBackends storageBackends
Target storage backends.
QgsAbstractHistoryProvider * providerById(const QString &id)
Returns the provider with matching id, or nullptr if no matching provider is registered.
bool updateEntry(long long id, const QVariantMap &entry, Qgis::HistoryProviderBackend backend=Qgis::HistoryProviderBackend::LocalProfile)
Updates the existing entry with matching id.
static QString userHistoryDbPath()
Returns the path to user's local history database.
bool clearHistory(Qgis::HistoryProviderBackend backend, const QString &providerId=QString())
Clears the history for the specified backend.
void entryAdded(long long id, const QgsHistoryEntry &entry, Qgis::HistoryProviderBackend backend)
Emitted when an entry is added.
bool addProvider(QgsAbstractHistoryProvider *provider)
Adds a provider to the registry.
bool addEntries(const QList< QgsHistoryEntry > &entries, QgsHistoryProviderRegistry::HistoryEntryOptions options=QgsHistoryProviderRegistry::HistoryEntryOptions())
Adds a list of entries to the history logs.
QgsHistoryProviderRegistry(QObject *parent=nullptr, bool useMemoryDatabase=false)
Creates a new empty history provider registry.
bool removeProvider(const QString &id)
Removes the provider with matching id.
long long addEntry(const QString &providerId, const QVariantMap &entry, bool &ok, QgsHistoryProviderRegistry::HistoryEntryOptions options=QgsHistoryProviderRegistry::HistoryEntryOptions())
Adds an entry to the history logs.
QgsHistoryEntry entry(long long id, bool &ok, Qgis::HistoryProviderBackend backend=Qgis::HistoryProviderBackend::LocalProfile) const
Returns the entry with matching ID, from the specified backend.
QList< QgsHistoryEntry > queryEntries(const QDateTime &start=QDateTime(), const QDateTime &end=QDateTime(), const QString &providerId=QString(), Qgis::HistoryProviderBackends backends=Qgis::HistoryProviderBackend::LocalProfile) const
Queries history entries which occurred between the specified start and end times.
void entryUpdated(long long id, const QVariantMap &entry, Qgis::HistoryProviderBackend backend)
Emitted when an entry is updated.
void addDefaultProviders()
Adds the default history providers to the registry.
QStringList providerIds() const
Returns a list of the registered provider IDs.
void historyCleared(Qgis::HistoryProviderBackend backend, const QString &providerId)
Emitted when the history is cleared for a backend.
History provider for operations performed through the Processing framework.
static QVariantMap removePointerValuesFromMap(const QVariantMap &map)
Removes any raw pointer values from an input map, replacing them with appropriate string values where...
Scoped object for logging of the runtime for a single operation or group of operations.
static QDomElement writeVariant(const QVariant &value, QDomDocument &doc)
Write a QVariant to a QDomElement.
static QVariant readVariant(const QDomElement &element)
Read a QVariant from a QDomElement.
sqlite3_statement_unique_ptr prepare(const QString &sql, int &resultCode) const
Prepares a sql statement, returning the result.
int open(const QString &path)
Opens the database at the specified file path.
QString errorMessage() const
Returns the most recent error message encountered by the database.
Unique pointer for sqlite3 prepared statements, which automatically finalizes the statement when the ...
QString columnAsText(int column) const
Returns the column value from the current statement row as a string.
qlonglong columnAsInt64(int column) const
Gets column value from the current statement row as a long long integer (64 bits).
#define BUILTIN_UNREACHABLE
Definition: qgis.h:5853
#define QgsDebugError(str)
Definition: qgslogger.h:38
QString qgs_sqlite3_mprintf(const char *format,...)
Wraps sqlite3_mprintf() by automatically freeing the memory.