/
qgsspatialiteproviderconnection.cpp
443 lines (412 loc) · 16.8 KB
/
qgsspatialiteproviderconnection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/***************************************************************************
QgsSpatialiteProviderConnection.cpp - QgsSpatialiteProviderConnection
---------------------
begin : 6.8.2019
copyright : (C) 2019 by Alessandro Pasotti
email : elpaso at itopen dot it
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsspatialiteproviderconnection.h"
#include "qgsspatialiteconnection.h"
#include "qgsspatialiteprovider.h"
#include "qgsogrprovider.h"
#include "qgssettings.h"
#include "qgsmessagelog.h"
#include "qgsproviderregistry.h"
#include "qgsapplication.h"
QgsSpatiaLiteProviderConnection::QgsSpatiaLiteProviderConnection( const QString &name )
: QgsAbstractDatabaseProviderConnection( name )
{
setDefaultCapabilities();
// TODO: QGIS 4: move into QgsSettings::Section::Providers group
QgsSettings settings;
settings.beginGroup( QStringLiteral( "SpatiaLite" ) );
settings.beginGroup( QStringLiteral( "connections" ) );
settings.beginGroup( name );
QgsDataSourceUri dsUri;
dsUri.setDatabase( settings.value( QStringLiteral( "sqlitepath" ) ).toString() );
setUri( dsUri.uri() );
}
QgsSpatiaLiteProviderConnection::QgsSpatiaLiteProviderConnection( const QString &uri, const QVariantMap &configuration ):
QgsAbstractDatabaseProviderConnection( uri, configuration )
{
const QRegularExpression removePartsRe { R"raw(\s*sql=\s*|\s*table=""\s*|\([^\)]+\))raw" };
// Cleanup the URI in case it contains other information other than the file path
setUri( QString( uri ).replace( removePartsRe, QString() ) );
setDefaultCapabilities();
}
void QgsSpatiaLiteProviderConnection::store( const QString &name ) const
{
// TODO: QGIS 4: move into QgsSettings::Section::Providers group
QgsSettings settings;
settings.beginGroup( QStringLiteral( "SpatiaLite" ) );
settings.beginGroup( QStringLiteral( "connections" ) );
settings.beginGroup( name );
settings.setValue( QStringLiteral( "sqlitepath" ), pathFromUri() );
}
void QgsSpatiaLiteProviderConnection::remove( const QString &name ) const
{
// TODO: QGIS 4: move into QgsSettings::Section::Providers group
QgsSettings settings;
settings.beginGroup( QStringLiteral( "SpatiaLite" ) );
settings.beginGroup( QStringLiteral( "connections" ) );
settings.remove( name );
}
QString QgsSpatiaLiteProviderConnection::tableUri( const QString &schema, const QString &name ) const
{
const auto tableInfo { table( schema, name ) };
return uri() + QStringLiteral( " table=%1" ).arg( QgsSqliteUtils::quotedIdentifier( name ) );
}
void QgsSpatiaLiteProviderConnection::createVectorTable( const QString &schema,
const QString &name,
const QgsFields &fields,
QgsWkbTypes::Type wkbType,
const QgsCoordinateReferenceSystem &srs,
bool overwrite,
const QMap<QString, QVariant> *options ) const
{
checkCapability( Capability::CreateVectorTable );
if ( ! schema.isEmpty() )
{
QgsMessageLog::logMessage( QStringLiteral( "Schema is not supported by Spatialite, ignoring" ), QStringLiteral( "OGR" ), Qgis::Info );
}
QMap<QString, QVariant> opts { *options };
opts[ QStringLiteral( "layerName" ) ] = QVariant( name );
opts[ QStringLiteral( "update" ) ] = true;
QMap<int, int> map;
QString errCause;
QgsVectorLayerExporter::ExportError errCode = QgsSpatiaLiteProvider::createEmptyLayer(
uri() + QStringLiteral( " table=%1 (geom)" ).arg( QgsSqliteUtils::quotedIdentifier( name ) ),
fields,
wkbType,
srs,
overwrite,
&map,
&errCause,
&opts
);
if ( errCode != QgsVectorLayerExporter::ExportError::NoError )
{
throw QgsProviderConnectionException( QObject::tr( "An error occurred while creating the vector layer: %1" ).arg( errCause ) );
}
}
void QgsSpatiaLiteProviderConnection::dropVectorTable( const QString &schema, const QString &name ) const
{
checkCapability( Capability::DropVectorTable );
if ( ! schema.isEmpty() )
{
QgsMessageLog::logMessage( QStringLiteral( "Schema is not supported by Spatialite, ignoring" ), QStringLiteral( "OGR" ), Qgis::Info );
}
QString errCause;
QgsSqliteHandle *hndl = QgsSqliteHandle::openDb( pathFromUri() );
if ( !hndl )
{
errCause = QObject::tr( "Connection to database failed" );
}
if ( errCause.isEmpty() )
{
sqlite3 *sqlite_handle = hndl->handle();
int ret;
if ( !gaiaDropTable( sqlite_handle, name.toUtf8().constData() ) )
{
// unexpected error
errCause = QObject::tr( "Unable to delete table %1\n" ).arg( name );
QgsSqliteHandle::closeDb( hndl );
}
else
{
// TODO: remove spatial indexes?
// run VACUUM to free unused space and compact the database
ret = sqlite3_exec( sqlite_handle, "VACUUM", nullptr, nullptr, nullptr );
if ( ret != SQLITE_OK )
{
QgsDebugMsg( QStringLiteral( "Failed to run VACUUM after deleting table on database %1" )
.arg( pathFromUri() ) );
}
QgsSqliteHandle::closeDb( hndl );
}
}
if ( ! errCause.isEmpty() )
{
throw QgsProviderConnectionException( QObject::tr( "Error deleting vector/aspatial table %1: %2" ).arg( name ).arg( errCause ) );
}
}
void QgsSpatiaLiteProviderConnection::renameVectorTable( const QString &schema, const QString &name, const QString &newName ) const
{
checkCapability( Capability::RenameVectorTable );
if ( ! schema.isEmpty() )
{
QgsMessageLog::logMessage( QStringLiteral( "Schema is not supported by Spatialite, ignoring" ), QStringLiteral( "OGR" ), Qgis::Info );
}
// TODO: maybe an index?
QString sql( QStringLiteral( "ALTER TABLE %1 RENAME TO %2" )
.arg( QgsSqliteUtils::quotedIdentifier( name ),
QgsSqliteUtils::quotedIdentifier( newName ) ) );
executeSqlDirect( sql );
sql = QStringLiteral( "UPDATE geometry_columns SET f_table_name = lower(%2) WHERE lower(f_table_name) = lower(%1)" )
.arg( QgsSqliteUtils::quotedString( name ),
QgsSqliteUtils::quotedString( newName ) );
executeSqlDirect( sql );
sql = QStringLiteral( "UPDATE layer_styles SET f_table_name = lower(%2) WHERE f_table_name = lower(%1)" )
.arg( QgsSqliteUtils::quotedString( name ),
QgsSqliteUtils::quotedString( newName ) );
try
{
executeSqlDirect( sql );
}
catch ( QgsProviderConnectionException &ex )
{
QgsDebugMsgLevel( QStringLiteral( "Warning: error while updating the styles, perhaps there are no styles stored in this GPKG: %1" ).arg( ex.what() ), 4 );
}
}
QList<QList<QVariant>> QgsSpatiaLiteProviderConnection::executeSql( const QString &sql ) const
{
checkCapability( Capability::ExecuteSql );
return executeSqlPrivate( sql );
}
void QgsSpatiaLiteProviderConnection::vacuum( const QString &schema, const QString &name ) const
{
Q_UNUSED( name )
checkCapability( Capability::Vacuum );
if ( ! schema.isEmpty() )
{
QgsMessageLog::logMessage( QStringLiteral( "Schema is not supported by Spatialite, ignoring" ), QStringLiteral( "OGR" ), Qgis::Info );
}
executeSqlDirect( QStringLiteral( "VACUUM" ) );
}
void QgsSpatiaLiteProviderConnection::createSpatialIndex( const QString &schema, const QString &name, const QgsAbstractDatabaseProviderConnection::SpatialIndexOptions &options ) const
{
Q_UNUSED( name )
checkCapability( Capability::Vacuum );
if ( ! schema.isEmpty() )
{
QgsMessageLog::logMessage( QStringLiteral( "Schema is not supported by Spatialite, ignoring" ), QStringLiteral( "OGR" ), Qgis::Info );
}
executeSqlPrivate( QStringLiteral( "SELECT CreateSpatialIndex(%1, %2)" ).arg( QgsSqliteUtils::quotedString( name ),
QgsSqliteUtils::quotedString( ( options.geometryColumnName ) ) ) );
}
bool QgsSpatiaLiteProviderConnection::spatialIndexExists( const QString &schema, const QString &name, const QString &geometryColumn ) const
{
checkCapability( Capability::CreateSpatialIndex );
if ( ! schema.isEmpty() )
{
QgsMessageLog::logMessage( QStringLiteral( "Schema is not supported by Spatialite, ignoring" ), QStringLiteral( "OGR" ), Qgis::Info );
}
const QList<QVariantList> res = executeSqlPrivate( QStringLiteral( "SELECT spatial_index_enabled FROM geometry_columns WHERE lower(f_table_name) = lower(%1) AND lower(f_geometry_column) = lower(%2)" )
.arg( QgsSqliteUtils::quotedString( name ),
QgsSqliteUtils::quotedString( geometryColumn ) ) );
return !res.isEmpty() && !res.at( 0 ).isEmpty() && res.at( 0 ).at( 0 ).toInt() == 1;
}
QList<QgsSpatiaLiteProviderConnection::TableProperty> QgsSpatiaLiteProviderConnection::tables( const QString &schema, const TableFlags &flags ) const
{
checkCapability( Capability::Tables );
if ( ! schema.isEmpty() )
{
QgsMessageLog::logMessage( QStringLiteral( "Schema is not supported by Spatialite, ignoring" ), QStringLiteral( "OGR" ), Qgis::Info );
}
QList<QgsSpatiaLiteProviderConnection::TableProperty> tableInfo;
QString errCause;
try
{
QgsSpatiaLiteConnection connection( pathFromUri() );
QgsSpatiaLiteConnection::Error err = connection.fetchTables( true );
if ( err != QgsSpatiaLiteConnection::NoError )
{
QString msg;
switch ( err )
{
case QgsSpatiaLiteConnection::NotExists:
msg = QObject::tr( "Database does not exist" );
break;
case QgsSpatiaLiteConnection::FailedToOpen:
msg = QObject::tr( "Failed to open database" );
break;
case QgsSpatiaLiteConnection::FailedToCheckMetadata:
msg = QObject::tr( "Failed to check metadata" );
break;
case QgsSpatiaLiteConnection::FailedToGetTables:
msg = QObject::tr( "Failed to get list of tables" );
break;
default:
msg = QObject::tr( "Unknown error" );
break;
}
QString msgDetails = connection.errorMessage();
if ( !msgDetails.isEmpty() )
{
msg = QStringLiteral( "%1 (%2)" ).arg( msg, msgDetails );
}
throw QgsProviderConnectionException( QObject::tr( "Error fetching table information for connection: %1" ).arg( pathFromUri() ) );
}
else
{
const QString connectionInfo = QStringLiteral( "dbname='%1'" ).arg( QString( connection.path() ).replace( '\'', QLatin1String( "\\'" ) ) );
QgsDataSourceUri dsUri( connectionInfo );
// Need to store it here because provider (and underlying gaia library) returns views as spatial table if they have geometries
QStringList viewNames;
for ( const auto &tn : executeSqlPrivate( QStringLiteral( "SELECT name FROM sqlite_master WHERE type = 'view'" ) ) )
{
viewNames.push_back( tn.first().toString() );
}
// Another weirdness: table names are converted to lowercase when out of spatialite gaia functions, let's get them back to their real case here,
// may need LAUNDER on open, but let's try to make it consistent with how GPKG works.
QgsStringMap tableNotLowercaseNames;
for ( const auto &tn : executeSqlPrivate( QStringLiteral( "SELECT name FROM sqlite_master WHERE LOWER(name) != name" ) ) )
{
const QString tName { tn.first().toString() };
tableNotLowercaseNames.insert( tName.toLower(), tName );
}
const auto constTables = connection.tables();
for ( const QgsSpatiaLiteConnection::TableEntry &entry : constTables )
{
QString tableName { tableNotLowercaseNames.value( entry.tableName, entry.tableName ) };
dsUri.setDataSource( QString(), tableName, entry.column, QString(), QString() );
QgsSpatiaLiteProviderConnection::TableProperty property;
property.setTableName( tableName );
// Create a layer and get information from it
std::unique_ptr< QgsVectorLayer > vl = qgis::make_unique<QgsVectorLayer>( dsUri.uri(), QString(), QLatin1String( "spatialite" ) );
if ( vl->isValid() )
{
if ( vl->isSpatial() )
{
property.setGeometryColumnCount( 1 );
property.setGeometryColumn( entry.column );
property.setFlag( QgsSpatiaLiteProviderConnection::TableFlag::Vector );
property.setGeometryColumnTypes( {{ vl->wkbType(), vl->crs() }} );
}
else
{
property.setGeometryColumnCount( 0 );
property.setGeometryColumnTypes( {{ QgsWkbTypes::NoGeometry, QgsCoordinateReferenceSystem() }} );
property.setFlag( QgsSpatiaLiteProviderConnection::TableFlag::Aspatial );
}
if ( viewNames.contains( tableName ) )
{
property.setFlag( QgsSpatiaLiteProviderConnection::TableFlag::View );
}
tableInfo.push_back( property );
}
else
{
QgsDebugMsgLevel( QStringLiteral( "Layer is not valid: %1" ).arg( dsUri.uri() ), 2 );
}
}
}
}
catch ( QgsProviderConnectionException &ex )
{
errCause = ex.what();
}
if ( ! errCause.isEmpty() )
{
throw QgsProviderConnectionException( QObject::tr( "Error listing tables from %1: %2" ).arg( pathFromUri() ).arg( errCause ) );
}
// Filters
if ( flags )
{
tableInfo.erase( std::remove_if( tableInfo.begin(), tableInfo.end(), [ & ]( const QgsAbstractDatabaseProviderConnection::TableProperty & ti )
{
return !( ti.flags() & flags );
} ), tableInfo.end() );
}
return tableInfo ;
}
QIcon QgsSpatiaLiteProviderConnection::icon() const
{
return QgsApplication::getThemeIcon( QStringLiteral( "mIconSpatialite.svg" ) );
}
void QgsSpatiaLiteProviderConnection::setDefaultCapabilities()
{
mCapabilities =
{
Capability::Tables,
Capability::CreateVectorTable,
Capability::DropVectorTable,
Capability::RenameVectorTable,
Capability::Vacuum,
Capability::Spatial,
Capability::TableExists,
Capability::ExecuteSql,
Capability::CreateSpatialIndex,
Capability::SpatialIndexExists,
};
}
QList<QVariantList> QgsSpatiaLiteProviderConnection::executeSqlPrivate( const QString &sql ) const
{
QString errCause;
QList<QVariantList> results;
gdal::ogr_datasource_unique_ptr hDS( GDALOpenEx( pathFromUri().toUtf8().constData(), GDAL_OF_VECTOR | GDAL_OF_UPDATE, nullptr, nullptr, nullptr ) );
if ( hDS )
{
OGRLayerH ogrLayer( GDALDatasetExecuteSQL( hDS.get(), sql.toUtf8().constData(), nullptr, nullptr ) );
if ( ogrLayer )
{
gdal::ogr_feature_unique_ptr fet;
QgsFields fields;
while ( fet.reset( OGR_L_GetNextFeature( ogrLayer ) ), fet )
{
QVariantList row;
// Try to get the right type for the returned values
if ( fields.isEmpty() )
{
fields = QgsOgrUtils::readOgrFields( fet.get(), QTextCodec::codecForName( "UTF-8" ) );
}
if ( ! fields.isEmpty() )
{
QgsFeature f { QgsOgrUtils::readOgrFeature( fet.get(), fields, QTextCodec::codecForName( "UTF-8" ) ) };
const QgsAttributes &constAttrs { f.attributes() };
for ( int i = 0; i < constAttrs.length(); i++ )
{
row.push_back( constAttrs.at( i ) );
}
}
else // Fallback to strings
{
for ( int i = 0; i < OGR_F_GetFieldCount( fet.get() ); i++ )
{
row.push_back( QVariant( QString::fromUtf8( OGR_F_GetFieldAsString( fet.get(), i ) ) ) );
}
}
results.push_back( row );
}
GDALDatasetReleaseResultSet( hDS.get(), ogrLayer );
}
errCause = CPLGetLastErrorMsg( );
}
else
{
errCause = QObject::tr( "There was an error opening Spatialite %1!" ).arg( pathFromUri() );
}
if ( ! errCause.isEmpty() )
{
throw QgsProviderConnectionException( QObject::tr( "Error executing SQL %1: %2" ).arg( sql ).arg( errCause ) );
}
return results;
}
bool QgsSpatiaLiteProviderConnection::executeSqlDirect( const QString &sql ) const
{
sqlite3_database_unique_ptr database;
int result = database.open( pathFromUri() );
if ( result != SQLITE_OK )
{
throw QgsProviderConnectionException( QObject::tr( "Error executing SQL %1: %2" ).arg( sql ).arg( database.errorMessage() ) );
}
QString errorMessage;
result = database.exec( sql, errorMessage );
if ( result != SQLITE_OK )
{
throw QgsProviderConnectionException( QObject::tr( "Error executing SQL %1: %2" ).arg( sql ).arg( errorMessage ) );
}
return true;
}
QString QgsSpatiaLiteProviderConnection::pathFromUri() const
{
const QgsDataSourceUri dsUri( uri() );
return dsUri.database();
}